Javafx:使用FXML的可重用集合

我想将一个集合绑定到FXML中的多个ChoiceBox。 然而,我知道如何使用的唯一方法:

               

是否可以在控制器中声明集合并在FXML中引用它而不是为每个ChoiceBox复制集合?

您可以在控制器中定义项目:

 public class Controller { private ListProperty choiceBoxItems = new SimpleListProperty(FXCollections.observableArrayList()); public Controller() { IntStream.range(1,10).mapToObj(i -> Integer.toString(i)) .forEach(choiceBoxItems::add); } public ListProperty choiceBoxItemsProperty() { return choiceBoxItems ; } public ObservableList getChoiceBoxItems() { return choiceBoxItemsProperty().get() ; } public void setComboBoxItems(ObservableList choiceBoxItems) { choiceBoxItemsProperty().set(choiceBoxItems) ; } // ... } 

然后(这没有经过测试,但我认为它会起作用):

  

请参阅FXML文档中的表达式绑定 。 (实际上没有记录控制器在带有密钥controller的FXML命名空间中可用,但我认为使用它是安全的。)

您也可以使用fx:define在FXML中定义列表:

         

然后在每个选择框中引用它:

  

您可以使用通过其fx:id引用现有对象。 使用此标记可以重用ObservableList

                          

它可以在控制器或任何其他类中(例如combobox。同样可以应用于选择框):

combo.fxml

    

装载机类

 //SO answer : https://stackoverflow.com/a/44355944/3992939 public class ComboLoader { private ObservableList obsStrings; public ComboLoader() { obsStrings = FXCollections.observableArrayList(createStrings()); } private List createStrings() { return IntStream.rangeClosed(0, 5) .mapToObj(i -> "String "+i) .map(String::new) .collect(Collectors.toList()); } //name of this method corresponds to itemLoader.items in xml. //if xml name was itemLoader.a this method should have been //getA(). A bit odd public ObservableList getItems(){ return obsStrings; } } 

测试它:

 public class ComboTest extends Application { @Override public void start(Stage primaryStage) throws IOException { primaryStage.setTitle("Populate combo from custom builder"); Group group = new Group(); GridPane grid = new GridPane(); grid.setPadding(new Insets(25, 25, 25, 25)); group.getChildren().add(grid); FXMLLoader loader = new FXMLLoader(getClass().getResource("combo.fxml")); loader.getNamespace().put("itemLoader", new ComboLoader()); ComboBoxcombo = loader.load(); grid.add(combo, 0, 0); Scene scene = new Scene(group, 450, 175); primaryStage.setScene(scene); primaryStage.show(); } public static void main(String[] args) { launch(args); } } 

在此处输入图像描述