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.
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
- import java.util.*;
- import java.text.*;
- import java.applet.*;
- import java.awt.*;
- public class SimpleDigitalClock extends Applet implements Runnable
- {
- Thread thr = null;
- int clkhours = 0, clkminutes = 0, clkseconds = 0;
- String clkString = "";
- public void init()
- {
- setBackground(Color.blue);
- }
- public void start()
- {
- thr = new Thread(this);
- thr.start();
- }
- public void run()
- {
- try
- {
- while (true)
- {
- Calendar calndr = Calendar.getInstance();
- clkhours = calndr.get(Calendar.HOUR_OF_DAY);
- if (clkhours > 12) clkhours -= 12;
- clkminutes = calndr.get(Calendar.MINUTE);
- clkseconds = calndr.get(Calendar.SECOND);
- SimpleDateFormat frmtr = new SimpleDateFormat("hh:mm:ss");
- Date date = calndr.getTime();
- clkString = frmtr.format(date);
- repaint();
- thr.sleep(1000);
- }
- } catch (Exception excp) {}
- }
- public void paint(Graphics grp)
- {
- grp.setColor(Color.red);
- grp.drawString(clkString, 150, 150);
- }
- }
-
-
-
-
Output
After one minute the clock shows the following: