Java:每X秒执行一次操作 [英] Java: Perform Action Every X Seconds

查看:510
本文介绍了Java:每X秒执行一次操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个有效的Java程序,我想每隔X秒在显示器上绘制一个对象。做这个的最好方式是什么?我正在考虑使用用于循环和一些 sleep 语句,但我很好奇是否有更容易的或更有效的方法。

I've got a working Java program and I would like to draw an object on the display every X seconds. 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.

谢谢。

推荐答案

最简单的方法是使用 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();

您可能还想阅读

  • The Event Dispatching Thread
  • Concurrency in Swing

所以你可以理解为什么你不应该使用 while(true){Thread.sleep( X)} 调用 Swing (在EDT内)

So you can understand why you should never use a while (true) { Thread.sleep(X) } call in Swing (inside the EDT)

这篇关于Java:每X秒执行一次操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆