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

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

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.

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.

Then how would i use a timer object in a syntax like this?

What are you trying to do?

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)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.