Java Timer Class
Java Timer Class
The Java Timer class is used to generate events at regular intervals. It generates an action event at the given interval.
Timer(int delay, ActionListener listener)
The parameter delay is the interval at which an action event occurs. It is specified in milliseconds.
Timer Method     Method Description
start()Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â This method starts firing events at the given interval.
stop()Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â The stop() method stops firing events.
restart()Â Â Â Â Â Â Â Â Â Â Â Â Â Â This method restarts firing events.
setDelay(int)Â Â Â Â Â Â Â Â Â Â This method changes the time interval.
Example
Sample Java class
package com.testingdocs.sample;
import java.awt.Font;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import javax.swing.*;
public class Clock extends JFrame {
JLabel label;
Timer timer;
public Clock() {
super("Clock - Timer Example");
label= new JLabel(getTime());
label.setFont(new Font("Verdana", Font.BOLD,36) );
label.setHorizontalAlignment(JLabel.CENTER);
timer= new Timer(1000, e-> label.setText(getTime()));
timer.start();
getContentPane().add(label);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
private String getTime() {
LocalTime now = LocalTime.now();
return now.format
(DateTimeFormatter.ofPattern("HH:mm:ss"));
}
// main method
public static void main(String args[]) {
Clock clock= new Clock();
clock.setSize(500,500);
clock.setVisible (true);
}
}
Screenshot
Java Tutorials
Java Tutorial on this website:
For more information on Java, visit the official website :