Java怎么在JLabel中添加一个时钟? 70
这句代码jb.setText(newSimpleDateFormat("yyyy-MM-ddHH:mm:ss").format(newjava.util.Date()))...
这句代码jb.setText(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new java.util.Date()));添加的是一个系统当前时间,并不是动态的,我想要一个动态的,应该怎么做?
展开
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-%<tm-%<td %<tH:%<tM:%<tS",new Date());
lblNewLabel.setText(s);
}
};
}
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-%<tm-%<td %<tH:%<tM:%<tS",new Date());
lblNewLabel.setText(s);
}
};
}
追问
你好。我想在任意一个JPanel中加入一个动态的系统时间,可是怎么做都不对,你说的方法我在网上也查到了,加进去后老是报错。你能直接给我添加进去吗?弄了好久了,很上火啊,初学Java。
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询