Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a JButton, which, as soon as I click on it, I want to change some colors after a few seconds, for example from blue -> 1 sec -> red -> 1 sec -> yellow. My problem is that, as soon as I use the Thread.sleep function in ActionListener and I test my program, it freezes for the 2 seconds and gives me directly yellow. How can I fix that? Thanks a lot

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
617 views
Welcome To Ask or Share your Answers For Others

1 Answer

ActionListener and Thread.sleep..

..don't play well together.

Don't block the EDT (Event Dispatch Thread) - the GUI will 'freeze' when that happens. Instead of calling Thread.sleep(n) implement a Swing Timer for repeating tasks or a SwingWorker for long running tasks. See Concurrency in Swing for more details.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...