Home java Timer in Java Swing

Timer in Java Swing

Author

Date

Category

How can I create a timer that, after a specified time, will perform an action?

For example, say System.out.print ("Hi!"); after 4 seconds


Answer 1, authority 100%

Looking at javax.swing.Timer
Example:

import javax.swing.Timer; // Will be called every second
timer = new Timer (1000, new ActionListener (
  public void actionPerformed (ActionEvent ev) {
     System.out.println ("WOW!");
  }));
timer.start ();

Answer 2, authority 45%

Alternatively (although Timer is more convenient here) using a third-party Thread ‘a, so as not to interfere with the main one:

public class Test {
  public static void main (String args []) {
    new Thread (new Runnable () {
      public void run () {
        while (true) {// spin endlessly
          try {
            Thread.sleep (4000); // 4 seconds in milliseconds
            System.out.println ("Hi!");
          } catch (InterruptedException e) {
            e.printStackTrace ();
          }
        }
      }
    }). start ();
  }
}

Or, of course, using Timer – rewrite the method run () :

import java.util. *;
public class Test {
  public static void main (String args []) {
    Timer timer = new Timer ();
    timer.schedule (new SayHello (), 0, 4000); // set the schedule to execute SayHello every 4 seconds
  }
}
class SayHello extends TimerTask {
  public void run () {
    System.out.println ("Hi!");
  }
}

Answer 3, authority 36%

I wrote you a good example

package javaapplication24;
import java.util.Timer;
import java.util.TimerTask;
public class JavaApplication24 {
  public static void main (String [] args) {
    final Timer time = new Timer ();
    time.schedule (new TimerTask () {
      int i = 0;
      @Override
      public void run () {// RESTART THE RUN METHOD IN WHICH DO WHAT YOU NEED
        if (i & gt; = 2) {
          System.out.println ("The timer has finished its work");
          time.cancel ();
          return;
        }
        System.out.println ("It took 4 seconds");
        i = i + 1;
      }
    }, 4000, 4000); // (4000 - WAIT BEFORE STARTING IN MILISEK, WILL REPEAT 4 SECONDS (1 SEC = 1000 MILISEK))
  }
}

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions