在JAVA中进行线程处理时未显示GUI [英] GUI isn't shown while thread is in procces in JAVA

查看:96
本文介绍了在JAVA中进行线程处理时未显示GUI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用非常简单的线程(延迟1秒)制作简单的游戏 线程有问题,我的代码有while(true)循环:

I'm making simple game with very simple thread (1 sec delay) got problem with the thread, I have while(true) loop with the code:

try {
    while (true) {
       Ltimer.setText(getTimeElapsed());
       Thread.currentThread();
       Thread.sleep(1000); // Thread sleeping for 1 second           
    }
} catch (Exception e) {
    JOptionPane.showMessageDialog(null, "error with timer");       
} 

它只是每秒获取字符串并更新标签文本 当我尝试运行gui冻结时,只能看到黑色背景中的标签,所有按钮和bg img都消失了.试图解决 setVisible() repaint() 但一无所获..

it simply get string every second and updates label text when I'm trying to run it the gui freeze and I can only see the label in a black background, all buttons and bg img dissappeared. tried to fix with setVisible() repaint() but got nothing..

还有其他选择吗?

推荐答案

在EDT期间不要使用Thread#sleep(int),那么此处缺少EDT

don' use Thread#sleep(int) during EDT, then you have issue with Concurency in Swing, if you need to delay any action use java.swing.Timer, example for EDT lack here

这篇关于在JAVA中进行线程处理时未显示GUI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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