Java 如何从Vaadin列表框中选择项目?

Java 如何从Vaadin列表框中选择项目?,java,listbox,vaadin,listboxitem,Java,Listbox,Vaadin,Listboxitem,我正在尝试从Vaadin listBox元素中选择一个项目。 我用数据库中的对象数组列表填充列表框。选择对象/列表项后, 我想用选定对象的属性填充文本字段。 这是到目前为止我的代码。我试了很多,但都没能成功:/ // creating a ArrayList - listOfItems - filled with Items from the Database listBox.setItems(listOfItems); listBox.setHeight(&q

我正在尝试从Vaadin 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(…)
方法提供的项目完全相同。这意味着,其中一个提供的项必须具有与要选择的项完全相同的哈希代码。否则,您的选择可能不起作用


对于一些示例,请查看:

您可以使用ListBox类的
.setValue(…)
方法。但是,当您从数据库加载数据时,必须确保您选择的项目与通过
.setItems(…)
方法提供的项目完全相同。这意味着,其中一个提供的项必须具有与要选择的项完全相同的哈希代码。否则,您的选择可能不起作用

有关一些示例,请查看:

您在这里有一个bug:

        listBox.addValueChangeListener(event -> {
            if (event.getValue() == null) {
                Notification.show(event.getValue().toString());
            } else {
                Notification.show("value is null");
            }
        });
if
语句的第一部分中,调用
event.getValue().toString()
,这将导致空指针异常,因为
event.getValue()
为空。因此,如果(event.getValue()!=null)

您这里有一个bug,请将条件翻转到

        listBox.addValueChangeListener(event -> {
            if (event.getValue() == null) {
                Notification.show(event.getValue().toString());
            } else {
                Notification.show("value is null");
            }
        });
if
语句的第一部分中,调用
event.getValue().toString()
,这将导致空指针异常,因为
event.getValue()
为空。因此,如果(event.getValue()!=null)