How can I create a ComboBox that uses values from another ComboBox? JavaFX

℡╲_俬逩灬. 提交于 2019-12-13 05:06:37

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!