Start Search Contents Index Links About
AnalogWatch.java
/*
 * Author: Havard Rast Blok
 * E-mail:  
 * Web   : www.rememberjava.com
 */

import java.awt.*;
import java.util.*;
import javax.swing.*;

/**
 * An analog watch
 */
public class AnalogWatch extends JFrame
{
  //Cooridnates of the watch hands
  private double lenHour, lenMin, lenSec;
  private Point centre;
  private Point pHour, pMin, pSec;
  
  public AnalogWatch()
  {
    super("My watch");
    
    //set some constants; length of the hands and the centre point
    lenHour = 60;
    lenMin = 100;
    lenSec = 80;
    centre = new Point150160 );
    
    setDefaultCloseOperationJFrame.EXIT_ON_CLOSE );
    setSize(300300);
    show();
    
    showTime();
  }
  
  private void showTime()
  {
    GregorianCalendar cal;
    double hour, min, sec, milli;
    double hourAngle, minuteAngle, secondAngle, milliAngle;
    double PI2;
    
    PI2 = 2.0*Math.PI;
    
    //never ending loop
    whiletrue )
    {
      //get time info
      cal = new GregorianCalendar();
      hour = cal.getCalendar.HOUR_OF_DAY );
      min = cal.getCalendar.MINUTE );
      sec = cal.getCalendar.SECOND );
      milli = cal.getCalendar.MILLISECOND );
      
      //calculate angles
      milliAngle = milli/1000.0*PI2;
      secondAngle = (sec*PI2 + milliAngle)/60.0;
      minuteAngle = (min*PI2 + secondAngle)/60.0;
      hourAngle = (hour*PI2 + minuteAngle)/12.0;
     
      //calculate the end point of the hands
      pHour = getPointhourAngle, lenHour );
      pMin = getPointminuteAngle, lenMin );
      pSec = getPointsecondAngle, lenSec );
      
      //paint frame and let repaint thread run
      repaint();
      Thread.yield();
      
      //wait for small amount of time
      try
      {
        Thread.sleep(10);
      }
      catchException e ) {}
    }
  }
  
  /*
   * Gets the outer point of a hand
   */
  private Point getPointdouble angle, double len )
  {
    double x, y;
    Point ans;
    
    //shift the 0-angle from 12 o'clock till 3 o'clock
    angle -= 0.5*Math.PI;
    
    //calculate the position of the hand
    x = len*Math.cos(angle);
    y = len*Math.sin(angle);
    ans = new Pointcentre );
    ans.translate( (int)x, (int)y);
    
    return ans;
  }
  
  public void paintGraphics g )
  {
    //clear and display the time
    ifpHour != null )
    {
      //clear the frame
      g.setColor(Color.WHITE);
      g.fillRect(00, getWidth(), getHeight() );
      g.setColor(Color.BLACK);
      
      drawLineg, centre, pHour );
      drawLineg, centre, pMin );
      drawLineg, centre, pSec );
    }
  }
  
  /*
   * Draw a line between point p and q, using the Graphics context g
   */
  private void drawLineGraphics g, Point p, Point q )
  {
    g.drawLinep.x, p.y, q.x, q.y );
  }
  
  public static void main(String[] args)
  {
     new AnalogWatch();
  }
  
}


site: Håvard Rast Blok
mail:
updated: 27 July 2007