# How to update libgdx scene2d Label text dynamically?

I display a BitmapFont on the screen, update its text and the font is updated dynamically on the screen as well.
I seem to fail to do the same with a scene2d Label added as actor to a Stage.
The act(delta) and draw() methods are being called in the render() method.
My code basically looks as follows:

public void init() {
Label label = new Label(text, labelStyle);
stage.addActor(label);
}

public void update() {
updateText(text);
}

@Override
public void resize(int width, int height) {
/* do some resizing */
label.setPosition(newPositionX, newPositionY);
}

@Override
public void render(float delta) {
/* do some rendering */
stage.act(delta);
stage.draw();
update();
}


Do I need to do anything other than setting the Label text, adding it to the Stage as actor, and then updating the text elsewhere? The label displays its original text, though the text updating works fine.

Thanks.

## 2 Answers

You can call .setText("Some String"); on your label in your Render-method.

• Am I missing something obvious here? Why is this downvoted as it seems like the most logical way do what's needed? – ollipekka Sep 18 '14 at 19:04
• maybe because you probably dont want to do it in your render method since its a one off trigger operation. – HörmannHH Jul 14 '15 at 11:56

I have decided to answer my own question to provide the solution I have come up with, in case someone may find it useful:

I have extended the Label class and overridden the act(float delta) method of the new custom label:

public class CustomLabel extends com.badlogic.gdx.scenes.scene2d.ui.Label {
private String text;

public CustomLabel(final CharSequence text, final LabelStyle style) {
super(text, style);
this.text = text.toString();
}

@Override
public void act(final float delta) {
this.setText(text);
super.act(delta);
}

public void updateText(final String text) {
this.text = text;
}
}


The updateText(String text) method is then called from outside whenever the text of the label should be updated.

• the updateText(String text) is redundant to setText(String text). – digitebs Aug 8 '14 at 2:45
• Agree, drop your custom class and use label.setText directly. – tom van green Sep 18 '14 at 14:56