[英]Java - repaint component every second?
I would like to repaint component after each second, but it didn't work. 我想在每秒后重新绘制组件,但它不起作用。 What I am trying is:
我在想的是:
try{
while(true){
Thread.currentThread().sleep(1000);
gc.cb.next();
gc.repaint();
}
}
catch(Exception ie){
}
I would advise using a javax.swing.Timer
for this problem, which will periodically fire an ActionEvent
on the Event Dispatch thread (note that you should only call repaint and / or manipulate Swing components from this thread). 我建议使用
javax.swing.Timer
来解决这个问题,它会定期在Event Dispatch线程上触发一个ActionEvent
(注意你应该只调用重绘和/或操作来自这个线程的Swing组件)。 You can then define an ActionListener
to intercept the event and repaint your component at this point. 然后,您可以定义
ActionListener
以拦截事件并在此时重新绘制组件。
Example 例
JComponent myComponent = ...
int delay = 1000; //milliseconds
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
myComponent.repaint();
}
};
new Timer(delay, taskPerformer).start();
Also note that SwingWorker
is probably inappropriate as it is typically used for background tasks that have a defined start and end, rather than a periodic task. 另请注意,
SwingWorker
可能不合适,因为它通常用于具有已定义的开始和结束的后台任务,而不是周期性任务。
Make sure you're not hogging the UI-thread for this. 确保你没有占用UI线程。 If you're executing this loop in the UI-thread, then the
repaint
event will never be dispatched. 如果您在UI线程中执行此循环,则永远不会调度
repaint
事件。
Another note; 另一个说明;
sleep
is a static method, and should be invoked as Thread.sleep(...)
. sleep
是一个静态方法,应该作为Thread.sleep(...)
调用。 (There is no way of doing thatThread.sleep(...)
anyway.) (无论如何,无法做
thatThread.sleep(...)
。)
The "correct" way of doing this is probably to use a SwingWorker
. 这样做的“正确”方法可能是使用
SwingWorker
。 Have a look at the tutorial . 看看教程 。
If you provide more code, we can provide better answers. 如果您提供更多代码,我们可以提供更好的答案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.