javafx中Clock类怎么做简易时钟
时间: 2023-10-13 21:30:12 浏览: 83
要在JavaFX中创建一个简易时钟,可以使用Clock类。以下是一个简单的JavaFX程序,它使用Clock类创建一个时钟:
```
import javafx.animation.Animation;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
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;
import java.time.format.DateTimeFormatter;
public class SimpleClock extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
// Create the clock components
Circle outerCircle = new Circle(100, 100, 80);
outerCircle.setFill(null);
outerCircle.setStroke(Color.BLACK);
outerCircle.setStrokeWidth(3);
Circle innerCircle = new Circle(100, 100, 5);
innerCircle.setFill(Color.BLACK);
Line hourHand = new Line(100, 100, 100, 50);
hourHand.setStrokeWidth(5);
Line minuteHand = new Line(100, 100, 100, 30);
minuteHand.setStrokeWidth(3);
Text timeText = new Text();
timeText.setFont(new Font(20));
timeText.setX(70);
timeText.setY(180);
// Create the timeline to update the clock every second
Timeline timeline = new Timeline(
new KeyFrame(Duration.seconds(1), event -> {
LocalTime now = LocalTime.now();
double hours = now.getHour() % 12 + now.getMinute() / 60.0;
double minutes = now.getMinute();
double seconds = now.getSecond();
hourHand.setEndX(100 + 40 * Math.sin(hours * 30 * Math.PI / 180));
hourHand.setEndY(100 - 40 * Math.cos(hours * 30 * Math.PI / 180));
minuteHand.setEndX(100 + 60 * Math.sin(minutes * 6 * Math.PI / 180));
minuteHand.setEndY(100 - 60 * Math.cos(minutes * 6 * Math.PI / 180));
String timeString = now.format(DateTimeFormatter.ofPattern("HH:mm:ss"));
timeText.setText(timeString);
})
);
timeline.setCycleCount(Animation.INDEFINITE);
timeline.play();
// Create the root node and add the clock components
StackPane root = new StackPane();
root.getChildren().addAll(outerCircle, innerCircle, hourHand, minuteHand, timeText);
// Create the scene and add the root node
Scene scene = new Scene(root, 200, 200);
// Set the stage title and scene, and show the stage
primaryStage.setTitle("Simple Clock");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
```
这个程序创建了一个圆形时钟,它包括一个外部圆,一个内部圆,一个时针,一个分针和一个显示当前时间的文本。时钟每秒钟更新一次。
阅读全文