【问题标题】:How do I close a JDialog window using a JButton?如何使用 JButton 关闭 JDialog 窗口?
【发布时间】:2011-12-21 16:17:37
【问题描述】:

我尝试了很多不同的方法来关闭窗口,但是由于您无法将其他参数发送到 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);
}
}

【问题讨论】:

    标签: jframe jbutton jdialog


    【解决方案1】:

    试试这个方法:

    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();
        }
    

    【讨论】:

    • 工作得很好,谢谢!但是为什么这行得通,而不是我尝试过的?
    • 导致 frame 未初始化(这就是您收到空指针异常的原因)。实际上,您可以保持您的代码与您发布的方式完全相同,只需将第 8 行更改为 public static JFrame frame = new JFrame();
    猜你喜欢
    • 1970-01-01
    • 2013-06-27
    • 2011-03-08
    • 2010-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-03
    相关资源
    最近更新 更多