package cn.oracle;
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.Label;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class Test_151130_Time extends Application {
volatile static boolean b = true;
volatile static boolean a = false;
static Thread t;
static int count = 0;
@Override
public void start(Stage stage) throws Exception {
// 声明一个
VBox box = new VBox(10);
box.setAlignment(Pos.CENTER);
// 添加一个文本
final Label label = new Label("显示时间");
box.getChildren().add(label);
HBox hbox = new HBox(10);
hbox.setAlignment(Pos.CENTER);
Button btn1 = new Button("启动");
Button btn2 = new Button("停止");
hbox.getChildren().addAll(btn1, btn2);
// 声明一个内部的线程
t = new Thread() {
@Override
public void run() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
while (true) {
while (b) {
String str = sdf.format(new Date());
System.err.println(str);
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Platform.runLater(new Runnable() {
@Override
public void run() {
label.setText(str);// 设置上面的文本
}
}
);
}
}
}
};
// 给btn1添加事件
btn1.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent event) {
if (count == 0) {
t.start();
count++;
} else {
System.out.println("--第" + count + "次重启--");
count++;
b = true;
}
}
});
btn2.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
System.out.println("--第" + count + "次停止--");
b = false;
}
});
box.getChildren().add(hbox);
// 添加用于显示的对象
Scene scene = new Scene(box, 300, 300);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch();
}
}