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?

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.