javaFX写代码,实现一个静态的钟表,时间为11:20:40,要求钟表有刻度,时针,分针,秒针的颜色不同,刻度内容为1到12,12在表盘最上面,逆时针排放其他数1,2,3,4,5,6,7,8,9,10,11
时间: 2024-12-08 16:16:35 浏览: 10
在JavaFX中创建一个静态的钟表可以使用`VBox`, `Circle` 和一些自定义布局。首先,你需要导入相关的库并创建一些基本组件:
```java
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;
import javafx.util.Duration;
public class ClockApp extends Application {
private static final double CIRCLE_RADIUS = 150;
private Label hourLabel, minuteLabel, secondLabel;
@Override
public void start(Stage primaryStage) {
initClock();
Scene scene = new Scene(new StackPane(), 400, 400);
primaryStage.setScene(scene);
primaryStage.show();
// 每秒更新时间
Duration timerInterval = Duration.seconds(1);
Clock clock = new Clock(secondLabel.getLayoutX() - 10, secondLabel.getLayoutY(), timerInterval);
clock.start();
}
private void initClock() {
Circle base = new Circle(CIRCLE_RADIUS, Color.WHITE);
base.setStroke(Color.BLACK);
// 刻度、时针、分针和秒针
for (int i = 1; i <= 12; i++) {
Label label = new Label(String.valueOf(i), base.getCenterX() + (i * CIRCLE_RADIUS / 12), base.getCenterY());
label.setRotate(-90 * i, base.getCenterX(), base.getCenterY()); // 逆时针旋转
label.setStyle("-fx-font-size: 15px; -fx-text-fill: gray;");
if (i == 12) {
label.setStyle("-fx-text-fill: red;");
}
base.getChildren().add(label);
}
hourLabel = new Label("11", base.getCenterX() - CIRCLE_RADIUS / 2, base.getCenterY());
hourLabel.setStyle("-fx-font-size: 30px; -fx-text-fill: blue;");
minuteLabel = new Label("20", base.getCenterX() - CIRCLE_RADIUS / 2, base.getCenterY() - CIRCLE_RADIUS / 4);
minuteLabel.setStyle("-fx-font-size: 20px; -fx-text-fill: green;");
secondLabel = new Label("40", base.getCenterX() - CIRCLE_RADIUS / 2, base.getCenterY() - CIRCLE_RADIUS / 2);
secondLabel.setStyle("-fx-font-size: 15px; -fx-text-fill: yellow;");
VBox layout = new VBox(base, hourLabel, minuteLabel, secondLabel);
layout.setAlignment(Pos.CENTER);
layout.setPadding(new Insets(20));
}
public static void main(String[] args) {
launch(args);
}
}
```
在这个例子中,我们首先创建了一个圆形作为背景,并添加了数字标签。然后设置了时针、分针和秒针的位置以及样式。最后,我们将所有元素放入一个`VBox`中并显示。
阅读全文