How do I close a JDialog window using a JButton?

你。 提交于 2019-12-24 12:18:16

问题


I've tried a bunch of different ways to close the window, but since you can't send additional parameters to to Action Listener method I can't dispose the frame due to a pointer exception for the frame.

This is my current code.

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;

public class errorRequiredFieldMissing extends JDialog{
JLabel error;
JButton exit;
public static JFrame frame;
public errorRequiredFieldMissing() {
    super(frame, "Error", true);
    setLayout(new FlowLayout());
    error = new JLabel ("Required field or fields missing, please fill in all fields to continue.");
    add(error);
    exit = new JButton ("OK");
    add(exit);
    System.out.println("chk1");
    exit.addActionListener(new ActionListener(){

        public void actionPerformed(ActionEvent event){
            System.out.println("chk2");
            frame.dispose();
        }
    }); 
}
public static void method2(){
    System.out.print("success!");
    errorRequiredFieldMissing gui = new errorRequiredFieldMissing();
    gui.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
    gui.setSize(400,100);
    gui.setLocation(300,25);
    gui.setVisible(true);
}
}

回答1:


try this way:

exit.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
        exitActionPerformed(evt);
    }
});

and then

 private void exitActionPerformed(java.awt.event.ActionEvent evt) {
        this.dispose();
    }


来源:https://stackoverflow.com/questions/8003892/how-do-i-close-a-jdialog-window-using-a-jbutton

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!