1

I want cut my code in fxml.

fx1.textProperty().addListener((observable, oldValue, newValue)->{
    doThis();
});
fx2.textProperty().addListener((observable, oldValue, newValue)->{
    doThis();
});
fx3.textProperty().addListener((observable, oldValue, newValue)->{
    doThis();
});
fx4.textProperty().addListener((observable, oldValue, newValue)->{
    doThis();
});
fx5.textProperty().addListener((observable, oldValue, newValue)->{
    doThis();
});

I want loop in this component. Any suggestions?

Neuron
  • 5,141
  • 5
  • 38
  • 59
Light
  • 175
  • 1
  • 2
  • 11

1 Answers1

3

If this is an all-Java application (or if these controls are created in Java), you can simply create them in a loop and register the listener when you create them:

for (int i=0 ; i < 5 ; i++) {
    TextField fx = new TextField();
    fx.textProperty().addListener((obs, oldText, newText) -> doThis());
    somePane.getChildren().add(fx);
}

If these are FXML-injected, they need their own identity. The shortest code is probably to create a stream:

Stream.of(fx1, fx2, fx3, fx4, fx5)
    .map(TextField::textProperty)
    .forEach(text -> text.addListener((obs, oldText, newText) -> doThis()));

Also see adding elements defined in FXML to list with loop

James_D
  • 201,275
  • 16
  • 291
  • 322