2016-11-04 181 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); 
    } 
    

    對不起,我有點亂括號使用,會清理一下後...