简单时钟java程序

import java.awt.Container;
import java.awt.GridLayout;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

class MyThread1 extends JPanel implements Runnable {
int h, m, s;
JLabel time1 = new JLabel();
public MyThread1() { // 编写子类的构造方法
this.add(time1);
}
public void run() { // 定义线程体,编写线程代码
while (true) {
Date now = new Date();
DateFormat df = DateFormat.getDateTimeInstance(DateFormat.LONG,
DateFormat.LONG); // 显示日期。时间(精确到秒)
String str = df.format(now);
time1.setText("");
time1.setText(str); // 显示时间
try {
Thread.sleep(1000); // 休眠1秒
} catch (InterruptedException e) {}
}
}
}
class MyThread2 extends JPanel implements Runnable {
int h, m, s;
Thread t;
JLabel time2 = new JLabel();
public MyThread2(Thread thread) { // 编写子类的构造方法
t = thread;
this.add(time2);
}
public void run() { // 定义线程体,编写线程代码
while (true) {
Calendar ca = Calendar.getInstance();
int h = ca.get(Calendar.HOUR);// 小时
int m = ca.get(Calendar.MINUTE);// 分
int s = ca.get(Calendar.SECOND);// 秒
if (m == 0 && s == 0) {
t.suspend(); // 挂起线程t
for (int i = 1; i < 5; i++) {
time2.setText("整点报时!现在时间" + h + "点整!");
try {
Thread.sleep(500);
} catch (InterruptedException e) {}
time2.setText("");
try {
Thread.sleep(480);
} catch (InterruptedException e) {}
}
t.resume(); // 恢复线程t}
}
}
}
public class ShiYan13_1 extends JFrame {
MyThread1 trun1 = new MyThread1();
MyThread2 trun2 = null;
ShiYan13_1() {
super("整点报时");
Thread t1 = new Thread(trun1);
t1.start();
Container c = this.getContentPane();
c.setLayout(new GridLayout(3, 1));
c.add(new JLabel("现在时间是:"));
c.add(trun1);
trun2 = new MyThread2(t1);
c.add(trun2);
Thread t2 = new Thread(trun2);
t2.start();
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(250, 200);
this.setVisible(true);
}
public static void main(String args[]) {
new ShiYan13_1();
}
}

相关文档
最新文档