Digital Clock In Java Applet

Introduction

 
In this article, we describe how to create a digital clock using a Java applet. we discuss how to make a digital clock using an applet in Java. To make a digital clock we need to use the Thread and Graphics classes of Java. Threads are used to change the seconds, minutes, and hours of the clock and the Graphics class is used for the design of the clock.
 

Digital Clock in Java

 
In the following example, we create a digital clock in the applet by the use of the Calendar class and SimpleDateFormat class. The following figure describes the digital clock's formatting.
 
digital clock in Java
 

Calendar class in Java 

 
It is an abstract class that sets the calendar fields, such as MONTH,  HOUR, YEAR, DAY_OF_MONTH, and so on, and for manipulating the calendar fields, such as getting the date of the next month.
 

SimpleDateFormat class

 
As its name implies, it's used to set the format of the date.
 
Program coding
  1. import java.util.*;  
  2. import java.text.*;  
  3. import java.applet.*;  
  4. import java.awt.*;  
  5. public class SimpleDigitalClock extends Applet implements Runnable  
  6. {  
  7.     Thread thr = null;  
  8.     int clkhours = 0, clkminutes = 0, clkseconds = 0;  
  9.     String clkString = "";  
  10.     public void init()  
  11.     {  
  12.         setBackground(Color.blue);  
  13.     }  
  14.     public void start()  
  15.     {  
  16.         thr = new Thread(this);  
  17.         thr.start();  
  18.     }  
  19.     public void run()  
  20.     {  
  21.         try  
  22.         {  
  23.             while (true)  
  24.             {  
  25.                 Calendar calndr = Calendar.getInstance();  
  26.                 clkhours = calndr.get(Calendar.HOUR_OF_DAY);  
  27.                 if (clkhours > 12) clkhours -= 12;  
  28.                 clkminutes = calndr.get(Calendar.MINUTE);  
  29.                 clkseconds = calndr.get(Calendar.SECOND);  
  30.                 SimpleDateFormat frmtr = new SimpleDateFormat("hh:mm:ss");  
  31.                 Date date = calndr.getTime();  
  32.                 clkString = frmtr.format(date);  
  33.                 repaint();  
  34.                 thr.sleep(1000);  
  35.             }  
  36.         } catch (Exception excp) {}  
  37.     }  
  38.     public void paint(Graphics grp)  
  39.     {  
  40.         grp.setColor(Color.red);  
  41.         grp.drawString(clkString, 150150);  
  42.     }  
  43. }  
  44. /* 
  45. <applet code="SimpleDigitalClock.class" width="400" height="400"> 
  46. </applet> 
  47. */  
Output
 
digital clock in Java
 
After one minute the clock shows the following:
 
digital clock in Java