2

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?

Maximilian Peters
  • 30,348
  • 12
  • 86
  • 99
Udi Oshi
  • 6,787
  • 7
  • 47
  • 65

4 Answers4

5

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

Community
  • 1
  • 1
mKorbel
  • 109,525
  • 20
  • 134
  • 319
2

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.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
2

You may not use Swing components outside of the event dispatch thread. See http://download.oracle.com/javase/6/docs/api/javax/swing/package-summary.html#threading

Use SwingUtilities.invokeLater each time your thread must change something in the UI. Or use a Swing Timer.

If this infinite loop is in fact in the EDT, then it blocks all the UI events, repaints, etc. while it's running. So you should run this loop in a separate thread.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
1

Have a look at SwingWorker.

http://download.oracle.com/javase/6/docs/api/javax/swing/SwingWorker.html

Thomas
  • 8,357
  • 15
  • 45
  • 81