JFrame不会关闭 [英] JFrame Will Not Close

查看:82
本文介绍了JFrame不会关闭的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前,我正在为自己制作娱乐版的Conway的《人生游戏》.到目前为止,一切都进行得很顺利,但是当我测试某些最终零件时,我注意到了一个令人讨厌的错误.该代码的主体位于一个while循环内,该循环由用户希望看到的游戏世代"数量控制.在执行此循环时,JFrame的红色X拒绝响应,我对此感到茫然.

At the moment, I am working on a version of Conway's Game of Life for my own amusement. Up to this point, everything has gone smoothly, but just as I was testing some of the final parts, I noticed an irritating error. The main body of the code takes place inside of a while loop that is controlled by the number of 'generations' of the game the user would like see. While this loop is executing, the JFrame's red X refuses to respond and I am at a loss as to why this is.

我遇到此问题的区域:

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

推荐答案

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

I would suggest you to put this kind of processing in a separate thread. As long as you keep it in the main body of your code, Swing components will not respond to any user interaction as long as the loop is running.

此页面中,您可以找到一些有关异步操作的良好做法在Swing应用程序中.我想强调一个主题:

In this page you can find some good practices regarding asynchronous operations in Swing applications. I would like to highlight one of the topics:

规则2:不要在事件线程上运行耗时的操作.

我将继续重复此操作:Swing对所有GUI事件使用一个线程.如果您的事件处理程序正在通过网络上传一个数兆字节的文件,那么这些事件将被延迟,直到您完成操作为止.该规则涉及一种平衡行为:某些操作(例如获取文件的大小)是如此之快,以至于它们不会打扰用户.但是,这并不是变得轻率的原因,因为有一天您的用户将获得驻留在具有间歇性网络连接的文件服务器上的文件的大小.

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.

SwingWorker 类.

This other page also shows an example of how to handle long-running tasks in a Swing application. You may also want to have a look at the SwingWorker class.

这篇关于JFrame不会关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆