【发布时间】:2014-07-10 20:24:50
【问题描述】:
我有一个 Java 应用程序,它打开一个 JFrame 并在其中绘制。问题是当我尝试退出应用程序时,通过关闭 JFrame 窗口(在我的 Mac 或 PC 上)或从菜单栏中选择退出(在我的 Mac 上),应用程序只是挂起。有趣的是,这种行为仅在我将 JButton 添加到我的应用程序后才出现。这是我的 代码:
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 流上的输出如下所示:
空 无效的 无效的 无效的 无效的 // 这里是我输入 command-Q 的地方 java.awt.event.MouseEvent[MOUSE_CLICKED,(210,45),absolute(210,67),button=1,modifiers=Button1,clickCount=1] 在 frame0 java.awt.event.MouseEvent[MOUSE_CLICKED,(210,45),absolute(210,67),button=1,modifiers=Button1,clickCount=1] 在 frame0 java.awt.event.MouseEvent[MOUSE_CLICKED,(210,45),absolute(210,67),button=1,modifiers=Button1,clickCount=1] 在 frame0
我在应用程序中没有任何鼠标侦听器(尽管我假设 JButton 对象有一个),并且除了在 JButton 上的 ActionListener 之外,我没有注册任何侦听器。而且我没有碰鼠标。但我认为是所有这些 MouseEvents 阻止了应用程序退出。有人知道我能做些什么吗?谢谢。
【问题讨论】: