簡體   English   中英

關閉Java的JFrame退出

[英]JFrame Exit on close Java

我不知道如何使用此代碼:

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

使用x按鈕關閉程序。

你需要這條線

frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

因為按下X按鈕時JFrame的默認行為相當於

frame.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);

所以幾乎所有時候你都需要在創建JFrame時手動添加該行

我目前在WindowConstants引用常量,如WindowConstants.EXIT_ON_CLOSE而不是直接在JFrame聲明的相同常量,因為先前反映的意圖更好。

如果你沒有它,JFrame將被處理掉。 框架將關閉,但應用程序將繼續運行。

調用setDefaultCloseOperation(EXIT_ON_CLOSE)正是這樣做的。 當應用程序從操作系統收到關閉窗口事件時,它會導致應用程序退出。 按窗口上的關閉(X)按鈕會導致操作系統生成關閉窗口事件並將其發送到Java應用程序。 關閉窗口事件由Java應用程序中的AWT事件循環處理,該循環將退出應用程序以響應事件。

如果不調用此方法,則AWT事件循環可能不會退出應用程序以響應關閉窗口事件,但會使其在后台運行。

我花了很多時間通過互聯網尋找一個優雅的解決方案。 通常情況下,我發現了許多相互矛盾的信息。

我終於結束了:

  1. 不要使用EXIT_ON_CLOSE因為這會留下資源;
  2. 在JFrame初始化中使用以下內容:

     setDefaultCloseOperation(DISPOSE_ON_CLOSE); 
  3. 真正的發現是如何將窗口消息實際分派給JFrame。 作為示例,作為退出應用程序的JMenuItem的一部分,使用以下函數,其中函數getFrame()返回對JFrame的引用:

     public class AppMenuFileExit extends JMenuItem implements ActionListener { // do your normal menu item code here @Override public void actionPerformed(ActionEvent e) { WindowEvent we; we = new WindowEvent((Window) App.getFrame(), WindowEvent.WINDOW_CLOSING); App.getFrame().dispatchEvent(we); } } 

    JFrame是Window的子類,因此可以為此目的轉換為Window。

  4. 並且,在JFrame類中使用以下內容來處理Window消息:

     public class AppFrame extends JFrame implements WindowListener { // Do all the things you need to for the class @Override public void windowOpened(WindowEvent e) {} @Override public void windowClosing(WindowEvent e) {/* can do cleanup here if necessary */} @Override public void windowClosed(WindowEvent e) { dispose(); System.exit(0); } @Override public void windowActivated(WindowEvent e) {} @Override public void windowDeactivated(WindowEvent e) {} @Override public void windowDeiconified(WindowEvent e) {} @Override public void windowIconified(WindowEvent e) {} } 

如果您使用的是Frame(Class Extends Frame),那么您將無法獲得

frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE)

以下代碼適用於我:

System.exit(home.EXIT_ON_CLOSE);

this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

對於Class Extends Frame來說,這對我有用

如果您不擴展JFrame並在變量中使用JFrame本身,則可以使用:

frame.dispose();
System.exit(0);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM