JAVAFx制造时钟代码
时间: 2024-06-13 13:02:15 浏览: 123
JavaFX开发的示例代码
JavaFX是一个强大的图形用户界面(GUI)库,用于创建跨平台的富客户端应用程序。要使用JavaFX构建时钟,你可以使用`javafx.scene.canvas.Canvas`或`javafx.scene.layout.StackPane`结合`javafx.animation.AnimationTimer`来实现动态更新。下面是一个简单的例子,展示如何在JavaFX中创建一个计时器显示秒数:
```java
import javafx.application.Application;
import javafx.animation.AnimationTimer;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class JavaFXClock extends Application {
private int seconds = 0;
private Canvas canvas;
private double radius = 50;
@Override
public void start(Stage primaryStage) {
canvas = new Canvas(300, 300);
canvas.setStroke(Color.BLUE);
canvas.setFill(Color.TRANSPARENT);
canvas.centerXProperty().bind(primaryStage.widthProperty().divide(2));
canvas.centerYProperty().bind(primaryStage.heightProperty().divide(2));
var timer = new AnimationTimer() {
@Override
public void handle(long now) {
seconds++;
updateCanvas();
if (seconds % 60 == 0) { // 当秒数为整分钟时,重置秒数
seconds = 0;
}
}
};
timer.start();
StackPane root = new StackPane(canvas);
Scene scene = new Scene(root, 300, 300);
primaryStage.setScene(scene);
primaryStage.show();
}
private void updateCanvas() {
double x = canvas.getWidth() / 2 + radius * Math.cos(Math.toRadians(seconds * 6));
double y = canvas.getHeight() / 2 + radius * Math.sin(Math.toRadians(seconds * 6));
canvas.getGraphicsContext2D().beginPath();
canvas.getGraphicsContext2D().moveTo(x, y);
canvas.getGraphicsContext2D().arcTo(x, y, radius, radius, 0, 360);
canvas.getGraphicsContext2D().stroke();
}
public static void main(String[] args) {
launch(args);
}
}
```
在这个例子中,我们创建了一个圆形路径,随着时间的流逝,秒针会在画布上移动。每过一分钟,秒针会回到起点。
阅读全文