An overview of the

The Timer component is a Timer that fires one or more ActionEvents at a specified time interval.

The results can be achieved as follows:

Quick start

First, create a Timer.

The second step is to pass in two parameters, a delay and an event, to the Timer constructor.

Third, call the start() method to enable the timer.

public static void main(String[] args) { JFrame frame = new JFrame(); Frame. SetTitle (" Timer test "); frame.setSize(300, 300); Container contentPane = frame.getContentPane(); JLabel = new JLabel(" label "); contentPane.add(label); // Create a Timer component with two parameters. The first parameter is a delay of 1000 milliseconds, i.e., every 1000 milliseconds. The second parameter is event handler Timer Timer = new Timer(1000, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date = new Date(); // Displays the date and time in the JLabel label label.settext (format.format(date)); }}); timer.start(); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }Copy the code

methods

The constructor method of the Timer is as follows:

public Timer(int delay, ActionListener listener)
Copy the code

  • The first parameter delay is the delay time in milliseconds, that is, after each delay millisecond, subsequent events are triggered.
  • The second parameter, listener, is a listener for timer action events, such as displaying the current time.

The common methods of Timer are as follows:

Method names

instructions

addActionListener(ActionListener 1)

Add an action listener to the Timer

getDelay()

Returns the delay between two triggering action events, in milliseconds

isCoalesce()

Returns true if Timer combines multiple pending action events

isRunning()

Returns true if Timer is running

restart()

Restart the Timer to cancel all pending triggers and cause it to fire with initial delay

setCoalesce(boolean flag)

Sets whether the Timer combines multiple pending ActionEvents

setDelay(int delay)

Set Timer’s inter-event delay, the number of milliseconds between two consecutive action events

setLogTimers(boolean flag)

Enable/disable timer logging

setRepeats(boolean flag)

If flag is false, the Timer is instructed to send only one action event to its listener

start()

Start the Timer so that it starts sending action events to its listeners

stop()

Stop the Timer so that it stops sending action events to its listeners