ActionListener and Thread.sleep

ぐ巨炮叔叔 提交于 2020-03-12 05:44:27

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!