循环中的JavaFX所有组件

JavaFX all component in loop

我想在 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();
});

我想在这个组件中循环。有什么建议吗?

如果这是一个全 Java 应用程序(或者如果这些控件是在 Java 中创建的),您可以简单地在循环中创建它们并在创建它们时注册侦听器:

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

如果这些是 FXML 注入的,则它们需要自己的标识。最短的代码大概是创建一个流:

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

另见