Creating a Java Timer and a TimerTask?

Radicate picture Radicate · Nov 2, 2012 · Viewed 15.3k times · Source

I'm new to Java and I'm trying to set a simple timer, I'm familiar with set_interval, because of experience with JavaScript and ActionScript,

I'm not so familiar with classes yet so I get confused easily, I understand that I need to set a new Timer, and then set a TimerTask, but I don't get how exactly to do it even though I'm looking at the documentation right now..

So I created an Applet, and that's my init method:

public void init() {
    TimerTask myTask;
    Timer myTimer;
    myTimer.schedule(myTask,5000);
}

How do I actually set the task code? I wanted it to do something like

g.drawString("Display some text with changing variables here",10,10);

Answer

Roman C picture Roman C · Nov 2, 2012

Whatever you want to perfom i.e. drawing or smwhat, just define task and implement the code inside it.

import javax.swing.*;
import java.awt.*;
import java.util.Timer;
import java.util.TimerTask;

public class TimerApplet extends JApplet {

  String someText;
  int count = 0;

  public TimerApplet() {
    Timer time = new Timer();
    Сalculate calculate = new Сalculate();
    time.schedule(calculate, 1 * 1000, 1000);
  }

  class Сalculate extends TimerTask {

    @Override
    public void run() {
      count++;
      System.out.println("working.. "+count);
      someText = "Display some text with changing variables here.." +count;
      repaint();

    }
  }

  //This is how do you actually code.
  @Override
  public void paint(Graphics g)//Paint method to display our message
  {
//    super.paint(g);   flickering
    Graphics2D g2d = (Graphics2D)g;
    g2d.setColor(Color.WHITE);
    g2d.fillRect(0, 0, getWidth(), getHeight());
    if (someText != null) {
      g2d.setColor(Color.BLACK);
      g2d.drawString(someText,10,10);
    }

    //.....
  }
}