In this tutorial, we'll create a simple digital clock in Java using the Swing framework. The clock will display the current time and update every second.
This is a great way to learn about GUI programming in Java, handling time, and updating the user interface dynamically.
Here is what we will create and you can see some of the code in the background.
We can also think about other features and how we add them to our clock or modify our clocks appearance. Lets carry on.
Table of Contents
Features of the Digital Clock:
Displays the current time in HH:mm format.
Updates every second to show the accurate current time.
Uses Swing components like JFrame, JLabel, and Timer.
Provides a clean and simple user interface.
Complete Code of the Digital Clock
import javax.swing.*; import java.awt.*; import java.text.SimpleDateFormat; import java.util.Date; public class DigitalClock extends JFrame { private JLabel timeLabel; private SimpleDateFormat timeFormat; public DigitalClock() { // Set up the frame this.setTitle("Digital Clock"); this.setSize(300, 150); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setLocationRelativeTo(null); // Center the frame // Set up the time format timeFormat = new SimpleDateFormat("HH:mm:ss"); // Create a label to display the time timeLabel = new JLabel(); timeLabel.setFont(new Font("Verdana", Font.PLAIN, 50)); timeLabel.setHorizontalAlignment(SwingConstants.CENTER); // Add the label to the frame this.add(timeLabel); // Create a timer to update the time every second Timer timer = new Timer(1000, e -> updateTime()); timer.setInitialDelay(0); timer.start(); // Make the frame visible this.setVisible(true); } private void updateTime() { // Get the current time and set it to the label String currentTime = timeFormat.format(new Date()); timeLabel.setText(currentTime); } public static void main(String[] args) { // Run the clock in the Event Dispatch Thread SwingUtilities.invokeLater(() -> new DigitalClock()); } }
Explanation of the Code
1. Import Statements
import javax.swing.*; import java.awt.*; import java.text.SimpleDateFormat; import java.util.Date; javax.swing.*: Imports all Swing components needed for the GUI (JFrame, JLabel, Timer, etc.). java.awt.*: Imports AWT classes for graphics (Font, Color, etc.). java.text.SimpleDateFormat: Allows formatting of date and time. java.util.Date: Provides date and time information.
2. Class Declaration
public class DigitalClock extends JFrame { // Class content }
DigitalClock extends JFrame, making it a window that can contain GUI components.
3. Instance Variables
private JLabel timeLabel; private SimpleDateFormat timeFormat; timeLabel: Displays the current time. timeFormat: Defines the format in which the time will be displayed.
4. Constructor
public DigitalClock() { // Frame setup this.setTitle("Digital Clock"); this.setSize(300, 150); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setLocationRelativeTo(null); // Time format setup timeFormat = new SimpleDateFormat("HH:mm:ss"); // Time label setup timeLabel = new JLabel(); timeLabel.setFont(new Font("Verdana", Font.PLAIN, 50)); timeLabel.setHorizontalAlignment(SwingConstants.CENTER); // Adding label to frame this.add(timeLabel); // Timer setup Timer timer = new Timer(1000, e -> updateTime()); timer.setInitialDelay(0); timer.start(); // Making the frame visible this.setVisible(true); }
Frame Setup:
setTitle(“Digital Clock”): Sets the window title.
setSize(300, 150): Sets the window size.
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE): Closes the application when the window is closed.
setLocationRelativeTo(null): Centers the window on the screen.
Time Format Setup:
timeFormat = new SimpleDateFormat(“HH:mm:ss”): Defines the time format (24-hour format).
Time Label Setup:
timeLabel = new JLabel(): Initializes the label.
setFont(new Font(“Verdana”, Font.PLAIN, 50)): Sets the font type and size.
setHorizontalAlignment(SwingConstants.CENTER): Centers the text in the label.
Adding Label to Frame:
this.add(timeLabel): Adds the label to the frame.
Timer Setup:
Timer timer = new Timer(1000, e -> updateTime()): Creates a timer that triggers every 1000 milliseconds (1 second) and calls updateTime().
setInitialDelay(0): Starts the timer immediately without delay.
timer.start(): Starts the timer.
Making Frame Visible:
this.setVisible(true): Displays the window.
5. updateTime() Method
private void updateTime() { String currentTime = timeFormat.format(new Date()); timeLabel.setText(currentTime); }
Gets the current time using new Date().
Formats the time according to timeFormat.
Updates the label to display the current time.
6. main() Method
public static void main(String[] args) { SwingUtilities.invokeLater(() -> new DigitalClock()); }
Ensures thread safety by running GUI updates on the Event Dispatch Thread.
Creates an instance of DigitalClock, which sets up and displays the clock.
Step-by-Step Breakdown
Initialize the Frame:
We set up the main window (JFrame) for our digital clock.
Define Time Format:
We specify how the time will be displayed using SimpleDateFormat.
Create and Configure the Time Label:
We create a JLabel to show the time.
We set its font and alignment for better visibility.
Add the Label to the Frame:
The label is added to the frame so it will be displayed.
Set Up the Timer:
A Timer is created to update the time every second.
The updateTime() method is called every time the timer ticks.
Display the Frame:
We make the frame visible so the user can see the clock.
Update Time Method:
This method gets the current time and updates the label.
It is called by the timer every second.
Run the Application:
The main() method launches the application safely on the Event Dispatch Thread.
Enhancements and Customizations
1. Displaying the Date
You can modify the code to also display the current date.
Changes:
Add another JLabel for the date.
Update the updateTime() method to set the date.
Modified Code Snippet:
private JLabel dateLabel; private SimpleDateFormat dateFormat; public DigitalClock() { // ... existing code ... // Set up the date format dateFormat = new SimpleDateFormat("EEEE, MMMM dd, yyyy"); // Create a label to display the date dateLabel = new JLabel(); dateLabel.setFont(new Font("Verdana", Font.PLAIN, 25)); dateLabel.setHorizontalAlignment(SwingConstants.CENTER); // Add labels to the frame using a layout manager this.setLayout(new GridLayout(2, 1)); this.add(timeLabel); this.add(dateLabel); // ... existing code ... } private void updateTime() { String currentTime = timeFormat.format(new Date()); String currentDate = dateFormat.format(new Date()); timeLabel.setText(currentTime); dateLabel.setText(currentDate); }
2. Changing to 12-Hour Format
To display time in a 12-hour format with AM/PM:
Change the time format pattern.
Modified Code Snippet:
timeFormat = new SimpleDateFormat("hh:mm:ss a");
3. Customizing Appearance
Change Fonts: Use different fonts or styles.
Change Colors: Set background and foreground colors.
Example:
timeLabel.setForeground(Color.BLUE); timeLabel.setBackground(Color.BLACK); timeLabel.setOpaque(true);
Running the Application
To compile and run the application:
Save the code in a file named DigitalClock.java.
Compile the code using the command:
javac DigitalClock.java
Run the application using the command:
java DigitalClock
Note: Ensure that your Java Development Kit (JDK) is properly installed and configured.
Conclusion
By following this tutorial, you've created a functional digital clock using Java Swing.
This example demonstrates:
Creating a GUI application with Swing components.
Using Timer to perform actions at regular intervals.
Formatting dates and times with SimpleDateFormat.
Ensuring thread safety in Swing applications by using the Event Dispatch Thread.
You can further enhance this digital clock by adding new features like:
Alarm functionality.
Custom skins or themes.
Resizable fonts based on window size.
Additional time zones.
This project serves as a solid foundation for learning GUI programming in Java and can be expanded upon for more complex applications.