Create a Digital Clock in Java

In this tutorial, we'll learn how to create a digital clock in Java that looks like the one below:

Create digital clock in Java

To create GUI based applications, Java provides Swing framework which is a graphical user interface framework that includes a set of classes that are powerful and flexible.

To create a digital clock, we will use JFrame, JLabel, and Timer class from the Swing framework. The JFrame class is used to construct a top-level window for a Java application. The JLabel class is used to display a string and the Timer class is used to fire events at specified intervals.

The following code creates and displays a digital clock in Java:


import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import javax.swing.Timer;

public class DigitalClock {

	static void display() {
		// create window for clock
		JFrame clockFrame = new JFrame("Digital Clock");
		clockFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		// create label to print time
		JLabel timeLabel = new JLabel("", SwingConstants.CENTER);
		timeLabel.setPreferredSize(new Dimension(400, 100));
		timeLabel.setFont(new Font("Calibri", Font.BOLD, 50));
		clockFrame.getContentPane().add(timeLabel, BorderLayout.CENTER);

		// Display the window
		clockFrame.setLocationRelativeTo(null);
		clockFrame.pack();
		clockFrame.setVisible(true);

		int delay = 100;
		Timer timer = new Timer(delay, new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				LocalDateTime now = LocalDateTime.now();
				DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss");
				String formattedDateTime = now.format(formatter);
				timeLabel.setText(formattedDateTime);
			}
		});

		timer.start();
    }

	public static void main(String args[]) {
		display();
	}
}