Search code examples
tooltiprendererlistitemvaadin23

How to make a tip showed up while hovering over list item in Vaadin 23


I have the following code in my Vaadin application:

public class TitleRenderer extends ComponentRenderer<Component, Book> {

@Override
public Component createComponent(Book book) {
    VerticalLayout layout = new VerticalLayout(createTitleLinkComponent(book));
    layout.getStyle().set("background-color", book.getHighlight());
    Set<Tag> tags = book.getTags();
    if (tags != null && !tags.isEmpty()) {
        ListItem[] tagItems = new ListItem[tags.size()];
        int tn = 0;
        for (Tag tag : tags) {
            ListItem item = new ListItem(tag.getTagName());
            item.addClassName("tag");
            tagItems[tn++] = item;
        }
        UnorderedList tagList = new UnorderedList(tagItems);
        tagList.getStyle().set("list-style-type", "none");
        
        layout.add(tagItems);
    }
    layout.setMinWidth("55%");
    return layout;
}

It displays book title and a list of tags associated with the book. However, Tag object contains not only tagName, but also tagDescription. I'd like to display tagDescription when cursor is hovering over tagName. Unfortunately, ListItem class does not implement HasToolTip interface. Can someone, please, help me to create a LitRenderer to do so. I would appreciate it greatly.


Solution

  • You can apply a Tooltip even for components that do not implement the HasTooltip interface by using the Tooltip.forComponent method:

            for (Tag tag : tags) {
                ListItem item = new ListItem(tag.getTagName());
                Tooltip tooltip = Tooltip.forComponent(item);
                tooltip.setText(tag.getDescription());