用java实现时钟的功能,即按秒更新。页面效果HH:mm:SS
时间: 2024-02-26 11:56:19 浏览: 19
好的,我可以帮你用 Java 实现这个功能。以下是代码示例:
```
import java.text.SimpleDateFormat;
import java.util.Date;
public class Clock {
public static void main(String[] args) {
while (true) {
Date now = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
String timeString = sdf.format(now);
System.out.println(timeString);
try {
Thread.sleep(1000); // 暂停一秒钟
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
```
这段代码会每秒钟输出一次当前的时间,时间格式为 HH:mm:SS。你可以将输出方式改为更新页面中的元素,以实现在页面上显示时钟的效果。
注意,这段代码会一直循环输出时间,你需要手动停止程序。如果你想要在 JavaFX 窗口中显示时钟,可以使用类似于以下的代码:
```
import javafx.animation.Animation;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import javafx.util.Duration;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Clock extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
Label timeLabel = new Label();
StackPane root = new StackPane(timeLabel);
Scene scene = new Scene(root, 200, 50);
Timeline timeline = new Timeline(
new KeyFrame(Duration.seconds(0), event -> {
Date now = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
String timeString = sdf.format(now);
timeLabel.setText(timeString);
}),
new KeyFrame(Duration.seconds(1))
);
timeline.setCycleCount(Animation.INDEFINITE);
timeline.play();
primaryStage.setTitle("Clock");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
```
这段代码会创建一个 JavaFX 窗口,窗口中显示当前时间,时间格式为 HH:mm:SS。每秒钟更新一次。你可以根据需要修改窗口大小、位置、字体等属性。
相关推荐
![java](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)