Friday, 11 May 2012

Create your own Clock in Java

Many programmers would like to create a Clock of his own. Today I am going to post a code on creating a digital cum analog clock using Java. This requires some mathematical calculations to find the position of the clock hands and numbers. This is done using java's Math class API. Here is the code for you ->


import  java.util.concurrent.*;
import java.awt.*;
import java.util.*;
import javax.swing.*;
import javax.swing.border.*;
import java.lang.*;
import java.text.*;
import java.awt.event.*;


public class Clock extends JApplet {
    private int r;
    private boolean firsttime;
    private int x4, y4, xx4, yy4, x5, y5, xx5, yy5, x6, y6, xx6, yy6 ;
       
    private SimpleDateFormat formatter;  // Formats the date displayed
        private String todaydate,time;
        private Date currentDate;
        public void init() {
          r = 150;
          firsttime=true;
         MyThread mt = new MyThread(this);
         mt.start();
     }
   
    public void paint(Graphics g) {
        Graphics2D g2 = (Graphics2D)g;
       int theta, r1, r2, r3, r4,rr4,r5, rr5, r6, rr6, x1, x2, y1, y2, x3, y3 ;
       double radian;
       g2.translate(250, 250);
       if(firsttime) {
          g2.setColor(new Color(0, 0, 0));
          g2.setStroke(new BasicStroke(5));
          g2.drawOval(-r, -r, 2 * r, 2 * r);
          g2.fillOval(-r, -r, 2 * r, 2 * r);
          g2.setColor(new Color(255, 0, 0));
          g2.setStroke(new BasicStroke(2));
       
         for (theta = 0; theta < 360; theta += 6) {
            radian = theta * Math.PI / 180;
            r1 = theta % 30 != 0 ? r - 5 : r - 10;
            x1 = (int)(r1 * Math.cos(radian));
            y1 = (int)(r1 * Math.sin(radian));
            r2 = r;
            x2 = (int)(r2 * Math.cos(radian));
            y2 = (int)(r2 * Math.sin(radian));
            g2.drawLine(x1, y1, x2, y2);
        }
        g2.translate(-5, 3);
        r3 = r - 19;
        g2.setColor(new Color(84,245,245));
        ///draw number on  clock face
        for (theta = 0; theta < 360; theta += 6) {
            radian = theta * Math.PI / 180;
            if (theta % 30 == 0) {
                x3 = (int)(r3 * Math.cos(radian));
                y3 = (int)(r3 * Math.sin(radian));
                g2.drawString((theta == 270 ? 12 : (theta / 30 + 3) % 12) + "", x3, y3);
            }
        }
       
        firsttime=false;
       
        g2.translate(5, -3);   //after translation the center point is rebuild into ( 250,250 )
        }
        GregorianCalendar gc = new GregorianCalendar();
        currentDate = new Date();
        //date showing format
        formatter = new SimpleDateFormat ( "MMM dd EEE ", Locale.getDefault() );
        todaydate = formatter.format(currentDate);
        //time showing format
        formatter = new SimpleDateFormat ("hh:mm:ss ", Locale.getDefault());                      
        time=formatter.format(currentDate);
                           
        int hour = gc.get(Calendar.HOUR);
        int minute = gc.get(Calendar.MINUTE);
        int second = gc.get(Calendar.SECOND);
        int millisecond = gc.get(Calendar.MILLISECOND);
       
        //hour pointer
        radian =  (((30 * hour)+(minute/2))-90) * Math.PI / 180; 
        r4=3;
        rr4 = r-40;
        //cleanig process of previous hour pointer
        g2.setStroke(new BasicStroke(2));
        g2.setColor(new Color(0, 0, 0));
        g2.drawLine(x4,y4,xx4,yy4);
        x4=  (int)(r4 * Math.cos(radian));
        y4 = (int)(r4 * Math.sin(radian));
        xx4 = (int)(rr4 * Math.cos(radian));
        yy4 = (int)(rr4 * Math.sin(radian));
       
        //minute pointer
        radian =  (((minute*6)+(second/12))-90) * Math.PI / 180; 
        r5=9;
        rr5 = r-35;
        //cleanig process of previous minute pointer
        g2.setStroke(new BasicStroke(2));       
        g2.drawLine(x5,y5,xx5,yy5);
       
        x5=  (int)(r5 * Math.cos(radian));
        y5 = (int)(r5 * Math.sin(radian));
        xx5 = (int)(rr5 * Math.cos(radian));
        yy5 = (int)(rr5 * Math.sin(radian));
       
        //second pointer
        radian =  ((( second*6)+(millisecond/200))-90) * Math.PI / 180; 
        r6=13;
        rr6 = r-30;
        //cleanig process of previous second pointer
        g2.setStroke(new BasicStroke(2));
        g2.drawLine(x6,y6,xx6,yy6);
        x6=  (int)(r6 * Math.cos(radian));
        y6 = (int)(r6 * Math.sin(radian));
        xx6 = (int)(rr6 * Math.cos(radian));
        yy6 = (int)(rr6 * Math.sin(radian));
               
        //time showing box       
        g2.setColor(new Color(255,255,255));
        g2.fillRect(-40,50,80,20);
        g2.setColor(new Color(207,158,248));
        g2.drawRect(-40,50,80,20);
        g2.setColor(new Color(0,0,0));
        g2.drawString(time+(gc.get(Calendar.AM_PM)==1?"PM":"AM"),-35,65);
       
        //date showing box
        g2.setColor(new Color(255,255,255));
        g2.fillRect(40,-15,80,20);
        g2.setColor(new Color(207,158,248));
        g2.drawRect(40,-15,80,20);
        g2.setColor(new Color(0,0,0));
        g2.drawString(todaydate,45,0);
       
        //draw hour pointer
        g2.setColor(new Color(4,255,250));
        g2.setStroke(new BasicStroke(2));
        g2.drawOval(-3,-3,6,6);
        g2.drawLine(x4,y4,xx4,yy4);
       
        //draw minute pointer
        g2.setColor(new Color(255,0,0));
        g2.setStroke(new BasicStroke(2));
        g2.drawOval(-9,-9,18,18);
        g2.drawLine(x5,y5,xx5,yy5);
       
        //draw second pointer
        g2.setStroke(new BasicStroke(2));
        g2.setColor(new Color(11, 196, 6));
        g2.drawOval(-13,-13,26,26);
        g2.drawLine(x6,y6,xx6,yy6);
             
    }
          public static void main(String s[]) throws Exception{
         final JFrame f = new JFrame("Clock");
         final JApplet applet = new Clock();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          f.setBackground(new Color(253,206,243));
          f.setSize(500,500);
          f.setVisible(true);
          javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
            applet.repaint();   
            f.setLayout(new FlowLayout());   
            }
        });
          TimeUnit.SECONDS.sleep(0);
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
      public void run() {
         applet.setSize(500,500);
         f.add(applet);
         applet.init();   
       }
     });
       } 
}


class MyThread extends  Thread {
    private Clock c;
    public MyThread(Clock c) {
        this.c = c;
    }
    public void run() {
        while (true) {
            try {
                Thread.sleep(1000);
                c.repaint();
            }
            catch (Exception e) {
            }
       }
    }   

You can also download source from below link->
Download Java source file from Mediafire
Hope this helps .

No comments:

Post a Comment