如何从 Vaadin-listBox 中选择项目?

问题描述

我正在尝试从 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");
            }
        });

有人知道为什么吗?

提前致谢

解决方法

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

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

,

你这里有一个错误:

        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)