Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GUI isn't shown while thread is in procces in JAVA

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");       
} 

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..

any other options?

like image 299
Udi Oshi Avatar asked Jun 23 '26 10:06

Udi Oshi


2 Answers

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

like image 82
mKorbel Avatar answered Jun 25 '26 01:06

mKorbel


My guess is you are using the GUI Event Thread to do this. When you have the GUI thread tied up doing something else it cannot also be updating the screen. I suggest you run a new thread to do this.

like image 31
Peter Lawrey Avatar answered Jun 24 '26 23:06

Peter Lawrey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!