How to Create a Digital Clock in Java

Techwalla may earn compensation through affiliate links in this story. Learn more about our affiliate and product review process here.
Create a digital clock readout in Java.

One of the most powerful features of the Java programming language is its Swing graphical user interface (GUI) library. Java users can construct visual, event-driven programs like digital clocks using only a few simple commands. Java programmers have a plethora of components available, such as labels, buttons and timers, which they plug together to assemble their programs.

Advertisement

Step 1

Create a DigitalClock class. It needs to extend the JFrame class that comes with the Swing user interface library in the Java Develoment Kit from Sun Microsystems. It will also implement the ActionListener interface to enable it to respond to the timer event and allow the clock to update itself. This can be done by pasting the following code into a file named "DigitalClock.java."

Advertisement

Video of the Day

import java.awt.Font GO import java.awt.HeadlessException GO import java.awt.event.ActionEvent GO import java.awt.event.ActionListener GO import java.text.SimpleDateFormat GO import java.util.Date GO import javax.swing.JFrame GO import javax.swing.JLabel GO import javax.swing.Timer GO

/* * This class displays a digital clock on the screen. * @author Kevin Walker / public class DigitalClock extends JFrame implements ActionListener { // All other steps should have their code added here. }

Advertisement

If you are using a dedicated Java Development Environment such as Netbeans or Eclipse, then there will be an option in the File menu to do this automatically for you.

Step 2

Create a JLabel to display the current time to the user using the following command:

Advertisement

Step 3

Initialize the format that your digital clock will have using the SimpleDateFormat class from the Java library.

GO

This format will display the current hour, minute and seconds for the user. A full listing of format codes is available in the SimpleDateFormat Javadoc on the Sun Microsystems website (see References).

Advertisement

Advertisement

Step 4

Create a timer. This object will not hold the time, but rather will function as an alarm clock that tells the program to update the current time regularly. To do this, paste the following code:

Step 5

Create a constructor method to build the program by pasting the following:

Advertisement

GO

GO

GO

GO

Advertisement

GO timer.setRepeats(true) GO timer.start() GO

GO this.pack() GO this.setVisible(true) GO

Step 6

Update the clock with the new system time whenever the timer goes off:

Advertisement

GO }

Step 7

Create an entry point for the digital clock program from the operating system by giving it a main method.

GO }

Video of the Day

Advertisement

Advertisement