The itemsProperty()
is the 要在组合框弹出窗口中显示的项目列表 https://openjfx.io/javadoc/14/javafx.controls/javafx/scene/control/ComboBox.html#itemsProperty;它的值是一个ObservableList
.
The valueProperty()
is the 所选项目 https://openjfx.io/javadoc/14/javafx.controls/javafx/scene/control/ComboBoxBase.html#valueProperty(如果组合框可编辑,则为用户输入的值)。
我建议的是data组合框中是键列表,并使用自定义单元格将每个单元格中的文本绑定到这些键的翻译。我不会说 scala,但在 Java 中它看起来像:
ComboBox<String> comboBox = new ComboBox<>();
comboBox.getItems().setAll(getAllKeys());
class TranslationCell extends ListCell<String> {
@Override
protected void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
textProperty().unbind();
if (empty || item == null) {
setText("");
} else {
textProperty().bind(createStringBinding(item));
}
}
}
comboBox.setCellFactory(lv -> new TranslationCell());
comboBox.setButtonCell(new TranslationCell());
现在请注意,valueProperty()
包含key为选定的值。
如果您确实想将项目绑定到ObservableValue<ObservableList<String>>
你可以这样做:
comboBox.itemsProperty().bind(Bindings.createObjectBinding(() ->
FXCollections.observableArrayList(...),
...));
第一个在哪里...
是一个可变参数String
值,第二个...
是一个可观察的值,其变化将提示列表重新计算。 (所以就你而言,我猜你有一个ObservableValue<Locale>
代表当前语言环境的某个地方;您可以将其用于第二个参数。)
在您的特定用例中(只有列表的第一个元素是国际化的),简单地使用侦听器可能会更容易:
comboBox.getItems().setAll(
noneOptionTest.getValue(),
"COUNT()",
"AVG()",
"SUM");
noneOptionTest.addListener((obs, oldVal, newVal) ->
comboBox.getItems().set(0, newVal));
虽然我同意这稍微不太优雅。
为了完整性:
我对两者之间的差异感到矛盾ObservableValue
,
ObservableList
and Property
接口,因为它们听起来都一样。
ObservableValue<T>
: 代表类型的单个值T
这可以是observed(意味着代码发生变化时可以执行)。
Property<T>
: 代表一个writable ObservableValue<T>
;目的是实现将有一个代表该值的实际变量。它定义了附加功能,允许其值绑定到其他ObservableValue<T>
.
因此,例如:
DoubleProperty x = new SimpleDoubleProperty(6);
DoubleProperty y = new SimpleDoubleProperty(9);
ObservableValue<Number> product = x.multiply(y);
x
and y
都是Property<Number>
;实施SimpleDoubleProperty
有一个实际的double
代表这个值的变量,你可以做类似的事情y.set(7);
更改值。
另一方面,product
不是一个Property<Number>
;你不能改变它的值(因为这样做会违反binding:声明的不变量product.getValue() == x.getValue() * y.getValue()
);然而它是可观察到的,这样你就可以绑定它:
BooleanProperty answerCorrect = new SimpleBooleanProperty();
answerCorrect.bind(product.isEqualTo(42));
etc.
An ObservableList
有点不同:它是一个java.util.List
(元素的集合),你可以观察它的响应列表上的操作。 IE。如果你添加一个监听器ObservableList
,侦听器可以确定元素是否被添加或删除等。