最近我一直在写老师布置的时钟日期工具,但是因为部分功能还未实现,所以还不能贴完整代码,不过后面会陆续更新电子表和日历的小程序。虽然这个时钟的效果图不是特别好看,但是基本的功能已经实现。读者可以试着把它做的跟美观漂亮一点。
简易时钟的代码如下:
1 import java.awt.*; 2 import java.awt.geom.AffineTransform; 3 import java.util.Calendar; 4 import javax.swing.JFrame; 5 import javax.swing.JPanel; 6 //@Author:M-Y 7 //@Time:2016/12/1 8 public class time extends JFrame{ 9 public time(){ 10 JPanel panel=new JPanel(); 11 panel.setLayout(new GridLayout()); 12 Clock1 c=new Clock1(); 13 panel.add(c); 14 this.add(panel); 15 } 16 public static void main(String[] args) { 17 time t=new time(); 18 t.setSize(300,300); //窗口大小 19 t.setTitle("Clock");//窗口名 20 t.setVisible(true); //设置为可见 21 t.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 22 } 23 } 24 class Clock1 extends JPanel{ 25 Thread th; 26 public void run(){ 27 while(true){ 28 try{ 29 repaint(); 30 }catch(Exception e){} 31 } 32 } 33 public void paint(Graphics g){ 34 Graphics2D g2d=(Graphics2D)g; 35 //去掉锯齿 36 g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON); 37 //清空原来的图形 38 g2d.setColor(Color.white); 39 g2d.fillRect(0,0,this.getWidth(),this.getHeight()); 40 g2d.setColor(Color.black); 41 //圆心(x,y) 半径radius=100 42 int x0=150; 43 int y0=150; 44 int radius=100; 45 g2d.drawOval(50,50,200,200); 46 g2d.drawOval(48,48,204,204); 47 //画刻度 48 for(int i=0;i<60;i++){ 49 g2d.fillRect(x0-2,46,3,3); 50 g2d.rotate(Math.toRadians(6),x0,y0); 51 } 52 //画12个数字 53 for(int i=0;i<12;i++){ 54 double d=Math.PI/180*i*(360/12); //每次转360/12度 55 int x=(x0-4)+(int)((radius-12)*Math.cos(d)); 56 int y=(y0+4)+(int)((radius-12)*Math.sin(d)); 57 //因为是从顺时钟3点钟开始画,所以索引i需要加上3 58 int j=i+3; 59 if(j>12) 60 j=j-12; 61 g2d.drawString(Integer.toString(j),x,y); 62 } 63 //设置旋转重置 64 AffineTransform old=g2d.getTransform(); 65 g2d.setTransform(old); 66 Calendar c=Calendar.getInstance(); 67 int h=c.get(Calendar.HOUR_OF_DAY); //得到hour ----时 68 int m=c.get(Calendar.MINUTE); //得到minute---分 69 int s=c.get(Calendar.SECOND); //得到second---秒 70 //画时针 71 double hAngle=(h-12+m/60d)*360d/12d; 72 g2d.rotate(Math.toRadians(hAngle),x0,y0); 73 g.drawLine(x0,y0,x0,100); 74 //画分针 75 double mAngle=(m+s/60d)*360d/60d; 76 g2d.rotate(Math.toRadians(mAngle),x0,y0); 77 g.drawLine(x0,y0,x0,70); 78 //画秒针 79 double sAngle=s*360d/60d; 80 g2d.rotate(Math.toRadians(sAngle),x0,y0); 81 g.drawLine(x0,y0,x0,55); 82 repaint(); 83 } 84 }
运行界面如下:
时间: 2024-11-05 02:54:39