import java.awt.FlowLayout;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Clock extends JFrame {
private static final long serialVersionUID = 4168118275271453942L;
private JLabel jlabel = null;
public Clock() {
super("时钟");
init();
}
private void init() {
jlabel = new JLabel();
this.setLayout(new FlowLayout(FlowLayout.CENTER));
this.add(jlabel);
this.setLocation(450, 450);
this.setSize(120, 60);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setVisible(true);
TimeThread time = new TimeThread(jlabel);
Thread thread = new Thread(time);
thread.start();
}
class TimeThread implements Runnable{
private JLabel label = null;
public TimeThread(JLabel label ){
this.label = label;
}
public void run() {
while(true){
try {
Thread.sleep(1000);
showTime();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private void showTime() {
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
label.setText(sdf.format(date));
}
}
public static void main(String[] args) {
new Clock();
}
}
专门给你写的!很简单看看吧
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
public class test1{
public static void main(String[] args) throws Exception{
Timer time=new Timer();
time.schedule(new tast(),1000);
//1秒后执行 去除为立即执行
}
}
class tast extends TimerTask{
public void run(){
Date date=new Date();
System.out.println("I'm start!"+date.toString());
try{
Thread.sleep((1000)); //休息一秒
//执行你需要调用的代码
}catch(Exception e){
e.printStackTrace();
}
date=new Date();
System.out.println("I'm execute!"+date.toString());
}
}
while(true)
{
// do whatever you wanna do
sleep(time in ms);
}
用timer函数可以定时循环