开发者

Thread.sleep(xx) but the whole program sleeps?

开发者 https://www.devze.com 2023-02-07 16:29 出处:网络
Hey.. i have a program that check-in some people.. if they have a dept, the prog will show a panel with a list..

Hey.. i have a program that check-in some people.. if they have a dept, the prog will show a panel with a list..

so i wanna to set the panel not visible after a few seconds.. how could i do that?

I created a new Thread (FadeThread) and started it in the view, but now, when i write

Thread.sleep(5000)

the whole p开发者_StackOverflow社区rogram sleeps for this 5seconds,.. i only want to wait in the background for 5seconds and set the panel visible(false) but the whole UI and the program sleeps..

Thanks...


Thread.sleep() will suspend the current thread, which I presume is the event dispatcher thread in your case. If you do it in a background thread, it should work, although if you accidentally call run() instead of start(), it won't.

To execute code with a set delay, you'll have to use the Timer class. Much cleaner and you don't have to worry about accidentally creating too many threads, not exiting a thread properly and so on.


You are causing the Event Dispatch Thread to sleep so the GUI can't react to events.

Read the section from the Swing tutorial on Concurrency for more information and a potential solution.


Assuming you're using Swing, have a look at the SwingWorker class. You can create a process that will block for 5 seconds and then hide the panel in a thread-safe manner.

Alternatively you could used a ScheduledExecutor as long as you make sure you run it on the EDT using invokeLater().

0

精彩评论

暂无评论...
验证码 换一张
取 消