更新用于计时器的 JLabel

Update JLabel used for timer

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

这是带有计时器的型号class:

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);
    }
}

视图 class 非常大,所以我只包含了第一部分,其中包含计时器和标签的代码:

*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*

如果您想要完整的未剪辑视图 class 只需说出这个词,但我应该警告您,这很碍眼。

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

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

}

在视图 class 中,添加更新计时器的方法:

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

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

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