I want to bind text field to indicate whether list of integer contain 1. i have a button that insert 1 to the list and I want the text field will update but this doesn't happens. why and how can i repair it?
@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("Hello World!");
final List<Integer> list = new ArrayList<Integer>();
Button btn = new Button();
btn.setText("Say 'Hello World'");
btn.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
list.add(1);
}
});
TextField txt = new TextField();
txt.textProperty().bind(new SimpleStringProperty(String.valueOf(list.contains(1))));
VBox root = new VBox();
root.getChildren().addAll(btn,txt);
primaryStage.setScene(new Scene(root, 300, 250));
primaryStage.show();
}
Try creating a BooleanBinding:
Let's break down the code:
new SimpleStringProperty(String.valueOf(list.contains(1)));
-> initially
list.contains(1)
= false->
String.valueOf(false)
= "false"->
new SimpleStringProperty("false")
will create new instance ofStringProperty
with initial value "false", and this instance is bound to textProperty of textField. That is it, since we are initiating with the String value "false", no further observation forlist
and its content where it contains 1 or not. Hence we need an observable list here.Thus the textfield's text will change in sync if the bound StringProperty is changed. Rewriting as,