编写程序显示一个时钟

编写程序显示一个时钟。示例输出如图所示。

代码:

 

package com.DisplayClock;

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

public class DisplayClock{
	Thread hourThread = null;	//时针线程
	Thread minuteThread = null; 	//分针线程
	Thread secondThread = null;	//秒针线程
	int currentHour = 0;	//获取当前时间中代表小时的数字值
	int currentMinute = 0;	//获取当前时间中代表分钟的数字值
	int currentSecond = 0;	//获取当前时间中代表秒数字值
	
	int isRestart = 0;	//判断是否重新开始
	
	public static void main(String[] args){
		EventQueue.invokeLater(new Runnable()
		{
			public void run()
			{
				DrawFrame frame = new DrawFrame();
				frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
				frame.setVisible(true);
				
			}
		});
	}
}
class DrawFrame extends JFrame{
	public DrawFrame()
	{
		setTitle("DisplayClock");//设置显示窗的标题
		setSize(DEFAULT_WIDTH,DEFAULT_HEIGHT);//设置窗口的大小
		DrawComponent component = new DrawComponent();
		//创建要建立的图形的对象
		add(component);
		//将该图形加入到面板上
	}
	public static final int DEFAULT_WIDTH = 500;
	//设置窗口的宽度
	public static final int DEFAULT_HEIGHT = 500;
	//设置窗口的高度
} 
//建立时钟图形
class DrawComponent extends JComponent
{
	public void paintComponent(Graphics g)
	{
		g.setColor(Color.blue);
		Graphics2D g2 = (Graphics2D) g;
		Ellipse2D circle = new Ellipse2D.Double();
		circle.setFrameFromCenter(200,200,300,300);
		g2.draw(circle);
		//用来写表盘上的刻度
		g.setColor(Color.green);
		double jiaodu = Math.PI / 2;
		double keX[] = new double[60];//存放表盘刻度的起始X坐标
		double keY[] = new double[60];//存放表盘刻度的起始Y坐标
		double duX[] = new double[60];//存放表盘刻度的终止X坐标
		double duY[] = new double[60];//存放表盘刻度的终止Y坐标
		
		for(int i = 0;i < 60;i++){
			if(i == 0||i%5 == 0)
			{
				keX[i] = 200 + 80 * Math.cos(jiaodu);
				keY[i] = 200 - 80 * Math.sin(jiaodu);	
			}
			else
			{
			keX[i] = 200 + 90 * Math.cos(jiaodu);
			keY[i] = 200 - 90 * Math.sin(jiaodu);
			}
			duX[i] = 200 + 100 * Math.cos(jiaodu);
			duY[i] = 200 - 100 * Math.sin(jiaodu);
			jiaodu = jiaodu - Math.PI / 30;
		}
		for(int j =0;j < 60;j++){
			g2.draw(new Line2D.Double(keX[j],keY[j],duX[j],duY[j]));
		}
			
		//画12点的指针秒针
		
		g.setColor(Color.black);
		
		g2.draw(new Line2D.Double(200,200,200,130));
		
		//画出分针
        g.setColor(Color.BLUE);
		
		g2.draw(new Line2D.Double(200,200,200,140));
		//画出时针
        g.setColor(Color.PINK);
		
		g2.draw(new Line2D.Double(200,200,200,150));
	}
}

你可能感兴趣的:(java,DisplayClock,编写程序显示一个时钟)