I do not know how to do this and can not find how on google.

I want to add code to my action listener to disable a jButton after it is clicked an then enable it again after x amount of time.

anyone know how to do this?

Recommended Answers

All 4 Replies

My suggestion:

When te button is clicked:
- disable the button.
- Make a new thread, with a while loop in it.
- Check whether the startTime - currentTime is bigger then the needed time.
- If it is, enable the button.

You should pass the button as a parameter into the thread, so you can enable it.

Any questions, please ask!

The correct way to do this is with a Swing Timer, designed and optimised for exactly this kind of task:

when the button is clicked
   disable the button
   create and start a new javax.swing.Timer with
      a delay equal to how long you want the button disabled for, 
      and an actionPerformed method that re-enables the button

Yeah, a javax.swing.Timer would probabaly be better, ut a thread (or BackgroundWorker) with a while loop should work I think.
I don't have the time to try it...

Yes, a thread with a loop in the background would work, but at the expense of burning CPU as fast as it could for the entire delay. Also your re-enable code will run on the wrong thread (all Swing code should run on Swing's thread).
javax.swing.Timer uses the same timer/event queue as Swing itself uses for things like the delay before popping up a tooltip. It really is the only recommendable solution.

Be a part of the DaniWeb community

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