简体   繁体   English

在Swing中等待几秒钟

[英]Wait a few seconds in Swing

I need to wait a few seconds between invoking two different methods in a program with Swing interface. 在带有Swing接口的程序中调用两种不同的方法之间,我需要等待几秒钟。 Those methods are not related to the GUI. 这些方法与GUI不相关。

firstMethod();
//The interface is changed by other methods
...
//I want to Wait five seconds
secondMethod();

I have tried using a Swing Timer but it does not work. 我尝试使用Swing Timer但是它不起作用。 Apparently, the Timer starts but is a non-blocking action, so secondMethod() is executed immediately. 显然, Timer启动了,但这是一个非阻塞动作,因此secondMethod()会立即执行。 I can use sleep() , but that freezes the GUI for those five seconds, so the interface is not updated until after that, which I would prefer to avoid. 我可以使用sleep() ,但这会将GUI冻结5秒钟,因此直到那之后才更新接口,我希望避免这样做。

I have found here some recommendations to use Future<V> and I have read the Javadoc but I have never used ExecutorService before and I am afraid I may write a too complex piece of code for something that simple. 我在这里找到了一些使用Future<V>建议,并且我已经阅读过Javadoc,但是我以前从未使用过ExecutorService ,而且恐怕我可能为这么简单的代码编写太复杂的代码。

Any idea on how to do it? 有什么想法吗?

Sounds like your code is something like: 听起来您的代码是这样的:

firstMethod();

startTimer();

secondMethod();

I have tried using a Timer but it does not work 我已经尝试过使用计时器,但是它不起作用

You can't just start a Timer and do nothing. 您不能只是启动计时器而什么也不做。 When the timer fires you need to invoke the secondMethod(...) in the actionPerformed of the Timer. 当计时器触发时,您需要在计时器的actionPerformed中调用secondMethod(...)

Use Swing Timer instead of Java Timer and Thread.sleep. 使用Swing Timer而不是Java Timer和Thread.sleep。

Please have a look at How to Use Swing Timers 请看看如何使用Swing计时器

Timer timer = new Timer(5000, new ActionListener() {

    @Override
    public void actionPerformed(ActionEvent arg0) {            
        secondMethod();
    }
});
timer.setRepeats(false);
timer.start()

A timer won't just stop code execution like sleep does. 计时器不仅会像睡眠一样停止执行代码。 You have to assign an ActionListener to it which will be notified when the time is up. 您必须为其分配一个ActionListener,时间到时将通知它。

It goes something like this: 它是这样的:

firstMethod();
Timer t = new Timer(5000);
t.setRepeats(false);
t.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            secondMethod();    
        }
    })
t.start();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM