java 动态显示时间

2024-11-15 11:21:50
推荐回答(3个)
回答1:

javax.swing.Timer ,岩野余很容易的,一个事件,在事件里面显示你粗滚的时间就可以了。

import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Date;

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

public class TimerShow extends JFrame {

public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
new TimerShow();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}

private JLabel lblNewLabel;

public TimerShow() {
super("time");
setBounds(100, 100, 450, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().setLayout(null);
lblNewLabel = new JLabel(" 简单时钟 "脊孝, JLabel.CENTER);
lblNewLabel.setBounds(0, (300-35-35)/2, 440, 35);
getContentPane().add(lblNewLabel);
setVisible(true);

new Timer(delay, taskPerformer).start();
}

int delay = 1000; //milliseconds
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
String s=String.format("%tY-% lblNewLabel.setText(s);
}
};
}

回答2:

利用死循环和线程,让线程在循环中每sleep1秒,重新获取下系统时间就是动态显示时间了。
while(true){
Date date=new Date(System.currentTimeMillis());
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(date);
//每一亩李谈秒迅碰刷新下时扰差间
try {
Thread.sleep(1000);//sleep是以ms为单位
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

回答3:

额 加个定时器 在触发事件中 时间间隔1秒 然后+datetime.now