簡體   English   中英

Java:每X秒執行一次操作

[英]Java: Perform Action Every X Seconds

我有一個工作的Java程序,我想每隔X秒在顯示器上繪制一個對象。 做這個的最好方式是什么? 我正在考慮使用for循環和一些sleep語句,但我很好奇是否有更簡單或更有效的方法來解決這個問題。

謝謝。

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

您可能也想閱讀一下

所以你可以理解為什么你不應該在Swing使用while (true) { Thread.sleep(X) }調用(在EDT中)

ScheduledExecutorService可能會有所幫助。 Javadoc顯示了示例用法。 完成后不要忘記調用shutdown方法。

使用Thread,這將在每個XMilSeconds上在屏幕上繪制一個矩形。 這將在5次運行后停止。 編輯xMilSeconds以進行較慢的運行,j> 4表示停止前的運行次數。 它確實凍結了,我無法解決。

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM