【问题标题】:How can I stop the closing of a Java application如何停止关闭 Java 应用程序
【发布时间】:2015-12-31 07:03:13
【问题描述】:

我有一个 Java 桌面应用程序,我希望当用户选择退出时弹出一个窗口,询问他是否要继续关闭应用程序。我知道如何让窗口出现并阅读用户的响应,但我需要知道如何阻止应用程序关闭(类似于System.close().cancel())。

这可能吗?

【问题讨论】:

标签: java swing user-interface windowlistener


【解决方案1】:

是的,这是可能的。

调用setDefaultCloseOperation(DO_NOTHING_ON_CLOSE)后,添加WindowListenerWindowAdapter,并在windowClosing(WindowEvent)方法中弹出JOptionPane

int result = JOptionPane.showConfirmDialog(frame, "Exit the application?");
if (result==JOptionPane.OK_OPTION) {
    System.exit(0);     
}

【讨论】:

    【解决方案2】:

    您可以添加一个窗口侦听器。 (注意:WindowAdapterjava.awt.event 包中)

    myframe.addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent e) {
            // do something
        }
    });
    

    【讨论】:

      【解决方案3】:

      setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE); 设置为您的JFrame 或JDialog 后,添加一个windows 监听器:

      addWindowListener(new WindowAdapter() {
              @Override
              public void windowClosing(WindowEvent arg0) {
                  int result = JOptionPane.showConfirmDialog((Component) null, "Do u really want to exit ?!",
                          "Confirmation", JOptionPane.YES_NO_OPTION);
                  if (result == 0) {
                      System.exit(0);
                  } else {
      
                  }
              }
          });
      

      【讨论】:

        【解决方案4】:

        在您的JFrame 上,您必须设置一个defaultCloseOperation

        JFrame.setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        

        然后将弹出窗口的关闭操作设置为EXIT_ON_CLOSE

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2015-07-01
          • 1970-01-01
          • 1970-01-01
          • 2018-07-17
          • 2015-06-02
          • 1970-01-01
          • 2015-07-03
          相关资源
          最近更新 更多