gpt4 book ai didi

java - 更新用于计时器的 JLabel

转载 作者:行者123 更新时间:2023-12-02 12:20:47 27 4
gpt4 key购买 nike

我到处搜索都没有找到解决这个问题的方法,所以我把它发布在这里。基本上,我有一个从 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com