gpt4 book ai didi

javafx - 如何使用 FXML 将项目添加到 ComboBox(或其他控件)?

转载 作者:行者123 更新时间:2023-12-02 05:45:22 27 4
gpt4 key购买 nike

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

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

(一个用例可能是使 FXML 成为半功能模型,以向利益相关者展示。)

最佳答案

研究证明这是通过结合 fx:valuefx:factory 属性来完成的。这些似乎已经添加到 JavaFX 8 JavaFX 2 .

下面我会引用其中的机制,然后给出一些例子。

🦶🔫警告:

请注意,正如 @fabian 所做的那样,虽然这在短期内对于原型(prototype)或模型之类的东西效果很好,但直接将项目添加到 FXML 打破了模型之间的分离 em> 和查看——从长远来看,这可能是一个不受欢迎的结果。

机制

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>

ComboBox in FXML with default value

检查组合框

ControlsFX控件略有不同:

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

checkcombobox

TableView

TableView 变得有点复杂,因为它需要 CellValueFactory了解在每一列中显示人物的哪一部分。

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

TableView in FXML

关于javafx - 如何使用 FXML 将项目添加到 ComboBox(或其他控件)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47946127/

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