How to Create a Digital Clock 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.

...
Create a digital clock readout in Java.

Step

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.\"

Step

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

Step

/ _ 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. }

Step

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

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

Step

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

Step

GO

Step

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).

Step

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

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

Step

GO

Step

GO

Step

GO

Step

GO

Step

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

Step

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

Step

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

Step

GO }

Step

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

Step

GO }