您的位置:首页 > 编程语言 > Java开发

线程实现JAVA编写时钟案例

2016-04-11 08:57 543 查看
<img src="http://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;@Overridepublic 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 {@Overridepublic 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() {@Overridepublic void run() {label.setText(sdf.format(new Date())); // 设置上面的文本!!!}});try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}}// 停止时,让thread设置为nullthread = null;}};// 给button1添加一个事件!!!button1.setOnAction(new EventHandler<ActionEvent>() {@Overridepublic 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>() {@Overridepublic 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);}@Overridepublic void stop() throws Exception {// 点击右上角关闭运行!!!!boo = false;super.stop();}}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: