【问题标题】:How to select items from a Vaadin-listBox?如何从 Vaadin-listBox 中选择项目?
【发布时间】:2021-01-04 19:12:19
【问题描述】:

我正在尝试从 Vaadin listBox 元素中选择一个项目。 我用数据库中的对象数组列表填充 listBox。选择一个对象/列表项后, 我想用所选对象的属性填充文本字段。 到目前为止,这是我的代码。我已经尝试了很多,但无法正常工作:/

// creating a ArrayList - listOfItems - filled with Items from the Database

        listBox.setItems(listOfItems);
        listBox.setHeight("100px");
        add(listBox);

        Div value = new Div();
        listBox.addValueChangeListener(event -> {
            if (event.getValue() == null) {
                Notification.show(event.getValue().toString());
            } else {
                Notification.show("value is null");
            }
        });

有人知道为什么吗?

提前致谢

【问题讨论】:

    标签: java listbox vaadin listboxitem


    【解决方案1】:

    你这里有一个错误:

            listBox.addValueChangeListener(event -> {
                if (event.getValue() == null) {
                    Notification.show(event.getValue().toString());
                } else {
                    Notification.show("value is null");
                }
            });
    

    if 语句的第一部分,调用event.getValue().toString(),会导致空指针异常,因为event.getValue() 为空。所以翻转条件为if (event.getValue() != null)

    【讨论】:

      【解决方案2】:

      您可以使用 ListBox 类的.setValue(...) 方法。但是当您从数据库加载数据时,您必须确保您选择的项目与您通过.setItems(...) 方法提供的项目之一完全相同。这意味着,提供的项目之一必须与您要选择的项目具有完全相同的 hashCode。否则您的选择可能无效。

      有关一些示例,请查看:https://vaadin.com/components/vaadin-list-box/java-examples

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-01-30
        • 1970-01-01
        • 1970-01-01
        • 2014-06-09
        • 1970-01-01
        • 2022-08-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多