如何创建使用另一个ComboBox中的值的ComboBox? JavaFX [英] How can I create a ComboBox that uses values from another ComboBox? JavaFX

查看:79
本文介绍了如何创建使用另一个ComboBox中的值的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.

推荐答案

使用监听器获取 ComboBox 的code>属性,并从中更新第三个的项:

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(); 
}

请注意,这不会阻止在两个 ComboBox es。

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.

这篇关于如何创建使用另一个ComboBox中的值的ComboBox? JavaFX的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆