J W J W - 1 year ago 231
Java Question

libGDX label sometimes stops when updating every millisecond

I'm trying to update a label every millisecond in libGDX for a set amount of time.

However, sometimes the label suddenly stops without an error OR I receive a "String index out of range" error which then crashes my program. These are two separate issues.


Stage stage;
Timer timer = new Timer();
Label countUpLabel;
int countUp;

public void create () {

stage = new Stage(new FitViewport(Gdx.graphics.getWidth(), Gdx.graphics.getHeight()));

//Setting up time label
BitmapFont font = new BitmapFont(Gdx.files.internal("04b_19__-32.fnt"));
LabelStyle labelStyle = new LabelStyle(font, Color.WHITE);
countUpLabel = new Label("Time:\n00000", labelStyle);



//Setting up timer
timer.schedule(new TimerTask() {
public void run() {

if (countUp < 3000) {
countUpLabel.setText(String.format("Time:\n%d", countUp));

}, 0, 1); //every millisecond run the timer

Thanks in advance.

Answer Source

Most of libGDX is not thread safe, unless explicitly stated that it is. Also, updating a label every millisecond, while it is only shown about every 16 milliseconds (the refresh rate of your typical display device), isn't a very good approach. So you might want to remove your timer and instead update the label when it is actually visible: in the render method:

float counter = 0f;
public void render() {
    if (counter < 3) {
        counter += Gdx.graphics.getDeltaTime();
        countUpLabel.setText(String.format("Time:\n%01.22f", counter));
    // call glClear, stage.act, stage.draw, etc.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download