Javafx:使用FXML的可重用集合 [英] Javafx: Reusable collections using FXML

查看:338
本文介绍了Javafx:使用FXML的可重用集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'd like to bind a single collection to multiple ChoiceBox's in FXML. However the only way I know how is using:

<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>

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

Is it possible to declare the collection in the controller and refer to it in FXML instead of copying the collection for each ChoiceBox?

推荐答案

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

You can define the items in the 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) ;
    }

    // ...
}

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

and then (this is not tested, but I think it will work):

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

参见表达式绑定。 (实际上没有记录控制器在FXML命名空间中可用,键控制器,但我认为使用它是安全的。)

See expression binding in the FXML documentation. (It's not actually documented that the controller is available in the FXML namespace with key controller, but I think it is safe to use this.)

您也可以使用 fx:define

You can also just define the list in the FXML using fx:define:

<fx:define>

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

</fx:define>

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

and then refer to it in each choice box:

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

这篇关于Javafx:使用FXML的可重用集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆