java实现机械表

本文介绍了如何使用Java编程语言来实现机械表的模拟,详细探讨了相关算法和逻辑,帮助读者理解时间显示的更新机制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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();
      	}
	
}

运行图
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值