如何防止JFrame窗体关闭?

3

我想在我的项目中防止意外关闭。我使用JFrame表单作为主页。当我点击主页窗口的关闭按钮时,我在Yes选项中放置了Exit代码。我想停止关闭,当我点击No选项时。有没有办法。这是我的代码。我正在使用Netbeans 7.3

 private void formWindowClosing(java.awt.event.WindowEvent evt) {                                   
 int i= JOptionPane.showConfirmDialog(null, "Are you sure to exit?");
    if (i == JOptionPane.YES_OPTION) {
        System.exit(0);
    } else{
        new Home().setVisible(true);

    }
}

我不认为它是这样的。:( 我可以使用按钮的动作事件来执行相同的过程。我应该使用哪个事件? - Dilini
你能解释一下你当前的代码有什么问题吗? - Duncan Jones
错误就是当我点击“否”或“取消”而不是“是”,主窗口仍然关闭。 - Dilini
"new Home().setVisible(true)" 创建了一个新的 Home 对象,然后调用了它的 setVisible 方法。这对创建窗口并关闭的 Home 对象没有影响。事件应该在现有的 Home 对象上调用。你应该能够写成 "this.setVisible(true)"。 - Zweibieren
2个回答

6
如何处理呢?
class MyGUI extends JFrame {

    public MyGUI() {
        setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);// <- don't close window 
                                                             // when [X] is pressed

        final MyGUI gui = this;
        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                int i = JOptionPane.showConfirmDialog(gui,
                        "Are you sure to exit?", "Closing dialog",
                        JOptionPane.YES_NO_OPTION);
                if (i == JOptionPane.YES_OPTION) {
                    System.exit(0);
                }
            }
        });

        setSize(200, 200);
        setVisible(true);
    }

    //demo
    public static void main(String[] args) {
        new MyGUI();
    }
}

1
@user2867987 frame 不是一个包,而是你想要防止关闭的 JFrame 实例。你可以将这段代码放在你的 JFrame 类构造函数/初始化中,并将 frame 替换为 this 或者直接省略。 - Pshemo
@user2867987,我在我的示例中添加了更多的上下文。 - Pshemo
我也尝试过编辑。但是我仍然不知道应该把最终的JFrame框架放在哪里:frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);// <- 防止关闭 frame.addWindowListener(new WindowAdapter() {}); - Dilini
@user2867987,我不确定你是如何使用它的。就像我之前告诉过你的那样,frame保存了你想要执行确认测试的主窗口的引用,所以如果你想把这段代码放在代表主窗口的类中,那么只需删除frame(你可以使用this代替或者跳过它)。 - Pshemo
@user2867987 请编辑您的问题并包含您现在正在使用的代码。 - Pshemo
显示剩余3条评论

1
您可以像这样简单地完成此操作:

您可以像这样简单地完成此操作

Integer opt =  JOptionPane.showConfirmDialog(null, "This application cannot continue without login to the database\n Are you sure you need to exit...?", "Application X", JOptionPane.YES_NO_OPTION);
if(opt== JOptionPane.NO_OPTION){
    this.setVisible(true);
}else{
    System.exit(0);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接