问题
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