代码如下:
import java.awt.*;
import java.text.DateFormat;
import java.util.*;
import javax.swing.*;
public class ClockDemo extends JFrame implements Runnable{
Thread clock;
final int Xpoint=180;
final int Ypoint=180;
final int R=80;
int xHour=0,yHour=0,xSecond=0,ySecond=0,xMin=0,yMin=0;
public ClockDemo(){
super("数字时钟");
setFont(new Font("宋体体",Font.BOLD,20));
start();
setSize(360,360);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void start(){
if(clock==null)
clock=new Thread(this);//实例化进程
clock.start(); //开始进程
}
public void run(){ //运行进程
while(clock!=null){
repaint();
try{
Thread.sleep(1000);//线程暂停1000ms
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
public void stop(){
clock=null;
}
public void paint(Graphics g){
Graphics2D g1=(Graphics2D)g;
DateFormat dateFormat=DateFormat.getDateInstance(DateFormat.FULL);
Calendar now=new GregorianCalendar();//实例化日历对象
now.setTime(new Date());
String timeInfo="";//输出信息
int hour=now.get(Calendar.HOUR_OF_DAY); //得到小时数
int minute=now.get(Calendar.MINUTE); //得到分数
int second=now.get(Calendar.SECOND); //得到秒数
if(hour<=9)
timeInfo+="0"+hour+":";
else
timeInfo+=hour+":";
if(minute<=9)
timeInfo+="0"+hour+":";
else
timeInfo+=minute+":";
if(second<=9)
timeInfo+="0"+second;
else
timeInfo+=second;
g.setColor(Color.yellow);
Dimension dim=getSize(); //得到窗口尺寸
g.fillRect(0, 0, dim.width, dim.height);
g.setColor(Color.red);
g.drawString(timeInfo,130,140); //显示时间字符串
g.setColor(Color.green);
g.drawString(dateFormat.format(now.getTime()), 20, 60);
g.setColor(Color.black);
g.setFont(new Font("SAN_SERTF",Font.BOLD,15));
for(int i=0,num=12;i<360;i++){
double alfa=Math.toRadians(i);
int xPos=Xpoint+(int)(R*Math.sin(alfa));
int yPos=Ypoint+(int)(R*Math.cos(alfa));
if(i==0){
if(num%3==0)
g.setColor(Color.red); //数字3,6,9,12为红色
else
g.setColor(Color.black);
g.drawString(""+num, xPos-5, yPos+3); //写数字
num+=1;
}
else{
g.setColor(Color.black);
g.drawString(".",xPos,yPos );
}
}
g.setColor(Color.black);
g.fillOval(Xpoint-4, Ypoint-4, 8, 8);
//画秒针
xSecond=(int)(Xpoint+(R-10)*Math.sin(second*(2*Math.PI/60)));
ySecond=(int)(Ypoint-(R-10)*Math.cos(second*(2*Math.PI/60)));
g.setColor(Color.red);
g.drawLine(Xpoint, Ypoint, xSecond, ySecond);
//画分针
xMin=(int)(Xpoint+(R-20)*Math.sin((minute+second/60)*(2*Math.PI/60)));
yMin=(int)(Xpoint-(R-20)*Math.cos((minute+second/60)*(2*Math.PI/60)));
g.setColor(Color.red);
g.drawLine(Xpoint, Ypoint, xMin, yMin);
//画时针
xHour=(int)(Xpoint+(R-30)*Math.sin((hour+minute/60+second/60/60)*(2*Math.PI/12)));
yHour=(int)(Ypoint-(R-30)*Math.cos((hour+minute/60+second/60/60)*(2*Math.PI/12)));
g.setColor(Color.red);
g.drawLine(Xpoint, Ypoint, xHour, yHour);
}
public static void main(String[]args){
new ClockDemo();
}
}