问题
I have two ComboBoxes: fruits and drinks.
fruits has the Strings: "apple", "orange", "banana"
drinks has the Strings: "water", "coffee", "juice"
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.
回答1:
Use a listener to the value properties of the first 2 ComboBoxes 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();
}
Note that this does not prevent the same string to be added from both ComboBoxes.
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.
来源:https://stackoverflow.com/questions/56457169/how-can-i-create-a-combobox-that-uses-values-from-another-combobox-javafx