<img src="https://img-blog.csdn.net/20160411085956782?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" />
package cn.TimeDoem;
import java.text.SimpleDateFormat;
import java.util.Date;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonBar;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class Time extends Application {
boolean boo = false;
Thread thread;
@Override
public void start(Stage primaryStage) throws Exception {// 主要舞台!!!
// 声明一个盒子
VBox vBox = new VBox(20);
vBox.setAlignment(Pos.CENTER);
// 添加一个文本
final Label label = new Label("显示时间");
vBox.getChildren().add(label);
HBox hBox = new HBox(40);
hBox.setAlignment(Pos.CENTER);
Button button1 = new Button("启动");
Button button2 = new Button("停止");
hBox.getChildren().addAll(button1, button2);
// 声明一个内部的线程
class TimeThread extends Thread {
@Override
public void run() {
while (boo) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(sdf.format(new Date()));
Platform.runLater(new Runnable() {
@Override
public void run() {
label.setText(sdf.format(new Date())); // 设置上面的文本!!!
}
});
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 停止时,让thread设置为null
thread = null;
}
}
;
// 给button1添加一个事件!!!
button1.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
boo = true;
if (thread == null) {
System.out.println("启动");
thread = new TimeThread(); // 每次创建一个新线程!!!!
thread.start();
} else {
System.out.println("已经启动了");
}
}
});
// 停止按钮!!!!
button2.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
boo = false;
}
});
vBox.getChildren().add(hBox);
// 添加一个用于显示的对象
Scene scene = new Scene(vBox, 400, 400);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
@Override
public void stop() throws Exception {// 点击右上角关闭运行!!!!
boo = false;
super.stop();
}
}