java 钟_java实现时钟效果
时间: 2023-10-17 16:30:26 浏览: 150
要实现一个时钟效果,可以使用 Java 的 Graphics2D 类来绘制时钟的各个部分。
首先需要创建一个 JFrame 窗口,并在其中添加一个 JPanel 用于绘制时钟。然后在 JPanel 中重写 paintComponent 方法,在该方法中使用 Graphics2D 绘制时钟的各个部分。
以下是一个简单的 Java 时钟实现示例代码:
```java
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.Ellipse2D;
import java.time.LocalTime;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Clock extends JPanel {
private LocalTime time;
public Clock() {
time = LocalTime.now();
}
public void setTime(LocalTime time) {
this.time = time;
repaint();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
// 抗锯齿
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
// 获取面板尺寸
int width = getWidth();
int height = getHeight();
// 计算时钟半径
int radius = Math.min(width, height) / 2 - 5;
// 将原点移动到面板中心
g2d.translate(width / 2, height / 2);
// 绘制时钟外框
g2d.setStroke(new BasicStroke(3));
g2d.setColor(Color.BLACK);
g2d.draw(new Ellipse2D.Double(-radius, -radius, radius * 2, radius * 2));
// 绘制时钟刻度
for (int i = 0; i < 12; i++) {
double angle = i * Math.PI / 6;
int x1 = (int) (Math.cos(angle) * (radius - 20));
int y1 = (int) (Math.sin(angle) * (radius - 20));
int x2 = (int) (Math.cos(angle) * radius);
int y2 = (int) (Math.sin(angle) * radius);
g2d.drawLine(x1, y1, x2, y2);
}
// 绘制时钟指针
int hour = time.getHour() % 12;
int minute = time.getMinute();
int second = time.getSecond();
double hourAngle = (hour + minute / 60.0) * Math.PI / 6;
int hourLength = (int) (radius * 0.5);
int hourX = (int) (Math.cos(hourAngle) * hourLength);
int hourY = (int) (Math.sin(hourAngle) * hourLength);
g2d.setStroke(new BasicStroke(5));
g2d.setColor(Color.BLACK);
g2d.drawLine(0, 0, hourX, hourY);
double minuteAngle = minute * Math.PI / 30;
int minuteLength = (int) (radius * 0.7);
int minuteX = (int) (Math.cos(minuteAngle) * minuteLength);
int minuteY = (int) (Math.sin(minuteAngle) * minuteLength);
g2d.setStroke(new BasicStroke(3));
g2d.setColor(Color.BLUE);
g2d.drawLine(0, 0, minuteX, minuteY);
double secondAngle = second * Math.PI / 30;
int secondLength = (int) (radius * 0.9);
int secondX = (int) (Math.cos(secondAngle) * secondLength);
int secondY = (int) (Math.sin(secondAngle) * secondLength);
g2d.setStroke(new BasicStroke(1));
g2d.setColor(Color.RED);
g2d.drawLine(0, 0, secondX, secondY);
g2d.dispose();
}
public static void main(String[] args) throws InterruptedException {
JFrame frame = new JFrame("Clock");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 300);
Clock clock = new Clock();
frame.add(clock);
frame.setVisible(true);
while (true) {
clock.setTime(LocalTime.now());
Thread.sleep(1000);
}
}
}
```
该代码使用了 Ellipse2D、Line2D 等几何图形类来绘制时钟的各个部分,同时使用了 Stroke 类来设置画笔的粗细。在主函数中使用一个 while 循环不断更新时钟时间并刷新画面,实现了一个简单的时钟效果。
阅读全文