import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.*;
/**
* @author Administrator
* 用三角函数画时钟
*/
public class SimClock extends JFrame{
double h = 0,m = 0,sec = 0;//模拟时间
int ih = 0,im = 0,isec = 0;//数字时间
private int dotX = 170,dotY = 200;//圆心坐标
private int r = 100;//圆[表盘]的半径
private MyTimer timer;//定时器
SimClock(){
super("模拟时钟");
this.setResizable(false);
timer = new MyTimer(this);
timer.start();
this.setSize(340,350);
//获取显示器屏幕大小
Dimension dim = getToolkit().getScreenSize();
//在显示器的中间位置显示本窗口
this.setLocation((dim.width-getSize().width)/2,(dim.height-getSize().height)/2-100);
setVisible(true);
}
public void paint(Graphics g){
super.paint(g);
double x,y;
g.drawString("现在时间 : "+ih+":"+im+":"+isec, dotX-r/2, dotY-r-20);//显示数字时间
g.fillOval(dotX-9,dotY-9,18,18);//填充中心点的圆
//画表盘
for(int i = 0;i <= 360;i += 6){
int dot;
if(i%90 == 0){//画12,3,6,9点的位置
g.setColor(Color.red);
dot = 5;
}else if(i%30 == 0){//画 1,2,4,5,7,8,10,11点的位置
g.setColor(Color.blue);
dot = 2;
}else{// 画剩余点位置
g.setColor(Color.black);
dot = 1;
}
//获得'点'在表盘上的坐标
x = Math.cos(Math.PI*i/180.0)*r;
y = Math.sin(Math.PI*i/180.0)*r;
g.fillOval(dotX+(int)x-dot,dotY-(int)y-dot,2*dot,2*dot);
}
g.setColor(Color.black);
//
//画时针
//
//获得'点'在表盘上的坐标
x = Math.cos(Math.PI*h/180.0)*(r-40);
y = Math.sin(Math.PI*h/180.0)*(r-40);
//画时针线
g.drawLine(dotX,dotY,dotX+(int)x,dotY-(int)y);
//
//画分针
//
//获得'点'在表盘上的坐标
x = Math.cos(Math.PI*m/180.0)*(r-10);
y = Math.sin(Math.PI*m/180.0)*(r-10);
//画分针线
g.drawLine(dotX,dotY,dotX+(int)x,dotY-(int)y);
//
//画秒针
//
g.setColor(Color.blue);
//获得'点'在表盘上的坐标
x = Math.cos(Math.PI*sec/180.0)*r;
y = Math.sin(Math.PI*sec/180.0)*r;
//画秒针上边的圆圈
g.fillOval(dotX+(int)x-4,dotY-(int)y-4,8,8);
//画秒针线
g.drawLine(dotX,dotY,dotX+(int)x,dotY-(int)y);
}
public static void main(String[] args){
SimClock t = new SimClock();
t.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
import java.util.*;
public class MyTimer extends Thread{
private SimClock t;
MyTimer(SimClock t){
this.t = t;
}
public void run(){
while(true){
try{
sleep(1000);
}catch(InterruptedException e){}
Calendar time = new GregorianCalendar();
t.ih = time.get(Calendar.HOUR_OF_DAY);
t.im = time.get(Calendar.MINUTE);
t.isec = time.get(Calendar.SECOND);
t.m = -(double)(t.im-15)*6;
t.h = -(double)(t.ih-3)*30-t.im/2;
t.sec = -(double)(t.isec-15)*6;
t.repaint();
}
}
}