Digital Clock In Java Applet

Introduction

In this article we describe how to create a digital clock using a Java applet.

Description

In this article 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 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.jpg

Calendar class

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);

      }

  }

/*

<applet code="SimpleDigitalClock.class" width="400" height="400">

</applet

*/

Output

fig-1.jpg

After one minute the clock shows the following:

fig-2.jpg

Up Next
    Ebook Download
    View all
    Learn
    View all