clock.java

来自「用java中Timer类完成模拟时钟」· Java 代码 · 共 53 行

JAVA
53
字号
package com.clock.demo;

import java.awt.BorderLayout;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Timer;
import javax.swing.*;

class MyTimerTask extends TimerTask {
	private static String timeShow;
	private Clock c;

	public MyTimerTask(Clock c) {
		this.c = c;
	}

	public void run() {
		// 获得系统当前时间
		Calendar calendar = Calendar.getInstance();
		Date time = calendar.getTime();
		// 对获得的时间进行格式转换,转换成"HH:mm:ss"
		SimpleDateFormat dFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		timeShow = dFormat.format(time);
		this.c.setJlabel("模拟时钟:      "+timeShow);
	}
}

public class Clock extends JApplet {

	/**
	 * @param args
	 */
	private JLabel jlabel = new JLabel("");

	Timer timer = new Timer();

	public String getJlabel() {
		return this.jlabel.getText();
	}

	public void setJlabel(String jlabel) {
		this.jlabel.setText(jlabel);
	}

	public void init() {
		timer.schedule(new MyTimerTask(this), new Date(), 1000);
		this.add(jlabel,BorderLayout.NORTH);
		this.setSize(200,30);
		this.setVisible(true);
	}

}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?