0

I have been recently working on a java project to just practice java and work on making programs for fun, but i came up upon this bug:

When i use Thread.sleep on my java program, it doesent execute the line above the try-catch block where i have my Thread.sleep.
heres the code:

button1.setIcon(red); //not using this line

try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

button1.setIcon(white);
3
Contributors
6
Replies
7
Views
6 Years
Discussion Span
Last Post by JamesCherrill
0

Oh i also forgot to add that the code above is in an action listener

0

All swing activity (including action listeners and screen updates) is queued in a single thread called the Event Dispatch Thread. Your action listener is executed on the EDT, and everything else is held up until your method returns. Your first statement IS executed, but the screen won't be repainted until after your method returns, by which time you have reset the icon.
Moral; NEVER use Thread.sleep in a swing GUI. If you want to time things use a javax.swing.Timer, which works in total cooperation with the EDT.

0

it doesent execute the line above the try-catch block

Why do you think the code is NOT executing that line.
What happens if you put printlns both before and after the line?

You need to read about the Swing EDT thread. If your code is called on that thread (listeners are) and you stop the thread, then the GUI will do nothing until you release the thread. In your case you have FROZEN the GUI thread for one second.

0

Forget your current syntax. That's not the way to do it. You need a structure like this:

in button event handler:
1. change icon.
2. start Timer
3. return
(GUI now updates)

When the Timer expires it triggers your timer ActionPerformed, in which you
1. change to icon back
2. return
(GUI updates again)

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.