APP开始停止时器

package cn.oracle1;

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 TimeDemo extends Application {
 boolean boo = false;
 Thread thread;

 @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);

  // 声明一个内部的线程
  class TimeThread extends Thread {
   @Override
   public void run() {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    while (boo) {
     String str = sdf.format(new Date());
     System.err.println(str);
     Platform.runLater(new Runnable() {
      @Override
      public void run() {
       label.setText(str);// 设置上面的文本
      }
     });
     try {
      Thread.sleep(1000);
     } catch (InterruptedException e) {
      e.printStackTrace();
     }
    }
    //如果退出循环时设置thread=null
    thread = null;
   }
  }

  // 给btn1添加事件
  btn1.setOnAction(new EventHandler<ActionEvent>() {
   public void handle(ActionEvent event) {
    boo = true;
    if (thread == null) {
     System.err.println("启动。。。");
     thread = new TimeThread();
     thread.start();
    }else{
     System.err.println("已经启动了.....");
    }
   }
  });

  btn2.setOnAction(new EventHandler<ActionEvent>() {
   public void handle(ActionEvent event) {
    boo = false;
   }
  });

  box.getChildren().add(hbox);
  // 添加用于显示的对象
  Scene scene = new Scene(box, 300, 300);
  stage.setScene(scene);
  stage.show();
 }

 public static void main(String[] args) {
  launch(args);
 }

 // 程序用户点X号关闭时,会调用这个方法
 @Override
 public void stop() throws Exception {
  boo = false;
  super.stop();
 }
}

你可能感兴趣的:(APP开始停止时器)