package thread; import java.awt.*; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.*; import java.util.Date; import java.awt.*; class T extends JFrame implements Runnable { Thread t2 =new Thread(); public void run() { t2.start(); Frame f=new Frame("机械表"); f.setSize(600,300); f.setLocation(300,300); f.setVisible(true); f.add(new Paint()); f.addWindowListener (new WindowAdapter() { public void windowClosing(WindowEvent e) { f.dispose(); } } ); //关闭窗口 while(t2!=null) { f.repaint(); try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } class Paint extends JPanel { public void paint (Graphics g) { int radius,ybase,xbase; Date date=new Date(); int hour=date.getHours(); int minute=date.getMinutes(); int s=date.getSeconds(); radius=ybase=xbase=150/2; g.drawOval(10, 10, 150, 150); for (int i = 1; i <= 12; i++) { g.drawString(new String(i+""), (int)(10+xbase+Math.sin(Math.PI/6*i)*radius), (int)(10+ybase-Math.cos(Math.PI/6*i)*radius)); } /* * 圆心坐标:(x0,y0) 半径:r 角度:a 圆周率: PI 则圆上任一点为:(x1,y1) x1 = x0 + r * cos(a * PI /180 ) y1 = y0 + r * sin(a * PI /180 ) */ g.setColor(Color.blue); g.drawLine(xbase+10, ybase+10, (int)(10+xbase+(Math.cos((s*Math.PI/30)-Math.PI/2)*radius)), (int)(10+ybase+(Math.sin((s*Math.PI/30-Math.PI/2))*radius))); g.setColor(Color.green); g.drawLine(xbase+10, ybase+10, (int)(10+xbase+(Math.cos((minute*Math.PI/30-Math.PI/2))*radius)), (int)(10+ybase+(Math.sin((minute*Math.PI/30-Math.PI/2))*radius))); g.setColor(Color.red); g.drawLine(xbase+10, ybase+10, (int)(10+xbase+(Math.cos((hour*Math.PI/6-Math.PI/2))*radius)), (int)(10+ybase+((Math.sin(hour*Math.PI/6-Math.PI/2))*radius))); g.setFont(new Font("宋体", Font.BOLD,20)); g.setColor(Color.black); g.drawString(date.getHours()+":"+date.getMinutes()+":"+date.getSeconds(),200,100); g.drawString("北京时间",200,50); } } public class time { public static void main(String args[]) { T t1=new T(); t1.run(); } }
运行图