Introduction
Java Swing is a Java GUI widget toolkit that comes with various useful widgets. It is a part of the Java Foundation Classes(JFC). JFC contains many packages for creating desktop applications.
We can also use Java Swing to create a Digital clock.
Java Swing Program to create a Digital watch
We will use the following Java packages:
- swing package
- awt package
- A util package
- The text package
Algorithm
- To create a frame, we must first import the swing package.
- Then, the util package will be used to build the user interface.
- We also use a text package to write the program where date-time is required.
- We first create a frame and define its dimensions.
- We then set the values of all the variables to zero and initialize the three variables Hours, Minutes, and Seconds.
- In this software, the Calendar class is used. The abstract class that gives us access to date, time, year, and month methods is the Java Calendar class.
-
The millisecond interval is provided by Sleep(1000).
// Java program to create digital watch
import javax.swing.*;
import java.awt.*;
import java.text.*;
import java.util.*;
public class DigitalWatch implements Runnable{
JFrame frame;
Thread thread=null;
int hours=0, minutes=0, seconds=0;
String timeString = "";
JButton button;
DigitalWatch(){
frame=new JFrame();
thread = new Thread(this);
thread.start();
button=new JButton();
button.setBounds(100,100,100,50);
frame.add(button);
frame.setSize(300,400);
frame.setLayout(null);
frame.setVisible(true);
}
public void run() {
try {
while (true) {
Calendar cal = Calendar.getInstance();
hours = cal.get( Calendar.HOUR_OF_DAY );
if ( hours > 12 )
{hours -= 12;}
minutes = cal.get( Calendar.MINUTE );
seconds = cal.get( Calendar.SECOND );
SimpleDateFormat formatter = new SimpleDateFormat("hh:mm:ss");
Date date = cal.getTime();
timeString = formatter.format(date);
printTime();
thread.sleep(1000); //in milliseconds
}
}
catch (Exception e) { }
}
public void printTime(){
button.setText(timeString);
}
public static void main(String[] args) {
new DigitalWatch();
}
}
The output of the program

Read also Swing components in java






