java模拟时钟(一个庞大的问题)
程序代码:
import java.awt.Color; import java.awt.Container; import java.awt.Dimension; import java.awt.Font; import java.awt.Graphics; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Calendar; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.Timer; public class Clock extends JComponent implements Runnable{ Thread thread; Calendar currentTime;//当前时间 int hours = 0; int minutes = 0; int seconds = 0; public Clock() { setBounds(0,0,300,400); setBackground(Color.PINK); thread = new Thread(); thread.start(); } public void PaintClock(Graphics g) { g.setColor(Color.black);//设置黑色来画时钟 drawHourAndMinutePointer(2*Math.PI*hours/12,30,g);//画时针 drawHourAndMinutePointer(2*Math.PI*minutes/60,40,g);//画分针 drawSecondPointer(2*Math.PI*seconds/12,50,g);//画秒针 drawNumber(g); g.drawOval(0, 50, 150, 150);//画左边圆 } void drawSecondPointer(double angle, int radius, Graphics g) { angle -= 0.5*Math.PI;//减去90度,因坐标与时钟差90度 int x = (int)(radius*Math.cos(angle));//计算针头的X坐标 int y = (int)(radius*Math.sin(angle));//计算针头的Y坐标 g.drawLine(75, 200, 75+x, 200+y);//画秒针 } void drawHourAndMinutePointer(double angle, int radius, Graphics g) { angle -= 0.5*Math.PI;//减去90度,因坐标与时钟差90度 int x = (int)(radius*Math.cos(angle));//计算针头的X坐标 int y = (int)(radius*Math.sin(angle));//计算针头的Y坐标 angle += 2*Math.PI/3;//将angle调整为第一针尾的角度 int x2 = (int)(5*Math.cos(angle));//计算第一针尾点的X坐标 int y2 = (int)(5*Math.sin(angle));//计算第一针尾点的Y坐标 angle += 2*Math.PI/3;//将angle调整为第二针尾的角度 int x3 = (int)(5*Math.cos(angle));//计算第二针尾点的X坐标 int y3 = (int)(5*Math.sin(angle));//计算第二针尾点的Y坐标 g.drawLine(75+x2, 200+y2, 75+x, 200+y);//画左翼 g.drawLine(75+x3, 200+y3, 75+x, 200+y);//画右翼 g.drawLine(75+x2, 200+y2, 75+x3, 200+y3);//画针尾 } void drawNumber(Graphics g) { for(int i = 1; i <= 12; i++) { drawnumber(g,(float) (Math.PI / 6)*i,i); } } void drawnumber(Graphics g,double angle,int num) { float sine = (float) Math.sin(angle); float cosine = (float) Math.cos(angle); int x = (int) (40 * sine); int y = (int) (40 * cosine); g.drawString("" + num, x + 75, 200 - y); } public void run() { currentTime = Calendar.getInstance(); hours = currentTime.get(Calendar.HOUR); minutes = currentTime.get(Calendar.MINUTE); seconds = currentTime.get(Calendar.SECOND); repaint(); } }