diegoaguilar
diegoaguilar

Reputation: 8376

How to make the text in a JavaFX TextField change automatically using bindings?

I tried this statement:

movieTextField.textProperty().bindBidirectional(new SimpleStringProperty(YIFY.getPeliculaBuscada(), "peliculaBuscada"));

Being movieTextField a JavaFX TextField and YIFY.getPeliculaBuscada() returning a String.

At the moment of the call, getPeliculaBuscada has an initialized String but the TextField isn't showing anything.

How can I accomplish it?

Upvotes: 0

Views: 1310

Answers (1)

James_D
James_D

Reputation: 209330

The SimpleStringProperty constructor taking two parameters (see Javadocs) takes the object which is the owner of the property, and the name of the property. Neither of these parameters is the initial value of the parameter, which is null by default.

To create a StringProperty which has the value you want, you can do

movieTextField.textProperty().bindBidirectional(new SimpleStringProperty(YIFY.getPeliculaBuscada()));

However, this isn't really going to do anything, other that initialize the text in the text field: it's functionally equivalent to

movieTextField.setText(YIFY.getPeliculaBuscada());

The reason is that the text in the text field is bound to the StringProperty to which you no longer have a reference. Because you don't have a reference to the StringProperty, you have no other way of changing it, so there is no point in the text being bound to it. On the other hand, if the text in the text field changes, the StringProperty will be updated; but since you have no reference to it you have no way of observing that change.

What you are probably looking for is to have the class of which YIFY is an instance use a StringProperty and expose it through a StringProperty peliculaBuscadaProperty() method. Then you would do movieTextField.textProperty().bind(YIFY.peliculaBuscadaProperty());

Upvotes: 1

Related Questions