如何使用 FXML 将项目添加到组合框(或其他控件)?

How can I add items to a ComboBox (or other Control) using FXML?

最近,我发现 <ComboBox> 和其他控件可以在它们下面有一个 <items> 元素。

如何向 FXML 标记中的控件填充或添加项目?

(一个用例可能是使 FXML 具有半功能性,作为向利益相关者展示的模型。)

研究证明,它是通过 fx:valuefx:factory 属性的组合完成的。这些似乎是在JavaFX 8 JavaFX 2.

中添加的

下面,我将引用这些机制,然后举例说明。

警告:

请注意,正如@fabian 所做的那样,虽然这在短期内适用于原型或模型之类的东西,但将项目直接添加到 FXML 打破了 modelview——从长远来看,这可能是一个不受欢迎的结果。

机制

fx:value

The fx:value attribute can be used to initialize an instance of a type that does not have a default constructor but provides a static valueOf(String) method. For example, java.lang.String as well as each of the primitive wrapper types define a valueOf() method and can be constructed in FXML as follows:

   <String fx:value="Hello, World!"/>
   <Double fx:value="1.0"/>
   <Boolean fx:value="false"/>

Custom classes that define a static valueOf(String) method can also be constructed this way.

来源:JavaFX 2 Introduction to FXML


fx:factory

The fx:factory attribute is another means of creating objects whose classes do not have a default constructor. The value of the attribute is the name of a static, no-arg factory method for producing class instances. For example, the following markup creates an instance of an observable array list, populated with three string values:

<FXCollections fx:factory="observableArrayList">
    <String fx:value="A"/>
    <String fx:value="B"/>
    <String fx:value="C"/>
</FXCollections>

来源:JavaFX 2 Introduction to FXML


一些例子:

组合框

<ComboBox value="One">
    <items>
        <FXCollections fx:factory="observableArrayList">
            <String fx:value="Three"/>
            <String fx:value="Two"/>
            <String fx:value="One"/>
        </FXCollections>
    </items>
</ComboBox>

检查组合框

ControlsFX控件有点不同:

<CheckComboBox>
    <items>
        <String fx:value="One"/>
        <String fx:value="Two"/>
        <String fx:value="Three"/>
    </items>
</CheckComboBox>

TableView

TableView 变得有点复杂,因为它需要 CellValueFactorys 才能知道在每一列中显示 Person 的哪一部分。

<TableView prefHeight="200.0" prefWidth="200.0">
    <columns>
     <TableColumn text="Name">
        <cellValueFactory>
            <PropertyValueFactory property="name" />
        </cellValueFactory>
     </TableColumn>
     <TableColumn text="Comment">
        <cellValueFactory>
            <PropertyValueFactory property="comment" />
        </cellValueFactory>
     </TableColumn>
    </columns>  
    <items>
        <FXCollections fx:factory="observableArrayList">
            <Person name="Jacob" comment="Hey!"/>
            <Person name="Isabella" comment="Dude, we're in FXML!"/>
            <Person name="Ethan" comment="No way!"/>
        </FXCollections>
    </items>
</TableView>