【JAVA】时钟设计

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;
public class ClockPanel extends JPanel{
	private JTextField  hourField;
	private JTextField  minuteField;
	private double hour;
	private double minute;

	public ClockPanel(){
		hour=0;
		minute=0;
		add(new JLabel("Hour:"));
		hourField=new JTextField(5);
		add(hourField);
		
		add(new JLabel("Minute:"));
		minuteField=new JTextField(5);
		add(minuteField);
		
		add(createButton("Draw"));
	}
	public void paint(Graphics g)
	{
		double r;//弧度
		super.paint(g);
		g.setColor(Color.blue); 
		g.drawOval(150, 150, 200, 200);//画圆
		
		g.drawString("12", 245 , 145);  
        g.drawString("3", 355, 250);  
        g.drawString("9", 140, 250);  
        g.drawString("6", 249, 365); 
		
		r = minute / 60.0*2*Math.PI - Math.PI / 2;
		drawHand(r,100,g);//分针
		r = (hour*60.0 +minute)/(12*60)*2*Math.PI - Math.PI / 2;
		drawHand(r,50,g);//时针
	}
	//r弧度,size长度
	private void drawHand(double r,int size,Graphics g)
	{
		g.drawLine(250, 250, (int)(250+Math.cos(r)*size), (int)(250+Math.sin(r)*size));
	}
	
	private JButton createButton(String label)
	{
		JButton result=new JButton(label);
		class AddActionLister implements ActionListener
		{
			public void actionPerformed(ActionEvent evt)
			{
				hour=Double.parseDouble(hourField.getText());
				minute=Double.parseDouble(minuteField.getText());
				repaint();
			}
		}
		result.addActionListener(new AddActionLister());
		return result;
	}	
}

测试类

import javax.swing.JFrame;

public class ClockFaceTester{

	public static void main(String args[]){
		ClockPanel cp=new ClockPanel();
		JFrame JF=new JFrame();
		
		JF.setSize(550,500);
		JF.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		JF.setTitle("时钟");
		JF.add(cp);
		JF.setVisible(true);
		
	}
}

运行结果:

【JAVA】时钟设计_第1张图片

你可能感兴趣的:(JAVA)