2011-05-17 97 views
2

我有一個Java應用程序,打開一個JFrame並繪製它。問題是,當我嘗試退出應用程序時,通過關閉JFrame窗口(在我的Mac或PC上)或從菜單欄(在我的Mac上)選擇退出,應用程序就會掛起。有趣的是,這種行爲僅在我將JButton添加到我的應用程序後纔出現。這裏是我的 代碼:Java Swing應用程序不會退出

public class MyApplicationFrame extends JFrame { 

public MyApplicationFrame(MyApplicationLogic l) { 
    super(); 
    this.appLogic = l; 
    try { 
     SwingUtilities.invokeAndWait(new Runnable() { 
      @Override public void run() { 
       createAndShowGUI(); 
      } 
     }); 
    } 
    catch(InterruptedException e) { } 
    catch(InvocationTargetException e) { } 

    g = getGraphics(); 
} 

public void paint() { ... } 

private void createAndShowGUI() { 
    final Container c = getContentPane(); 
    c.setLayout(new java.awt.FlowLayout()); 

    final JButton startButton = new JButton("Start"); 
      // if I comment out these lines with the startButton, everything works 
    startButton.addActionListener(new ActionListener() { 
     @Override public void actionPerformed(ActionEvent event) { 
      appLogic.run(); 
      c.remove(startButton); 
     } 
    }); 
    c.add(startButton); 

    setSize(FRAME_SIZE, FRAME_SIZE); 
    setVisible(true); 
    } 
} 

在我的應用程序邏輯,我有以下方法:

public void run() { 
    appFrame.paint(); 
    getNextState(); 

    // then I added the following code to try and help solve this problem 
    System.err.println(java.awt.Toolkit.getDefaultToolkit().getSystemEventQueue().peekEvent());   
} 

對System.err的流輸出看起來是這樣的:

null 
null 
null 
null 
null 
// here's where I typed command-Q 
java.awt.event.MouseEvent[MOUSE_CLICKED,(210,45),absolute(210,67),button=1,modifiers=Button1,clickCount=1] on frame0 
java.awt.event.MouseEvent[MOUSE_CLICKED,(210,45),absolute(210,67),button=1,modifiers=Button1,clickCount=1] on frame0 
java.awt.event.MouseEvent[MOUSE_CLICKED,(210,45),absolute(210,67),button=1,modifiers=Button1,clickCount=1] on frame0

我在應用程序中沒有任何鼠標監聽器(儘管我假設JButton對象有一個),並且我沒有註冊除JButton上的ActionListener以外的任何監聽器。我沒有碰到鼠標。但我認爲這是所有這些MouseEvents,保持應用程序退出。有人知道我能做些什麼嗎?謝謝。

+0

可能重複【JAVA /擺動:正確的行動採取在關閉窗口】(http://stackoverflow.com/questions/5540354/ java-swing-the-right-action-to-upon-closing-closing-windows) – 2011-05-17 19:52:20

回答

3

告訴JFrame關閉時退出JVM。

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

默認情況下,關閉時JFrame不做任何事情。甚至沒有退出JVM。

5

createAndShowGUI()方法添加

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

+0

我不認爲我一定很清楚 - 當我嘗試退出時程序掛起。根據Java文檔,它看起來像**假設**在AWT事件隊列爲空之前不會退出,但是當我要求程序退出時,出於某種原因,無數個MouseEvent突然莫名其妙地出現在事件隊列中。 – jay 2011-05-17 21:54:53

+0

也顯式設置'frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);'沒有區別。謝謝。 – jay 2011-05-17 21:56:20

0

我的解決方案是創建一個額外的線程,以便我可以明確地將應用程序邏輯處理與事件處理分開。我不知道這是爲什麼起作用,但似乎已經解決了所有問題。

0

下面的代碼添加到構造函數MyApplicationFrame

this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);