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.
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."
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. }
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:
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).
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:
GO
GO
GO
GO
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:
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