java - JFrame 不会关闭

标签 java swing jframe

目前,我正在制作一个康威的生命游戏版本以供自己娱乐。到目前为止,一切都很顺利,但就在我测试一些最终部分时,我注意到一个恼人的错误。代码的主体发生在一个 while 循环内,该循环由用户希望看到的游戏“世代”数控制。执行此循环时,JFrame 的红色 X 拒绝响应,我不明白为什么会这样。

我遇到这个问题的区域:

public void run(int steps) throws InterruptedException{
    int a = 0;    
    do{
        step();
        myDisp.update(myDisp.getGraphics());
        Thread.sleep(delay);
        a++;
    }while(a < steps);
}    

最佳答案

我建议您将这种处理放在一个单独的线程中。 只要您将它保留在代码的主体中,只要循环正在运行,Swing 组件就不会响应任何用户交互。

this page您可以找到一些关于 Swing 应用程序中的异步操作的良好实践。我想强调其中一个主题:

Rule #2: do not run time-consuming operations on the event thread.

I'll keep repeating this: Swing uses a single thread for all GUI events. If your event handler is uploading a multi-megabyte file across the net, those events will be delayed until you're done. There is a balancing act involved with this rule: some operations (such as getting the size of a file) are so fast that they won't interrupt the user. However, that's not a reason to be cavalier, because some day your user will be getting the size of a file that resides on a fileserver that has an intermittent network connection.

This other page还展示了如何在 Swing 应用程序中处理长时间运行的任务的示例。您可能还想看看 SwingWorker类。

关于java - JFrame 不会关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21331998/

相关文章:

java - 是否可以将 TestNG 插件与 Netbeans 6.8 一起使用?

java - 使用 GridBagLayout 构建大富翁棋盘

swing - 用于纯 Windows 桌面应用程序的 JavaFX 2 与 Swing

java - JTable 排序后添加行 bug

java - 如何为 java.awt.Frame 进行键绑定(bind)?

java - setUndecorated(true) 与 toFront() 混淆

java - 从菜单单击开始新 Activity 时出错

java - Facebook JSON 区域设置

java - 是否可以在最小化 JFrame 之前执行某些操作?

java - HTML/JAVA 抓取