应用图形用户界面和多线程的知识,编写一个带界面的时钟程序,应用多线程实现时钟的走动,要求简单的数字时钟即可。
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();
}