如何创建使用另一个ComboBox中的值的ComboBox? JavaFX [英] How can I create a ComboBox that uses values from another ComboBox? JavaFX
问题描述
我有两个组合框:水果
和饮料
。
水果
具有以下字符串:苹果,橙色,香蕉
饮料
具有以下字符串:水,咖啡,果汁
如何制作具有用户为水果$选择的值的新组合框c $ c> ComboBox和
饮料
ComboBox?
How can I make a new ComboBox that has the values the user selects for the fruits
ComboBox and the drinks
ComboBox?
例如:如果用户选择苹果
和水
,新的组合框应包括苹果
和水
作为选项。
ex: if the user selects apple
and water
, the new ComboBox should include apple
and water
as options.
推荐答案
使用监听器获取值前2个
ComboBox
的code>属性,并从中更新第三个
Use a listener to the value
properties of the first 2 ComboBox
es and update the items of the third from it:
@Override
public void start(Stage primaryStage) {
ComboBox<String> c1 = new ComboBox<>();
c1.getItems().addAll("apple", "orange", "banana");
ComboBox<String> c2 = new ComboBox<>();
c2.getItems().addAll("water", "coffee", "juice");
ComboBox<String> c3 = new ComboBox<>();
ChangeListener<String> listener = (o, oldValue, newValue) -> {
final List<String> items = c3.getItems();
int index = items.indexOf(oldValue);
if (index >= 0) {
if (newValue == null) {
items.remove(index);
} else {
items.set(index, newValue);
}
} else if (newValue != null) {
items.add(newValue);
}
};
c1.valueProperty().addListener(listener);
c2.valueProperty().addListener(listener);
final VBox vBox = new VBox(c1, c2, c3);
primaryStage.setScene(new Scene(vBox));
primaryStage.show();
}
请注意,这不会阻止在两个 ComboBox
es。
Note that this does not prevent the same string to be added from both ComboBox
es.
如果只想添加而不删除项目,请将侦听器更改为
If you want to add only without removing items, change the listener to
ChangeListener<String> listener = (o, oldValue, newValue) -> {
final List<String> items = c3.getItems();
int index = items.indexOf(newValue);
if (index < 0) {
items.add(newValue);
}
};
此侦听器确实防止重复项。
This listener does prevent duplicate items.
这篇关于如何创建使用另一个ComboBox中的值的ComboBox? JavaFX的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!