문제

I set up the TimerTask UpdateTask but it only fires once at the when I start my program. Why doesn't it continue to trigger?

Some of the methods here are in other classes, if you need them, don't hesitate to let me know.

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) only schedules the task for one-time execution.

Use

timer.scheduleAtFixedRate(new UpdateTask(), 10, 10);

for repeating invocations of your TimerTask.

More info: JavaDoc

다른 팁

You need to use

scheduleAtFixedRate(TimerTask task,Date firstTime,long period)

(or)

schedule((TimerTask task,Date firstTime,long period))

10 in your schedule() method call is delay, not period.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top