2011-05-17 99 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);