我有一個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,保持應用程序退出。有人知道我能做些什麼嗎?謝謝。
可能重複【JAVA /擺動:正確的行動採取在關閉窗口】(http://stackoverflow.com/questions/5540354/ java-swing-the-right-action-to-upon-closing-closing-windows) – 2011-05-17 19:52:20