如何在JLable中能够显示动态的时间?即时间按秒是变化的?

qq_23030725 2014-11-29 12:13:15
如果只是简单地初始化,则显示的时间是静止的。
请问如何能在JLable中让时间随着秒变化?
谢谢!
...全文
378 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
huntor 2014-12-03
  • 打赏
  • 举报
回复
使用javax.swing.Timer更新
lliiqiang 2014-12-01
  • 打赏
  • 举报
回复
计时器Timer更新.
lida994707194 2014-11-29
  • 打赏
  • 举报
回复
用线程重写run方法
rumlee 2014-11-29
  • 打赏
  • 举报
回复


import java.awt.Dimension;
import java.awt.Toolkit;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.swing.JFrame;
import javax.swing.JLabel;

public class Test37 extends JFrame implements Runnable {
	private static final long serialVersionUID = -5639886507164562993L;
	private JLabel label1;
	private JLabel label2;

	public Test37() {
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		this.setSize(400, 200);
		this.setResizable(false);

		this.setTitle("测试时间显示");

		Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
		Dimension frameSize = this.getSize();
		if (frameSize.height > screenSize.height) {
			frameSize.height = screenSize.height;
		}
		if (frameSize.width > screenSize.width) {
			frameSize.width = screenSize.width;
		}
		this.setLocation((screenSize.width - frameSize.width) / 2,
				(screenSize.height - frameSize.height) / 2);
		this.setLayout(null);

		label1 = new JLabel("当前时间:");
		label1.setSize(100, 30);
		label1.setLocation(30, 20);
		label1.setHorizontalAlignment(JLabel.RIGHT);
		this.getContentPane().add(label1);

		label2 = new JLabel("");
		label2.setSize(200, 30);
		label2.setLocation(140, 20);
		label2.setHorizontalAlignment(JLabel.LEFT);
		this.getContentPane().add(label2);
	}

	public void run() {
		while (true) {
			Date d = new Date();
			DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			label2.setText(df.format(d));
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	public static void main(String[] args) {
		Test37 t = new Test37();
		new Thread(t).start();
		t.setVisible(true);
	}
}

62,623

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧