[英]Update JLabel used for timer
我到處搜索並沒有找到解決該問題的方法,因此我將其發布在這里。 基本上,我有一個倒計時計時器,從180秒開始倒計時,並成功打印到控制台。 該計時器位於一個名為“模型”的類中,但是我使用getter將所述計時器的當前值導入了包含所有圖形元素的“視圖”類中。 即使它成功打印到控制台,也不會更新JLabel,但它在整個過程中僅讀取“ 180”。
這是帶有計時器的Model類:
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);
}
}
視圖類很大,因此我只包括了第一部分,其中包含計時器和標簽的代碼:
*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*
如果您想要完整的未刪節視圖類,請說出這個詞,但我應該警告您,這真是令人討厭。
如果您想要一種快速簡單的解決方案,則可以使模型的視圖可見:
public class Model {
...
private YourViewClass view; // + setter, or init through constructor
}
在視圖類中,添加一種方法來更新計時器:
public void updateTimerText(String text) {
timeLabel.setText(text);
}
在ActionListener定義中,在if
條件內添加更新調用:
if (counter > 0) {
counter = counter - 1;
view.updateTimerText(String.valueOf(counter));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.