问题描述
在此程序中,我需要暂时停下来进行我想做的事情.我在Java Swing JFrame
中显示一些文本,重涂后显示它,我等待1.5秒钟,然后更改文本.
I need a one-time pause in this program for what I'm trying to do. I display some text in a Java Swing JFrame
, repaint shows it, I wait 1.5 sec, then I change the text.
基本上,我是从这个开始的:
Basically, I started with this:
statusLabel.setText(s);
appFrame.repaint();
Thread.sleep(1500);
statusLabel.setText(y);
appFrame.repaint();
但是这没有用. Thread.sleep()
将在重新绘制完成之前调用,这意味着s将永远不会显示.我读过很多地方,您不应该在swing应用程序中使用Thread.sleep()
,因为它会暂停所有线程,甚至是试图重绘的线程,并且要暂停actionPerformed()
触发的某些事情,您需要使用Java Swing计时器.
But this wasn't working. Thread.sleep()
would invoke before repaint had finished, meaning s would never be shown. I read a lot of places that you're not supposed to use Thread.sleep()
in swing applications because it pauses all threads, even the threads trying to repaint, and that to pause something triggered by actionPerformed()
you need to use a Java Swing Timer.
这一切都很好,但是我找不到一个可以对它们的工作方式进行恰当解释的地方.据我所知,由于计时器专门用于重复计时器上的事件.我只希望两次重涂之间有1.5秒的延迟.
Which is all well and fine, except I can't find a single place that offers a decent explanation on how they work. Since, as far as I can tell, timers are specifically used for repeating events on a timer. I just want a 1.5 second delay between 2 repaints.
我尝试这样做...
statusLabel.setText(s);
appFrame.repaint();
Timer timer = new Timer(1500, new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
}
});
timer.setInitialDelay(1500);
timer.setRepeats(false);
timer.start();
statusLabel.setText(y);
appFrame.repaint();
...在其actionPerformed事件中添加了一个具有1.5秒初始延迟,没有重复且没有主体的计时器,因此它实际上什么也没做,只是等待了1.5秒,但没有用.
...adding a timer with a 1.5 sec initial delay, no repeating, and no body to its actionPerformed event, so that it literally does nothing but wait that 1.5 sec, but it didn't work.
推荐答案
如示例中的代码所示,计时器似乎可以工作",因为actionPerformed
方法为空,它什么也不做.您可能会认为timer.start()
会阻塞并等待计时器触发,但实际上它会立即返回.计时器的工作方式是应该在UI线程中调用计时器的actionPerformed
方法.将代码放在计时器的actionPerformed
方法内部是一种定期更新UI状态的好方法.
As coded in your example, it looks like the timer would "work", it just doesn't do anything because the actionPerformed
method is empty. You might be thinking that timer.start()
blocks and waits for the timer to trigger, but it fact it returns immediately. The way timers work is that the timer's actionPerformed
method will be invoked from the UI thread when it is supposed to be. Placing code inside the actionPerformed
method of a timer is a good way to update the UI state periodically.
这篇关于无法理解Java Swing计时器.如何延迟1次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!