gpt4 book ai didi

Javafx:使用 FXML 的可重用集合

转载 作者:行者123 更新时间:2023-11-30 06:41:08 24 4
gpt4 key购买 nike

我想将单个集合绑定(bind)到 FXML 中的多个 ChoiceBox。然而我知道的唯一方法是使用:

<ChoiceBox fx:id="cb00" prefWidth="150.0" GridPane.rowIndex="0" GridPane.columnIndex="0">
<items>
<FXCollections fx:id="test" fx:factory="observableArrayList">
<String fx:value="1" />
<String fx:value="2" />
<String fx:value="3" />
<String fx:value="4" />
<String fx:value="5" />
<String fx:value="6" />
<String fx:value="7" />
<String fx:value="8" />
<String fx:value="9" />
</FXCollections>
</items>
</ChoiceBox>

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

最佳答案

您可以在 Controller 中定义项目:

public class Controller {

private ListProperty<String> choiceBoxItems = new SimpleListProperty(FXCollections.observableArrayList());

public Controller() {
IntStream.range(1,10).mapToObj(i -> Integer.toString(i))
.forEach(choiceBoxItems::add);
}

public ListProperty<String> choiceBoxItemsProperty() {
return choiceBoxItems ;
}

public ObservableList<String> getChoiceBoxItems() {
return choiceBoxItemsProperty().get() ;
}

public void setComboBoxItems(ObservableList<String> choiceBoxItems) {
choiceBoxItemsProperty().set(choiceBoxItems) ;
}

// ...
}

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

<ChoiceBox fx:id="cb00" items="${controller.choiceBoxItems}" prefWidth="150.0" GridPane.rowIndex="0" GridPane.columnIndex="0">

参见expression binding在 FXML 文档中。 (实际上并没有记录表明该 Controller 在带有键 controller 的 FXML 命名空间中可用,但我认为使用它是安全的。)

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

<fx:define>

<FXCollections fx:id="choiceBoxItems" fx:factory="observableArrayList">
<String fx:value="1"/>
<String fx:value="2"/>
<String fx:value="3"/>
<!-- ... -->
</FXCollections>

</fx:define>

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

<ChoiceBox fx:id="cb00" items="${choiceBoxItems}" prefWidth="150.0" GridPane.rowIndex="0" GridPane.columnIndex="0">

关于Javafx:使用 FXML 的可重用集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44354198/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com