자바 시계

3390 단어
더 읽 기
package com.good.test;

import java.awt.BasicStroke;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.util.Date;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class ClockPanel extends JPanel
{

	private static final long serialVersionUID = 4523747293746641642L;

	@Override
	public void paint(Graphics g)
	{
		super.paint(g);
		Graphics2D g2d = (Graphics2D) g;
		g2d.setStroke(new BasicStroke(3));
		g2d.drawOval(50, 50, 400, 400);//    (250,250)
		for (int i = 0; i < 60; i++)
		{
			int[] t = getPoint(i * 6, 200);
			int[] t1 = new int[2];
			if (i % 5 == 0)
			{
				if (i % 3 == 0)
				{
					g2d.setStroke(new BasicStroke(3));
					t1 = getPoint(i * 6, 180);
				} else
				{
					g2d.setStroke(new BasicStroke(2));
					t1 = getPoint(i * 6, 190);
				}
			} else
			{
				g2d.setStroke(new BasicStroke(1));
				t1 = getPoint(i * 6, 195);
			}
			g2d.drawLine(t[0], t[1], t1[0], t1[1]);
		}
		Date d = new Date();
		int h = d.getHours();
		int m = d.getMinutes();
		int s = d.getSeconds();

		double arc_s = s * 6 + 90;
		double arc_m = (m + s / 60.0) * 6 + 90;
		double arc_h = 0;
		if (h > 12)
			h = h - 12;
		arc_h = (h + m / 60.0) * 30 + 90;
		int[] st = getPoint(arc_s, 160);
		int[] mt = getPoint(arc_m, 130);
		int[] ht = getPoint(arc_h, 90);

		g2d.setStroke(new BasicStroke(1));
		g2d.setColor(Color.BLACK);
		g2d.drawLine(250, 250, st[0], st[1]);

		g2d.setStroke(new BasicStroke(2));
		g2d.setColor(Color.RED);
		g2d.drawLine(250, 250, mt[0], mt[1]);

		g2d.setStroke(new BasicStroke(3));
		g2d.setColor(Color.BLUE);
		g2d.drawLine(250, 250, ht[0], ht[1]);

		g2d.setColor(Color.RED);
		Font font = new Font("   ", Font.BOLD, 17);
		g2d.setFont(font);
		g2d.drawString("Hour: " + h + " Minute: " + m + " Second: " + s, 150,
				500);

	}

	public int[] getPoint(double arc, int r)
	{
		double sin = Math.sin(Math.toRadians(arc));
		double cos = Math.cos(Math.toRadians(arc));
		return new int[]
		{ (int) (250 - r * cos), (int) (250 - r * sin) };
	}

	public static void main(String[] args)
	{
		final JFrame frame = new JFrame();
		frame.add(new ClockPanel(), BorderLayout.CENTER);
		frame.setTitle("Clock!");
		frame.setSize(600, 600);
		frame.setLocation(100, 100);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setResizable(false);
		frame.setVisible(true);
		new Thread(new Runnable()
		{
			@Override
			public void run()
			{
				while (true)
				{
					frame.repaint();
					try
					{
						Thread.currentThread().sleep(1000);
					} catch (InterruptedException e)
					{
						e.printStackTrace();
					}
				}
			}

		}).start();
	}

}

좋은 웹페이지 즐겨찾기