Creating a Java Timer and a TimerTask?

后端 未结 4 2173
走了就别回头了
走了就别回头了 2020-12-21 01:26

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 no

4条回答
  •  渐次进展
    2020-12-21 01:50

    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);
        }
    
        //.....
      }
    }
    

提交回复
热议问题