问题
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
回答1:
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.
来源:https://stackoverflow.com/questions/18164944/actionlistener-and-thread-sleep