用Java FX做一个时钟
时间: 2024-01-29 17:05:05 浏览: 76
C8051FX 系列应用笔记 实时时钟的实现
好的,以下是一个简单的JavaFX时钟示例代码:
```java
import javafx.animation.Animation;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Line;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import javafx.util.Duration;
import java.time.LocalTime;
public class Clock extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
Group root = new Group();
Scene scene = new Scene(root, 400, 400, Color.WHITE);
// 创建时钟圆盘
Circle circle = new Circle(200, 200, 150);
circle.setFill(Color.WHITE);
circle.setStroke(Color.BLACK);
// 创建时钟刻度线
for (int i = 0; i < 12; i++) {
Line line = new Line(200, 50, 200, 75);
line.setStroke(Color.BLACK);
line.setRotate(i * 30);
root.getChildren().add(line);
}
// 创建时钟指针
Line hourHand = new Line(200, 200, 200, 100);
hourHand.setStrokeWidth(5);
hourHand.setStroke(Color.BLACK);
Line minuteHand = new Line(200, 200, 200, 50);
minuteHand.setStrokeWidth(3);
minuteHand.setStroke(Color.BLACK);
Line secondHand = new Line(200, 200, 200, 50);
secondHand.setStrokeWidth(1);
secondHand.setStroke(Color.RED);
// 创建时钟数字
for (int i = 1; i <= 12; i++) {
Text text = new Text(String.valueOf(i));
text.setFont(Font.font("Arial", 20));
text.setX(190 + 130 * Math.sin(i * Math.PI / 6));
text.setY(210 - 130 * Math.cos(i * Math.PI / 6));
root.getChildren().add(text);
}
// 创建时钟数字
Text text = new Text(175, 380, "");
text.setFont(Font.font("Arial", 20));
root.getChildren().add(text);
// 创建时间轴
Timeline timeline = new Timeline(
new KeyFrame(Duration.seconds(1), event -> {
LocalTime now = LocalTime.now();
double hourAngle = (now.getHour() % 12 + now.getMinute() / 60.0) * 30;
double minuteAngle = now.getMinute() * 6;
double secondAngle = now.getSecond() * 6;
hourHand.setRotate(hourAngle);
minuteHand.setRotate(minuteAngle);
secondHand.setRotate(secondAngle);
text.setText(now.toString());
})
);
timeline.setCycleCount(Animation.INDEFINITE);
timeline.play();
// 将时钟组件添加到根节点
root.getChildren().addAll(circle, hourHand, minuteHand, secondHand);
primaryStage.setTitle("Clock");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
```
该程序的界面如下所示:
![时钟界面](https://img-blog.csdnimg.cn/20210308155005474.png)
通过 Timeline 类来更新时钟指针和时间数字,这里我们将时间轴的周期设置为1秒。
阅读全文