Cheetah jimi
Cheetah jimi

Reputation: 31

Using threading in Java

I have a question about threading in Java. So, I have a gui program which consists of 8 buttons and if you click any one of them, the colors of all the other buttons are changed. But I have to modify it, so that the colors are automatically changed after 5 seconds. So, when you run the program, the colors of all the buttons should change for 5 seconds. And if you click on a button, the timer is reset.

I was hoping you guys can give some suggestions on how should I approach it. I have to use threading. Any help would be appreciated.

What if I want to do it without the timer?

Upvotes: 1

Views: 81

Answers (2)

user3392484
user3392484

Reputation: 1919

Look at javax.swing.Timer, and in particular its restart() method (invoke that from an ActionListener attached to your buttons).

Update: if you want to do it without the Timer (because it's homework?) then:

  • Create yourself a daemon Thread with an infinite loop that sleeps for five seconds, then uses SwingUtils.invokeLater (...) to get the GUI to update on the event dispatching thread.

  • If the sleep is interrupted then just loop, rather than updating the GUI.

  • If a button is clicked then interrupt() your sleeping thread, which (given the previous point) will effectively restart the timer.

Upvotes: 3

user692168
user692168

Reputation:

If you're using swing javax.swing.Timer is what you need. You can see it in action here http://docs.oracle.com/javase/tutorial/uiswing/misc/timer.html

Upvotes: 1

Related Questions