0

I have a Class called GameCharater, which has a "name" stored as a String. I have an instantiation of this object within my Controller class called executing character this executing character is being updated.

When this object updates I would like my UI to update accordingly. For example, a label that shows the player name should change.

Here is an outline of my class.

public class GameController implements Initializable {

    private GameCharacter executingCharater;

    @FXML
    private Label playernamelabel;

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {

        playernamelabel = new Label();

    }

How can I dynamical update my UI to a changing object within my controller?

I am aware of the Observer pattern, but I am getting lost trying to figure the standard implementation into a JAVA FX project?

  • https://stackoverflow.com/questions/42566161/javafx-and-the-observer-pattern-updating-a-ui recommends an observer subclass within my controller, is that the most straight forward approach to this? – Gooze_Berry Nov 20 '19 at 15:28
  • 1
    beware: you overwrite a field that is injected by fxml! So you may end up working on different instances may cause lots of trouble. So don't: _never-ever_ instantiate a field that's injected (as in really really really never!) – kleopatra Nov 20 '19 at 16:26

2 Answers2

1

From this answer, you can bind a value to the label

// where valueProperty is a string that holds the value of your label
playernamelabel = new Label("Start");
playernamelabel.textProperty().bind(valueProperty);

rileyjsumner
  • 523
  • 1
  • 8
  • 21
  • does using bind() presume whatever I am binding is observable? Meaning I need to make my PlayerCharacter Class Observable? – Gooze_Berry Nov 20 '19 at 15:32
1

Try to bind character name property and label text property.

Code snippet below:

public class GameCharacter {
    private final StringProperty name = new SimpleStringProperty();

    public GameCharacter() {
        setName("Default name");
    }

    public StringProperty nameProperty() {
        return name;
    }

    public void setName(final String value) {
        nameProperty().set(value);
    }

    public String getName() {
        return nameProperty().get();
    }
}
public class BindingApp extends Application {

    private final Label labelCharName = new Label();
    private final GameCharacter gameCharacter = new GameCharacter();

    public static void main(final String[] args) {
        Application.launch(args);
    }

    @Override
    public void start(final Stage primaryStage) throws Exception {
        primaryStage.setScene(new Scene(new VBox(labelCharName), 300, 200));
        labelCharName.textProperty().bind(gameCharacter.nameProperty());
        primaryStage.show();

        mockName();
    }

    public void mockName() {
        gameCharacter.setName("New Name");
    }
}
Oleks
  • 1,011
  • 1
  • 14
  • 25