线程实现JAVA编写时钟案例

<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();
	}
}

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值