Java: Perform Action Every X Seconds

蹲街弑〆低调 提交于 2019-12-10 11:44:58

问题


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.

Thanks.


回答1:


The simplest way would be to use a 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

  • The Event Dispatching Thread
  • Concurrency in Swing

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




回答2:


ScheduledExecutorService might help here. The Javadoc shows example usage. Don't forget to call the shutdown method when you're finished.




回答3:


Using Thread, this will draw a rectangle on the screen every XMilSeconds. This will stop after 5 runs. Edit the xMilSeconds for slower runs, and j > 4 for how many runs before stoping. 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();
        }
    }
}


来源:https://stackoverflow.com/questions/12593098/java-perform-action-every-x-seconds

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!