Java digital clock program code
Import java. awt .*;
Import java. util .*;
Import javax. swing .*;
// Digital clock
Public class ClockDemo extends JFrame implements Runnable {
Thread clock;
Public ClockDemo (){
Super ("Digital Clock"); // calls the parent class Constructor
SetFont (new Font ("Times New Roman", Font. BOLD, 60); // set the Font of the clock.
Start (); // start the process
SetSize (280,100); // set the window size
SetVisible (true); // visible window
Setdefaclocloseoperation (JFrame. EXIT_ON_CLOSE); // exit the program when the window is closed.
}
Public void start () {// start the process
If (clock = null) {// if the process is null
Clock = new Thread (this); // instantiate the process
Clock. start (); // start the process
}
}
Public void run () {// run the process
While (clock! = Null ){
Repaint (); // call the paint method to repaint the interface
Try {
Thread. sleep (1000); // Thread pause for one second (1000 ms)
}
Catch (InterruptedException ex ){
Ex. printStackTrace (); // output error message
}
}
}
Public void stop () {// stop the process
Clock = null;
}
Public void paint (Graphics g) {// The paint method of the overload component
Graphics2D g2 = (Graphics2D) g; // obtain the Graphics2D object.
Calendar now = new GregorianCalendar (); // instantiate a Calendar Object
String timeInfo = ""; // output information
Int hour = now. get (Calendar. HOUR_OF_DAY); // get the hours
Int minute = now. get (Calendar. MINUTE); // get the score
Int second = now. get (Calendar. SECOND); // get the number of seconds
If (hour <= 9)
TimeInfo + = "0" + hour + ":"; // format the output.
Else
TimeInfo + = hour + ":";
If (minute <= 9)
TimeInfo + = "0" + minute + ":";
Else
TimeInfo + = minute + ":";
If (second <= 9)
TimeInfo + = "0" + second;
Else
TimeInfo + = second;
G. setColor (Color. white); // set the current Color to white.
Dimension dim = getSize (); // obtain the window size.
G. fillRect (, dim. width, dim. height); // fill the background color in white.
G. setColor (Color. orange); // set the current Color to orange.
G. drawString (timeInfo, 20, 80); // display the time string
}
Public static void main (String [] args ){
New ClockDemo ();
}
}