关闭对话框的JFrame

时间:2016-11-04 15:26:42

标签: java swing

public static int clickOnExit() {
    int dialogButton=JOptionPane.YES_NO_OPTION;
    JOptionPane.showConfirmDialog(null, sharedConstants.exitMessage,"Confirm",dialogButton);
    if(dialogButton == JOptionPane.YES_OPTION){return JFrame.EXIT_ON_CLOSE;}
    else{return JFrame.DO_NOTHING_ON_CLOSE;}

}

确认(是)它可以工作,但我不确定取消选项是否正确解决。我只想取消JOptionPane并保持框架打开。

2 个答案:

答案 0 :(得分:2)

你需要做三件事:

  1. 将主应用程序框架设置为关闭时不执行任何操作。
  2. frame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);

    1. 注册一个监听WindowListener活动的windowClosing
    2. frame.addWindowListener(new WindowAdapter() {
          public void windowClosing(WindowEvent e) {
              maybeExit(); // Will not return if user clicks yes.
              super.windowClosing(e);
          }
      });
      
      1. 如果用户确认他们希望退出申请,请编写有条件调用System.exit的代码。
      2. private void maybeExit() {
            int yesNo = JOptionPane.showConfirmDialog(this, "Are you sure you wish to exit?", "Confirm", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
        
            if (yesNo == JOptionPane.YES_OPTION) {
                System.exit(0);
            }
        }
        

答案 1 :(得分:0)

有些建议很有用。我用这种方式解决了它:

        frame.addWindowListener(new java.awt.event.WindowAdapter() {
        @Override
        public void windowClosing(java.awt.event.WindowEvent windowEvent) {
            if (HandlingDialogBox.clickOnExit(frame) == 0) {
                frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            } else {
                frame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
            }
        }

    });

}

 public static int clickOnExit(final JFrame frame) {
     return JOptionPane.showConfirmDialog(frame,sharedConstants.exitMessage,"Confirm",
     JOptionPane.YES_NO_OPTION);
} 

对于有点凌乱的括号使用,请稍后清理它......