Locke Donohoe Locke Donohoe - 5 months ago 69
Java Question

LibGDX: Change text of TextField on focus

I have an array of TextFields added to a table by a loop. The number of TextFields added depends on an input given by the user.

The TextFields are initialised with the text "Player #" (# is incremented by the loop).
I want to be able to remove this text from each text field when they are focused, and if nothing is typed upon losing focus it will revert to the original string.

My problem here is being able to access the TextField to set the text in the FocusListener.

Here is my code: (NOTE: playernames is a table defined outside the code snippet.)

for(int i=0; i<MainMenu.numplayers; i++) {
playername[i] = new TextField("Player " + (i+1), skin);
playernames.add(new Label("Player " + (i+1) + ":", skin, "black")).padRight(5.0F).padBottom(5.0F);
playernames.add(playername[i]).width(125.0F).padBottom(5.0F);
playernames.row();

playername[i].addListener(new FocusListener() {
public void keyboardFocusChanged(FocusListener.FocusEvent event, Actor actor, boolean focused) {
if(focused == true) {
/** change text to "" */
}
else if(focused==false){
/** change text back to "Player #" if nothing was typed */
}
}
});


How can I access the TextField inside the Listener to be able to change the text?

Answer

Simplest option might be to add a final variable holding the text field in the loop. This can then be directly referenced int the handler. In general, if you want to access an outer variable from an anonymous class, make sure it's final.

for(int i = 0; i < MainMenu.numplayers; i++) {
  final TextField textField = new TextField("Player " + (i+1), skin);
  playername[i] = textField;
  // ...

  textField.addListener(new FocusListener() {
    public void focusGained(FocusEvent e) {
        // Access textField here and below as needed
    }
    public void focusLost(FocusEvent e) {
        // ...
    }
  });

}

I think the actor referenced in the event should be the text field, but this approach would require a type cast...

Comments