求用java语言设计一个动态时钟,每秒刷新一次

如题所述

package com.kaylves;

import java.text.SimpleDateFormat;
import java.util.Date;

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

public class Clock {
public static void main(String[] args) throws InterruptedException {
JFrame f = new JFrame();
Timer timer = new Timer();
Thread th=new Thread(timer);
th.start();
JLabel time = new JLabel();
f.add(time);
f.setVisible(true);
f.pack();
while(true){
time.setText(timer.getCurrentTime());
}
}
}

class Timer implements Runnable {
private String currentTime;

public String getCurrentTime() {
Date d = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
currentTime = sdf.format(d);
return currentTime;
}

public void run() {
try {
Thread.sleep(1000);
getCurrentTime();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
完成给分
温馨提示:答案为网友推荐,仅供参考
第1个回答  2011-12-07
import java.awt.*;
import java.awt.event.*;
import java.util.*;//这两个包你没有导入 至少在你贴进来的代码中没有导入
import java.text.SimpleDateFormat;

public class test extends Frame implements Runnable
{
private Label Labelshow=new Label();
private Panel pan1=new Panel();

public test()
{
super("time");
setup();
setResizable(false); //设置此图形界面是不可以改变大小的
setBounds(400, 200, 200, 400);
add(pan1);//修改1 你没有添加Panel界面会什么都不显示的
pack();
setVisible(true);
}

public void setup()
{
pan1.add(Labelshow);
Thread thread1=new Thread(this);//修改2 Panel没有实现Runnable接口 不能用做线程启动的
thread1.start();
}

public void run()
{
while(true)
{
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss");
Labelshow.setText(sdf.format(new Date()));
try
{
Thread.sleep(1000);
}
catch(Exception e)
{
Labelshow.setText("出错错误,请重启程序");
}
}
}

public static void main(String[] args)
{
test te=new test();
}
}