📄 timerd.java
字号:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import javax.swing.Timer;
public class Timerd
{
public static void main(String[] args)
{
TimerTestFrame frame = new TimerTestFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//常用写法
frame.show();
}
}
class TimerTestFrame extends JFrame
{
public TimerTestFrame()
{
setTitle("一个简易时钟");
setSize(WIDTH, HEIGHT);
setResizable(false);
Container c = getContentPane();
c.add(new ClockCanvas("Asia/Taipei"));//实例化Asia/Taipei地区的时间,加入到容器中
}
public static final int WIDTH = 212;
public static final int HEIGHT = 280;
}
class ClockCanvas extends JPanel
{
public ClockCanvas(String tz)
{
Calendar = new GregorianCalendar(TimeZone.getTimeZone(tz));
//设置时间间隔为一秒,增加监听
Timer t = new Timer(1000, new
ActionListener()
{
public void actionPerformed(ActionEvent event)
{
Calendar.setTime(new Date());
repaint();
}
});
t.start();
}
public void paintComponent(Graphics g)
{ double m=0.0;
Date t=new Date();
int x=0,y=0,x2=0,y2=0;
super.paintComponent(g);
//显示时刻点(60条线段)
for(int i=1;i<=60;i++)
{
m=i*Math.PI/30;
x=100+(int)(100*Math.sin(m));
y=100-(int)(100*Math.cos(m));
//判断是否是12、3、6、9这四个时刻
if (i%15!=0)
{
g.drawLine(x,y,(int)(100+90*Math.cos(2 * Math.PI
* (i - 15) / 60)),(int)(100+90*Math.sin(2 * Math.PI
* (i - 15) / 60)));
}
}
//显示12、3、6、9四个时刻线段(较其他56条线段长)以及数字
g.drawLine(100,0,100,20);
g.drawString("12",92,32);
g.drawString("3",172,104);
g.drawString("6",97,177);
g.drawString("9",21,104);
g.drawLine(200,100,180,100);
g.drawLine(100,200,100,180);
g.drawLine(0,100,20,100);
// 画时钟的一个圆
g.drawOval(0, 0, 200, 200);
//计算秒钟
int seconds = Calendar.get(Calendar.HOUR) * 60 * 60
+ Calendar.get(Calendar.MINUTE) * 60
+ Calendar.get(Calendar.SECOND);
//计算小时指针的角度
double hourAngle = 2 * Math.PI
* (seconds - 3 * 60 * 60) / (12 * 60 * 60);
//计算分钟指针的角度
double minuteAngle = 2 * Math.PI
* (seconds - 15 * 60) / (60 * 60);
//计算秒针指针的角度
double secondAngle = 2 * Math.PI
* (seconds - 15) / 60;
//分别画小时、分钟、秒钟指针线段
g.drawLine(100, 100, 100 + (int)(60
* Math.cos(hourAngle)),
100 + (int)(60 * Math.sin(hourAngle)));
g.drawLine(100, 100, 100 + (int)(80
* Math.cos(minuteAngle)),
100 + (int)(80 * Math.sin(minuteAngle)));
g.drawLine(100, 100, 100 + (int)(90
* Math.cos(secondAngle)),
100 + (int)(90 * Math.sin(secondAngle)));
g.drawString(t.toString(), 20, 220);
g.drawString("制作 by 张友军",60,240);
}
private GregorianCalendar Calendar;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -