1
我试过了一堆不同的方法来关闭窗口,但由于您无法将其他参数发送到Action Listener方法,所以我无法处理该帧,因为该帧的指针异常。如何使用JButton关闭一个JDialog窗口?
这是我现在的代码。
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);
}
}
非常完美谢谢!但为什么这个工作,而不是我所尝试的? – user1028872
原因**帧**没有初始化(这就是为什么你得到一个空指针异常)。实际上你可以保持你的代码与你发布的方式完全一样,只需将第8行改为'public static JFrame frame = new JFrame();' –