java - 更新用于计时器的 JLabel

标签 java timer jlabel

我到处搜索都没有找到解决这个问题的方法,所以我把它发布在这里。 基本上,我有一个从 180 秒开始倒计时的倒计时器,并成功打印到控制台。该计时器位于名为“Model”的类中,但使用 getter,我已将所述计时器的当前值导入到包含所有图形元素的“View”类中。即使它成功打印到控制台,它也不会更新 JLabel,它只是一直读取“180”。

这是带有计时器的模型类:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;


public class Model {
    private int counter = 180;
    //private String meme;
    public Model(){
        ActionListener al=new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                if(counter>0) {
                    counter = counter - 1;
                    System.out.println(counter);

                }

            }
        };
        Timer timer=new Timer(1000,al);
        timer.start();

    }

    public String getCounter(){
        return String.valueOf(counter);
    }
}

View 类非常大,因此我只包含第一部分,其中包含计时器和标签的代码:

*Other GUI elements initialization*
 private JLabel timeLabel=new JLabel("0");
Model model = new Model();
timeLabel.setText(model.getCounter());
*Other unrelated code*
JPanel east = new JPanel();
JPanel eastCenter = new JPanel();
JPanel eastCenterNorth = new JPanel();
east.setLayout(new BorderLayout());
eastCenter.setLayout(new BorderLayout());
eastCenterNorth.setLayout(new GridLayout(2,1));
east.add(eastCenter,BorderLayout.CENTER);
eastCenter.add(eastCenterNorth,BorderLayout.NORTH);
eastCenterNorth.add(timeLabel);
*Other GUI placement code*

如果您想要完整的未剪切 View 类,只需说出这个词,但我应该警告您,这非常碍眼。

最佳答案

如果您想要一个快速而简单的解决方案,您可以使您的 View 对模型可见:

public class Model {
  ...
  private YourViewClass view; // + setter, or init through constructor

}

在 View 类中,添加更新计时器的方法:

public void updateTimerText(String text) {
  timeLabel.setText(text);
}

在 ActionListener 定义中,在 if 条件内添加更新调用:

if (counter > 0) {
  counter = counter - 1;
  view.updateTimerText(String.valueOf(counter));
}

关于java - 更新用于计时器的 JLabel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45810421/

相关文章:

java - 如何根据另一个列值的变化更改生成列中选择的选定值

java.lang.IllegalArgumentException - 对话框关闭

java - 通过链接更改 JLABEL 的颜色

java - 使用 Jython 语法创建 JFrame/JLabel

java - 使用数据和 JTable?

java - SSL 证书绑定(bind)到实际的主机名。如果你有 "qa.example.com"的 SSL 证书,它不会在你名为 "dev.example.com"的机器上工作

javascript - 单页上有多个计时器

java - JLabel 不显示在 JFrame 上,而仅显示在 JOptionPane 上

java - Android for 循环计数不正确

Delphi:我自己的计时器的OnTimer事件从未发生