Learn how to create a real-time digital clock using Java. This program will display the current time and update it every second.
Code Implementation
public class DigitalClock {
public static void main(String[] args) {
// Create an instance of the ClockFrame class
ClockFrame clockFrame = new ClockFrame();
}
}
import javax.swing.*;
import java.awt.*;
import java.text.SimpleDateFormat;
import java.util.Date;
class ClockFrame extends JFrame {
private JLabel timeLabel;
public ClockFrame() {
setTitle("Digital Clock");
setSize(400, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
timeLabel = new JLabel("", JLabel.CENTER);
timeLabel.setFont(new Font("Serif", Font.BOLD, 50));
add(timeLabel);
setVisible(true);
// Update time every second
Timer timer = new Timer(1000, e -> updateClock());
timer.start();
}
private void updateClock() {
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
String currentTime = dateFormat.format(new Date());
timeLabel.setText(currentTime);
}
}
Explanation of the Program
This Java program creates a simple graphical user interface (GUI) digital clock using the javax.swing
library.
- ClockFrame class: This class extends
JFrame
to create a window with a JLabel where the time is displayed. It also sets up the timer to update the time every second. - Timer: The
Timer
class calls theupdateClock()
method every 1000 milliseconds (1 second) to refresh the displayed time. - SimpleDateFormat: This is used to format the current time into a string in the format “HH:mm:ss”.
How to Run the Program
- Ensure that you have Java Development Kit (JDK) installed on your system.
- Create a new file called
DigitalClock.java
and paste the code into the file. - Open a terminal or command prompt, navigate to the directory where the file is located, and compile the program using the following command:
javac DigitalClock.java
- Run the program using the following command:
java DigitalClock
- The digital clock window will appear showing the current time, updating every second.