Search code examples
componentsvaadinrenderervaadin-grid

Constructing ComponentRenderer in Vaadin 24


I am trying to modify an application that was created 2.5 years ago with Vaadin 23. I have upgraded to Vaadin 24.6.0 and got tons of compilation errors due to deprecation of multiple functions and classes. I fixed most of them, but stuck with one type of error - default constructor for the ComponentRenderer does not exist any more. My application displays a grid with the books information and every column is rendered specifically. Here is example of one of renderers, which creates an unordered list of book authors.

public class AuthorListRenderer extends ComponentRenderer<UnorderedList, Book> {
    
    @Override
    public UnorderedList createComponent(Book source) {
        Set<Author> authors = source.getAuthors();
        ListItem[] items = new ListItem[authors.size()];
        int i = 0;
        for (Author author : authors) {
            String item = ((author.getFirstName() == null) ? "" : (author.getFirstName() + " "))
                    + author.getLastName() + ((author.getNickName() == null) ? "" : (" (" + author.getNickName() + ")"));
            ListItem listItem = new ListItem(item);
            listItem.getStyle().set("font-style", "italic");
            listItem.getStyle().set("white-space", "normal");
            items[i++] = listItem;
        }
        return new UnorderedList(items);
    }
}

Now, instead of default constructor I need to use one of the four parametrized constructors, but I do not quite understand how those SerializableFunction or serializableSupplier works. I wasn't able to find any explanation or examples in Vaadin documentation. If someone can explain it to me, I will appreciate it.


Solution

  • The different c'tors basically provide the following features:

    • you create a component, that is agnostic of the current item (e.g. some static content for each row)
    • you create a component, that gets created for the item (most likely, what you want)
    • you create a component and later update it depending on the item
    • you create a component depending on the item and later want to create a different component depending on the item

    Details can be found in the Docs on Grid/Component Renderer and JavaDoc for ComponentRenderer

    E.g. (being explicit here, so no λ)

    class AuthorListRenderer extends ComponentRenderer<UnorderedList, Book> {
        AuthorListRenderer() {
            super(new SerializableFunction<Book, UnorderedList>() {
                @Override
                UnorderedList apply(Book book) {
                    new UnorderedList(
                            book.authors.collect { new ListItem(it.toString()) } as ListItem[]
                    )
                }
            })
        }
    }