Monday, November 14, 2011

Analog Clock Demonstration using Java Applets

Java Applet program to demo Analog Clock

import java.applet.*;
import java.awt.*;
import java.util.*;
public class AnalogClock2 extends Applet implements Runnable {
   int width, height;
   Thread t = null;
   boolean threadSuspended;
   int hours=0, minutes=0, seconds=0;
   String timeString = "";
   public void init() {
      resize(300,300);
      width = getSize().width;
      height = getSize().height;
      setBackground( Color.BLACK);
   }
   public void start() {
         t = new Thread( this );
         t.start();
   }
   public void run() {
      try {
         while (true) {
            Calendar cal = Calendar.getInstance();
            hours = cal.get( Calendar.HOUR_OF_DAY );
            if ( hours > 12 )
                hours -= 12;
            minutes = cal.get( Calendar.MINUTE );
            seconds = cal.get( Calendar.SECOND );
            repaint();
            t.sleep(995);  // interval given in milliseconds
         }
      }
      catch (InterruptedException e) { }
   }
   void drawHand( double angle, int radius, Graphics g ) {
      angle -= 0.5 * Math.PI;
      int x = (int)( radius*Math.cos(angle) );
      int y = (int)( radius*Math.sin(angle) );
      g.drawLine( width/2, height/2, width/2 + x, height/2 + y );
   }
   void drawWedge( double angle, int radius, Graphics g ) {
      angle -= 0.5 * Math.PI;
      int x = (int)( radius*Math.cos(angle) );
      int y = (int)( radius*Math.sin(angle) );
      angle += 2*Math.PI/3;
      int x2 = (int)( 5*Math.cos(angle) );
      int y2 = (int)( 5*Math.sin(angle) );
      angle += 2*Math.PI/3;
      int x3 = (int)( 5*Math.cos(angle) );
      int y3 = (int)( 5*Math.sin(angle) );
      g.drawLine( width/2+x2, height/2+y2, width/2 + x, height/2 + y );
      g.drawLine( width/2+x3, height/2+y3, width/2 + x, height/2 + y );
   }
   public void paint( Graphics g ) {
      g.setColor( Color.red );
      for(int i=1;i<=12;i++)
        g.drawString(""+i,width/2+(int)(140*Math.sin(2*Math.PI * i / 12)), height/2-(int) (140*Math.cos(2*Math.PI * i / 12)) );
      boolean flag=true;
      g.setColor( Color.blue );
      g.setColor( Color.PINK);
      g.drawOval(WIDTH, WIDTH, width, height);
      g.drawOval(WIDTH+30, WIDTH+30, width-60, height-60);
      g.drawOval(width/2-5, height/2-5, 10, 10);
      g.setColor( Color.darkGray );
      drawWedge( 2*Math.PI * (hours/12.0+minutes/720.0 ), width/6, g );
      g.setColor( Color.BLUE );
      drawWedge( 2*Math.PI * minutes / 60, width/4, g );
      g.setColor( Color.MAGENTA );
      drawHand( 2*Math.PI * seconds / 60, width/3+10, g );
      g.setColor( Color.white );
      g.drawString( timeString, 10, height-10 );
   }
}

No comments:

Post a Comment