2009-12-22 96 views

回答

73

如果你想要在JFrame關閉您的應用程序終止,使用

setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE) 

,而不是

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

documentation

  • DO_NOTHING_ON_CLOSE(在WindowCons中定義tants):不要做任何事情;要求程序處理已註冊WindowListener對象的windowClosing方法中的操作。
  • HIDE_ON_CLOSE(在WindowConstants中定義):在調用任何註冊的WindowListener對象後自動隱藏框架。
  • DISPOSE_ON_CLOSE(在WindowConstants中定義):在調用任何已註冊的WindowListener對象後,自動隱藏並處理該幀。
  • EXIT_ON_CLOSE(在JFrame中定義):使用系統退出方法退出應用程序。僅在應用程序中使用它。

這是我的回答澄清這個問題之前,仍然可能是有用的:

您可以在JFrame使用setVisible(false),如果你想再次顯示相同的幀。
否則請致電dispose()remove all of the native screen resources

+0

謝謝,但我關閉窗口右上角的關閉按鈕。它並不使用setVisible(false),而必須停止該線程。 – Keating 2009-12-22 06:32:56

+0

我想我必須重寫一些主題,我不知道哪個主題,但我相信它不是關閉的主題。 – Keating 2009-12-22 06:34:50

+0

我不確定你試圖達到什麼目的,你能否編輯你的問題並添加一些關於你想要做什麼以及哪些不起作用的信息? – 2009-12-22 06:39:54

3

它有幫助嗎?

import java.awt.BorderLayout; 

import javax.swing.JFrame; 
import javax.swing.JLabel; 
import javax.swing.JPanel; 
import javax.swing.SwingUtilities; 

public class TwoJFrames { 
    public static void main(String[] args) { 
     int nb = 4; 
     if (args != null && args.length > 0) { 
      nb = Integer.parseInt(args[0]); 
     } 

     final int frameCount = nb; 
     SwingUtilities.invokeLater(new Runnable() { 
      public void run() { 
       for (int i = 0; i < frameCount; i++) { 
        JFrame frame = new JFrame("Frame number " + i); 
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); 
        JPanel p = new JPanel(new BorderLayout()); 
        p.add(new JLabel("Click on the corner to close..."), BorderLayout.CENTER); 
        frame.setContentPane(p); 
        frame.setSize(200, 200); 
        frame.setLocation(100 + 20 * i, 100 + 20 * i); 
        frame.setVisible(true); 
       } 
      } 
     }); 

    } 
} 
+1

這很有用,謝謝! – Keating 2009-12-22 07:32:33