Search code examples
javavaadinvaadin7

Update a ListSelect in Vaadin 7


I need to update the list of a ListSelect after i click in one button but i dont know how to

Here is my code:

Create List Method

private void createListPanel() {
        VerticalLayout listPanel = new VerticalLayout();
        listPanel.setWidth(100f, Unit.PERCENTAGE);

        queryList= new ListSelect("List Of Querys", getQueryList());
        queryList.setWidth(100f, Unit.PERCENTAGE);

        queryList.setNullSelectionAllowed(false);

        queryList.addValueChangeListener(event -> {

            selectedQuery = (String) (queryList.getValue());
            String retrievedQuery = repository.getRawQuery(selectedQuery);

        });

        listPanel.addComponent(queryList);
        panelSuperior.addComponent(listPanel);
    }

getQueryList()

private List<String> getQueryList() {
    return repository.getQueryNames();
}

Create Button Method

private void CreateButton() {
    Button buttonRefresh= new Button("Refresh");

    buttonRefresh.addClickListener((Button.ClickEvent e) -> {
        // i tried this
        queryList.setContainerDataSource((Container) getQueryList());
    });

    buttonPanel.addComponent(button);

}

I tried this line at CreateButton() method:

queryList.setContainerDataSource((Container) getQueryList())

but i get a

java.lang.ClassCastException: java.util.ArrayList cannot be cast to com.vaadin.data.Container

because this method need a Container Object

I was searching in the Vaadin javadoc but I am not able to find a method to set or update the list of the ListSelect

Vaadin Javadoc: Vaadin Javadoc 7.7.9 ListSelect

Thanks in advance


Solution

  • The straightforward way is to remove all items from an underlying container and add new items afterward:

    Container container = queryList.getContainerDataSource();
    container.removAllItems();
    List<String> queries = getQueryList();
    for(String query : queries) {
        container.addItem(query);
    }
    

    ListSelect(String caption, Collection<?> options) constructor creates an IndexedContainer and populates it with items from your collection.

    Another option is to bind ListSelect to a container which could possibly enable it to track changes automatically. For more on this, see "Collecting Items in Containers" topic from Vaadin docs.