ActionListener和Thread.sleep [英] ActionListener and Thread.sleep
问题描述
我有一个JButton,一旦我点击它,我想在几秒后改变一些颜色,例如从蓝色 - > 1秒 - >红色 - > 1秒 - >黄色。我的问题是,只要我在ActionListener中使用Thread.sleep函数并测试我的程序,它会冻结2秒并直接给我黄色。我该如何解决这个问题?非常感谢
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
推荐答案
ActionListener和Thread.sleep ..
ActionListener and Thread.sleep..
..不能很好地一起玩。
..don't play well together.
不要阻止EDT(事件调度线程) - 当发生这种情况时,GUI将冻结。而不是调用 Thread.sleep(n)
为重复任务或实现Swing
用于长时间运行的任务。有关更多详细信息,请参阅 Swing中的并发。计时器
SwingWorker
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.
这篇关于ActionListener和Thread.sleep的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!