如何实现时钟更新?
本想用swing做一个电子时钟(可以实时更新的那种),可是做出来却不能实时更新,求大佬指点
代码如下:
//省略import
public class DateDemo extends JFrame {
private static final long serialVersionUID = -8501458415481947988L;
private JPanel contentPane;
private JPanel panel1;
private JPanel panel2;
private String tf;
private String tt;
private JLabel label1;
private JLabel label2;
public static void main(String[] args) {
try {
UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");
} catch (Throwable e) {
e.printStackTrace();
}
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
DateDemo frame = new DateDemo();
frame.setVisible(true);
}catch(Exception e) {
e.printStackTrace();
}
}
});
}
public DateDemo() {
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
do_this_windowClosing(e);
}
});
setTitle("数字时钟");
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
setBounds(100,100,275,125);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5,5,5,5));
setContentPane(contentPane);
contentPane.setLayout(new GridLayout(2,1,5,5));
panel1 = new JPanel();
label1 = new JLabel("年-月-日");
panel1.add(label1);
contentPane.add(panel1);
panel2 = new JPanel();
label2 = new JLabel("时:分:秒");
panel2.add(label2);
contentPane.add(panel2);
gan();
}
protected void do_this_windowClosing(WindowEvent e) {
JOptionPane.showMessageDialog(this,"确认关闭?",null,JOptionPane.CLOSED_OPTION);
System.exit(0);
}
protected void gan() {
Date date = new Date();
tf = String.format("%tF",date);
tt = String.format("%tT",date);
label1.setText("年-月-日 => " + tf);
label2.setText("时:分:秒 => " + tt);
}
}
在gan()方法时用while(true)时它又显示不出窗体
求助!