java做的简单的时钟

应用图形用户界面和多线程的知识,编写一个带界面的时钟程序,应用多线程实现时钟的走动,要求简单的数字时钟即可。
import java.awt.BorderLayout;
import java.awt.Container;
import java.util.Calendar;
import java.util.GregorianCalendar;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Clock {
public Clock() {
JFrame app = new JFrame(“电子时钟”);
Container c = app.getContentPane();
JLabel clock = new JLabel(“电子时钟”);
clock.setHorizontalAlignment(JLabel.CENTER);
c.setLayout(new BorderLayout());
c.add(clock, BorderLayout.CENTER);
app.setSize(160, 80);
app.setLocation(600, 300);
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
app.setVisible(true);
Thread t = new MyThread(clock);
t.start();
}

class MyThread extends Thread {
	private JLabel clock;

	public MyThread(JLabel clock) {
		this.clock = clock;
	}

	public void run() {
		while (true) {
			clock.setText(this.getTime());
			try {
				Thread.sleep(1000);
			} catch (Exception e) {
				System.err.println(e);
			}
		}
	}

	public String getTime() {
		Calendar cl = new GregorianCalendar();
		String time = cl.get(Calendar.YEAR) + "-"
				+ (cl.get(Calendar.MONTH) + 1) + "-"
				+ cl.get(Calendar.DATE) + "";
		int h = cl.get(Calendar.HOUR_OF_DAY);
		int m = cl.get(Calendar.MINUTE);
		int s = cl.get(Calendar.SECOND);
		time += h + ":" + m + ":" + s;
		return time;
	}
}

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

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值