【发布时间】:2013-11-01 13:12:25
【问题描述】:
我正在尝试创建一个显示当前时间的 Java GUI。目前,我可以让它显示当前时间,但只能在启动时显示。然后它就永远停留在那个时间。原因是我无法弄清楚如何让它每秒自动加载到新的当前时间。到目前为止,这是我的相关代码:
// Getting the current time...
long epoch = System.currentTimeMillis() / 1000;
String date = new java.text.SimpleDateFormat("HH:mm:ss").format(new java.util.Date(epoch * 1000));
// Creating the panel...
JLabel lblThetime = new JLabel(date);
sl_panel.putConstraint(SpringLayout.NORTH, lblThetime, 55, SpringLayout.SOUTH, lblIBeA);
sl_panel.putConstraint(SpringLayout.WEST, lblThetime, 139, SpringLayout.WEST, panel);
lblThetime.setFont(new Font("Avenir Next", Font.PLAIN, 40));
// Adding the time to the panel
panel.add(lblThetime);
// My refresher which doesn't work
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
removeAll();
validate();
repaint();
}
}, 1000, 1000);
我尝试使用来自this thread 的信息进行复习,但无济于事,窗口(运行时)只是空白。然后我尝试使用来自this thread 的信息进行不同的复习,并创建了这个:
// My refresher which doesn't work
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
contentPane.remove(lblThetime);
contentPane.add(lblThetime);
}
}, 1000, 1000);
contentPane 被定义为 private JPanel contentPane;
这也不起作用,但是只有时间本身是空白的,窗口中的其余内容(另一个 JLabel(只是一些文本))保持正常。
没有任何刷新,它的行为如上所述,它只显示它开始的时间并永远保持那个时间。
我将 Eclipse 与 WindowBuilder 一起使用。 (而且我(可能很明显)完全是 Java GUI 的菜鸟 xD)
【问题讨论】:
标签: java user-interface time clock windowbuilder