 |
|
|
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 Point( 150, 160 );
setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
setSize(300, 300);
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
while( true )
{
//get time info
cal = new GregorianCalendar();
hour = cal.get( Calendar.HOUR_OF_DAY );
min = cal.get( Calendar.MINUTE );
sec = cal.get( Calendar.SECOND );
milli = cal.get( Calendar.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 = getPoint( hourAngle, lenHour );
pMin = getPoint( minuteAngle, lenMin );
pSec = getPoint( secondAngle, lenSec );
//paint frame and let repaint thread run
repaint();
Thread.yield();
//wait for small amount of time
try
{
Thread.sleep(10);
}
catch( Exception e ) {}
}
}
/*
* Gets the outer point of a hand
*/
private Point getPoint( double 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 Point( centre );
ans.translate( (int)x, (int)y);
return ans;
}
public void paint( Graphics g )
{
//clear and display the time
if( pHour != null )
{
//clear the frame
g.setColor(Color.WHITE);
g.fillRect(0, 0, getWidth(), getHeight() );
g.setColor(Color.BLACK);
drawLine( g, centre, pHour );
drawLine( g, centre, pMin );
drawLine( g, centre, pSec );
}
}
/*
* Draw a line between point p and q, using the Graphics context g
*/
private void drawLine( Graphics g, Point p, Point q )
{
g.drawLine( p.x, p.y, q.x, q.y );
}
public static void main(String[] args)
{
new AnalogWatch();
}
}
|
|
|
 |