【问题标题】:Java making confirming exitJava 确认退出
【发布时间】:2011-10-08 18:56:19
【问题描述】:

我有一个应用程序。我需要这样做,当用户单击关闭按钮时,会出现确认(就像 javascript 确认对话框一样),“你确定吗”?我在 Netbeans 中使用 Swing 可视化编辑器,并且在关闭窗口时使用侦听器。但我做不到。有什么帮助吗?

【问题讨论】:

  • 请先搜索论坛,因为这个问题已经被问了无数次了。例如,how-can-a-swing-windowlistener-veto-jframe-closing。您还说您正在使用 WindowListner (正确的方法),“但我做不到” - 但是不要向我们展示您尝试过的内容。请这样做,否则我们无法告诉您您做错了什么。
  • @HovercraftFullOfEels 当时我无法为我的查询找到正确的关键字。感谢您的建议...
  • 不客气。同样,如果在查看链接或类似链接后您仍然遇到问题,请向我们展示您的代码并告诉我们有关它如何不工作的任何细节,例如错误消息或错误行为。
  • @HovercraftFullOfEels 实际上我试图用右上角的退出图标来实现确认。如果它是一个按钮,就没有问题。但是我怎样才能得到那个退出图标的参考。这就是为什么我没有写任何代码...

标签: java swing events


【解决方案1】:

试试这个代码:

jj4.addActionListener(new ActionListener()  // jj4-button's reference to implement exit
    {
        public void actionPerformed(ActionEvent ae)
        {
            if(!jtextarea.getText().equals("") && !jtextarea.getText().equals(fileContent))
            {
                if(fileName == null)
                {
                    //this method have 3 options (1 = YES, 2 = NO, 3 = Cancel)
                    option = JOptionPane.showConfirmDialog(null,"Do you want to save the changes ??");
                    if(option == 0)
                    {
                        //to save the text into file
                        saveAs();
                        System.exit(0);
                    }
                    if(option == 1)
                    {
                        //to exit the program without saving
                        System.exit(0);
                    }
                }
                else
                {
                    option = JOptionPane.showConfirmDialog(null,"Do you want to save the changes ??");
                    if(option == 0)
                    {
                        save();
                        System.exit(0);
                    }
                    if(option == 1)
                    {
                        System.exit(0);
                    }
                }
            }
            else
            {
                System.exit(0);
            }
        }
    });

【讨论】:

  • 不要使用幻数! JOptionPane 已定义变量来检查是、否和取消。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-02-15
  • 1970-01-01
  • 2014-09-09
  • 2011-04-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多