如何使用JButton关闭JDialog窗口?

时间:2011-11-04 01:13:20

标签: jframe jbutton jdialog

我尝试了一些不同的方法来关闭窗口,但是因为你无法向Action Listener方法发送其他参数,所以由于帧的指针异常,我无法处理帧。

这是我目前的代码。

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 个答案:

答案 0 :(得分:2)

尝试这种方式:

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

然后

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