Search code examples
javacomboboxvaadin8

How to get item size in Vaadin8 combobox?


I'm trying to show a pop-up if there is no any item in Vaadin8 combobox. But there is no getItems() or size() methods.

here is my code, if branch size = 0 I want to push a notification to user.

        cbxBranch = new ComboBox<>();
        cbxBranch.setPlaceholder("Select a branch");
        cbxBranch.setItemCaptionGenerator(Branch::getBranchName);
        cbxBranch.setEmptySelectionAllowed(false);
        cbxBranch.setItems(getBranches());
        cbxBranch.addFocusListener(e -> {
            //this line just a sample..
            System.out.println(cbxBranch.getDataProvider().size());
        });

UPDATE:

cbxBranch.addFocusListener(e -> {
    if (((ListDataProvider<Branch>) cbxBranch.getDataProvider()).getItems().isEmpty()) {
       Notification.show("You don't have a branch!", Type.WARNING_MESSAGE);
    }
});

Solution

  • Vaadin 8 uses DataProviders for item components like Grid, TreeGrid or ComboBox. The setItems method is a convenience method to set a ListDataProvider with your array/collection to the combo box. Therefore, you can call getDataProvider, cast to ListDataProvider and call getItems (see java doc here).