Java Swing Timer: Add to JFrame

In Java, the Timer class from the Swing components can be used to implement a timer function. Here is a simple example code showing how to add a timer to a window:

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class TimerExample {

    public static void main(String[] args) {
        JFrame frame = new JFrame("Timer Example");
        frame.setSize(200, 200);

        JLabel label = new JLabel("Time: 0");
        frame.add(label);

        Timer timer = new Timer(1000, new ActionListener() {
            int time = 0;

            @Override
            public void actionPerformed(ActionEvent e) {
                time++;
                label.setText("Time: " + time);
            }
        });

        timer.start();

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}

In the code above, we create a JFrame window and add a JLabel label to display the time of the timer. Then we create a Timer object, set the interval of the timer to 1 second, and implement the actionPerformed method of the ActionListener interface to update the time and display it on the label. Finally, we call timer.start() to start the timer.

After running the program, the window will display a timer that increases by one second each time.

bannerAds