2016-11-04 182 views
1
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并保持框架打开。JFrame关闭对话框

+0

参见[关闭应用程序(HTTPS:/ /tips4java.wordpress.com/2009/05/01/closing-an-application/)以了解关于此主题的更多信息。 – camickr

回答

2

你需要做三件事情:

  1. 设置主应用程序框架上做密切什么。

frame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);

  • 注册一个WindowListener侦听到windowClosing事件。
  •  
    frame.addWindowListener(new WindowAdapter() { 
        public void windowClosing(WindowEvent e) { 
         maybeExit(); // Will not return if user clicks yes. 
         super.windowClosing(e); 
        } 
    }); 
    
  • 编写代码以有条件地调用System.exit如果用户确认他们希望退出应用程序。
  •  
    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); 
        } 
    } 
    
    +0

    我不会推荐使用'System.exit'。最好放置该帧,并且在放置最后一帧时,JVM将自动关闭。 –

    +0

    @Jaroslaw:如果框架的默认关闭操作被设置为EXIT_ON_CLOSE,那不仅仅是这种情况吗? – Adamski

    +0

    据我记得,默认操作是'HIDE_ON_CLOSE'。这完全取决于OP的需求。我会说处理更安全,因为有一天你添加了另一个框架,你想在关闭第一个框架后保持打开状态,结果你需要改变现有的代码。 –

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

    对不起,我有点乱括号使用,会清理一下后...