最近用Java写了一个时钟小程序,遇到了很多麻烦,如绘图时存在锯齿、前一秒的秒钟不消失(60秒之后出现六十根秒钟,成辐射状)等..... 通过不断修改终于制作出了一个自我认为比较好的时钟小程序, 运行结果如下: 代码如下: import java.awt.*; import javax.swing.*; import java.util.*; public class ClockJFrame extends JFrame implements Runnable { private JTextField text; private int r,a,b;//时钟的半径、圆心坐标。 private int h,m,s;//变量时、分、秒 private int hp,mp,sp;//时钟、分钟、秒钟的长度 public ClockJFrame(int h,int m,int s) { super("小时钟"); this.h=h; this.m=m; this.s=s; r=150; a=250; b=200; hp=(int)(0.5*r); mp=(int)(4*r/5); sp=(int)(0.95*r); this.setSize(500,500); this.setVisible(true); this.setDefaultCloseOperation(EXIT_ON_CLOSE); } public void paint(Graphics g) { //消除2D图形锯齿: if(g instanceof Graphics2D) { Graphics2D gg=(Graphics2D)g; gg.setRenderingHint(RenderingHints.KEY_ANTIALIASING , RenderingHints.VALUE_ANTIALIAS_ON); } //绘出时钟背景色: g.setColor(Color.gray); g.fillOval(a-r,b-r,2*r,2*r); //绘制月亮背景,增加时钟美观: g.setColor(Color.yellow); g.fillOval(a-30,b-30,100,100); g.setColor(Color.gray); g.fillOval(a-45,b-45,100,100); //显示电子表时钟: String str=h+":"+m+":"+s; g.setColor(Color.black); g.drawString(str,a-20,b-50); //绘出时钟的2个外圆框 g.setColor(Color.red); g.drawOval(a-r,b-r,2*r,2*r);//红色外圆框 g.setColor(Color.blue); g.drawOval(a-r-5,b-r-5,2*r+10,2*r+10);//蓝色外圆框 //绘制中心点: g.fillOval(a-(int)(8*Math.cos(Math.PI/4)),b-(int)(8*Math.cos(Math.PI/4)),13,13); //绘制时钟刻度: for(int i=1;i<=60;i++) { int x1,y1,x2,y2,x3,y3; x1=a+(int)(0.9*r*Math.sin(i*Math.PI/30)); y1=b-(int)(0.9*r*Math.cos(i*Math.PI/30)); x2=a+(int)(r*Math.sin(i*Math.PI/30)); y2=b-(int)(r*Math.cos(i*Math.PI/30)); x3=a+(int)(0.96*r*Math.sin(i*Math.PI/30)); y3=b-(int)(0.96*r*Math.cos(i*Math.PI/30)); if(i%5==0) { g.setColor(Color.black); g.drawLine(x1,y1,x2,y2); } else { g.setColor(Color.green); g.drawLine(x3,y3,x2,y2); } } //分别算出小时、分钟、秒钟的端点坐标: int h_x=a+(int)(hp*Math.sin(h*Math.PI/6+m*Math.PI/360)); int h_y=b-(int)(hp*Math.cos(h*Math.PI/6+m*Math.PI/360)); int m_x=a+(int)(mp*Math.sin(m*Math.PI/30)); int m_y=b-(int)(mp*Math.cos(m*Math.PI/30)); int s_x=a+(int)(sp*Math.sin(s*Math.PI/30)); int s_y=b-(int)(sp*Math.cos(s*Math.PI/30)); //绘出小时指针: g.drawLine(a,b+5,h_x,h_y); g.drawLine(a+5,b,h_x,h_y); //分针指针: g.drawLine(a+3,b,m_x,m_y); g.drawLine(a,b+3,m_x,m_y); //秒针指针: g.setColor(Color.red);//设置秒针为红色 g.drawLine(a,b,s_x,s_y); g.drawLine(a,b+1,s_x,s_y); g.drawLine(a+1,b,s_x,s_y); } public void run() { Thread thread=new Thread(this); while(true) { try { thread.sleep(1000);//每隔一秒重绘一次 Calendar cal=Calendar.getInstance(); h=cal.get(Calendar.HOUR_OF_DAY); m=cal.get(Calendar.MINUTE); s=cal.get(Calendar.SECOND); repaint(); } catch(InterruptedException e){break;} } } public static void main(String atgs[]) { int h,m,s; Calendar cal=Calendar.getInstance(); h=cal.get(Calendar.HOUR_OF_DAY); m=cal.get(Calendar.MINUTE); s=cal.get(Calendar.SECOND); ClockJFrame clock=new ClockJFrame(h,m,s); Thread threat=new Thread(clock); threat.start(); } }