简体   繁体   中英

Update JLabel used for timer

I have searched everywhere and not found a solution to this problem so I am posting it here. Basically, I have a countdown timer that counts down from 180 seconds and it successfully prints to console. This timer is located in a class called "Model", but using getters I have imported the current value of said timer into the "View" class that contains all of the graphical elements. Even though it successfully prints to console it does not update the JLabel, it simply reads "180" the entire time.

This is the Model class with the timer:

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

The view class is very large so I have only included the first part which contains the code for the timer and label:

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

If you would like the full uncut view class just say the word but I should warn you it's quite an eyesore.

If you want a fast and simple solution, you can make your view visible for the model:

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

}

In the view class, add a method to update the timer:

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

In the ActionListener definition, add the update call inside the if condition:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM