I want my timer to execute the actionPerformed method only one time once it 5 seconds the time but it is writing in the console "Hello" lots of times:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;
public class X{
public static void main(String args[]) {
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
System.out.println( "Hello" );
}
};
Timer timer = new Timer( 5000, actionListener );
timer.start();
}
}
How can I make the effect I want? Thanks
Don't neglect to use the event dispatch thread. There's nothing wrong with
java.util.Timer
, butjavax.swing.Timer
has several advantages with Swing.If using
java.util.Timer
, update the GUI using a continuation.and then
Sounds like you want a
java.util.Timer
rather than ajavax.swing.Timer
.This should do the trick!
As already mentioned, it's better to use
java.util.Timer
, but you can also use setRepeats() before starting: