«Back to Home

Core Java

Topics

How To Make Digital Clock In Swing Java

Digital Clock in Swing
 
We can easily make the digital clock in Swing Java.
 
Let’s see an example of the digital clock, given below.
 
Code
  1. import javax.swing.*;  
  2. import java.awt.*;  
  3. import java.text.*;  
  4. import java.util.*;  
  5. public class DigitalClockExample implements Runnable {  
  6.     JFrame jf;  
  7.     Thread t = null;  
  8.     int hours = 0, minutes = 0, seconds = 0;  
  9.     String timeString = "";  
  10.     JButton b;  
  11.     DigitalClockExample() {  
  12.         jf = new JFrame();  
  13.         t = new Thread(this);  
  14.         t.start();  
  15.         b = new JButton();  
  16.         b.setBounds(15015015060);  
  17.         jf.add(b);  
  18.         jf.setSize(400400);  
  19.         jf.setLayout(null);  
  20.         jf.setVisible(true);  
  21.     }  
  22.     public void run() {  
  23.         try {  
  24.             while (true) {  
  25.                 Calendar cal = Calendar.getInstance();  
  26.                 hours = cal.get(Calendar.HOUR_OF_DAY);  
  27.                 if (hours > 12) {  
  28.                     hours -= 12;  
  29.                 }  
  30.                 minutes = cal.get(Calendar.MINUTE);  
  31.                 seconds = cal.get(Calendar.SECOND);  
  32.                 SimpleDateFormat f = new SimpleDateFormat("hh:mm:ss");  
  33.                 Date d = cal.getTime();  
  34.                 timeString = f.format(d);  
  35.                 printTime();  
  36.                 t.sleep(1000);  
  37.             }  
  38.         } catch (Exception e) {  
  39.         }  
  40.     }  
  41.     public void printTime() {  
  42.         b.setText(timeString);  
  43.     }  
  44.     public static void main(String[] args) {  
  45.         new DigitalClockExample();  
  46.     }  
  47. }  
58
59

Output

60
 
Summary

Thus, we learnt how to make the digital clock in Swing Java.