我设置了TimerTask UpdateTask,但是在启动程序时仅触发一次。为什么它不继续触发?
这里的某些方法在其他类中,如果您需要它们,请随时告诉我。
import java.awt.Graphics;
import java.util.Timer;
import java.util.TimerTask;
public class graphpanel extends variables
{
Timer timer = new Timer();
int ypoint;
int barheight;
int height = getHeight();
int width = getWidth();
int bars = (int)getLife() - (int)getAge();
int xpoint = 0;
int barwidth = 20;
public graphpanel()
{
timer.schedule(new UpdateTask(), 10);
}
public void paintComponent (Graphics g)
{
super.paintComponent(g);
for (int i = 0; i < bars; i++)
{
barheight = (int) getTime(i)/100;
ypoint = height/2 - barheight;
g.drawRect(xpoint, ypoint, barwidth, barheight);
g.drawString("hey", 10*i, 40);
}
}
class UpdateTask extends TimerTask
{
public void run()
{
bars = (int)getLife() - (int)getAge();
System.out.print("TimerTask detected");
repaint();
}
}
}
最佳答案
Timer.schedule(TimerTask, long)
仅将任务安排为一次性执行。
使用
timer.scheduleAtFixedRate(new UpdateTask(), 10, 10);
用于重复调用
TimerTask
。更多信息:JavaDoc
关于java - TimerTask仅触发一次,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20575813/