[英]Java: Perform Action Every X Seconds
I've got a working Java program and I would like to draw an object on the display every X seconds. 我有一个工作的Java程序,我想每隔X秒在显示器上绘制一个对象。 What is the best way to do this? 做这个的最好方式是什么? I was thinking of using a for
loop and some sleep
statements, but I'm curious if there is an easier or more efficient way to go about this. 我正在考虑使用for
循环和一些sleep
语句,但我很好奇是否有更简单或更有效的方法来解决这个问题。
Thanks. 谢谢。
The simplest way would be to use a javax.swing.Timer 最简单的方法是使用javax.swing.Timer
Timer timer = new Timer(X, new ActionListener() {
public void actionPerformed(ActionEvent evt) {
// Update the variables you need...
repaint();
}
});
timer.setRepeats(true);
timer.setCoalesce(true);
timer.start();
You might also like to have a read through 您可能也想阅读一下
So you can understand why you should never use a while (true) { Thread.sleep(X) }
call in Swing
(inside the EDT) 所以你可以理解为什么你不应该在Swing
使用while (true) { Thread.sleep(X) }
调用(在EDT中)
ScheduledExecutorService might help here. ScheduledExecutorService可能会有所帮助。 The Javadoc shows example usage. Javadoc显示了示例用法。 Don't forget to call the shutdown
method when you're finished. 完成后不要忘记调用shutdown
方法。
Using Thread, this will draw a rectangle on the screen every XMilSeconds. 使用Thread,这将在每个XMilSeconds上在屏幕上绘制一个矩形。 This will stop after 5 runs. 这将在5次运行后停止。 Edit the xMilSeconds for slower runs, and j > 4 for how many runs before stoping. 编辑xMilSeconds以进行较慢的运行,j> 4表示停止前的运行次数。 It does freeze though, that I can't fix. 它确实冻结了,我无法解决。
int i = 0;
private long xMilSeconds = 300;
private boolean paint;
public boolean running = true;
public void paint(Graphics g)
{
super.paint(g);
if(paint)
{
for(;i < i+1;)
{
g.drawRect(i+49,i+49,i+299,i+99);
g.setColor(Color.RED);
g.fillRect(i+49,i+49,i+299,i+99);
}
paint = false;
}
}
public void run()
{
while(running)
{
try
{
Thread.sleep(xSeconds);
paint = true;
repaint();
i++;
j++;
if(j > 4)
{
running = false;
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.