Java - 如何每秒更新一个面板

标签 java user-interface time clock windowbuilder

我正在尝试创建一个显示当前时间的 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)

最佳答案

我找到了解决方案!

我尝试了此处作为答案给出的所有解决方案,但没有一个能使代码完全起作用,但是所有答案都为我指明了正确的方向。我在一个我忘了名字的网站上找到了问题的解决方案,但我使用了它的建议并提出了这个有效的最终解决方案:

        // New timer which works!
    int delay = 1000; //milliseconds
      ActionListener taskPerformer = new ActionListener() {
          public void actionPerformed(ActionEvent evt) {
              String date = new java.text.SimpleDateFormat("HH:mm:ss").format(new java.util.Date(System.currentTimeMillis()));
              lblThetime.setText(date);
          }
      };
      new Timer(delay, taskPerformer).start();

感谢所有没有回答的人,我可能无法找到这个解决方案 :D

关于Java - 如何每秒更新一个面板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19727449/

相关文章:

c# - 多线程任务更新 1 个进度条 - UI C# WPF

performance - 是否有可能预测程序将运行多长时间?

windows - 是否可以在没有实际窗口的情况下在 Windows 操作系统上显示 "on screen"文本?

java.lang.NullPointerException,当我在托管 bean 的构造函数内调用其他 bean 的方法时

java - 如何在CVS中自动复制项目

java - 由于重复键,JPA 合并失败

c++ - QVideoWidget黑窗

c - 一个简单算法的时间复杂度

javascript - 每天下午用Javascript隐藏CSS类

java - 使用 JAVA API 获取我的 Azure 订阅中所有资源的详细信息