Vaadin14 Tooltip on Combobox Selection Mouseover

拥有回忆 提交于 2020-05-15 08:16:05

问题


I'm using Vaadin 14 + Java.

I have a combobox with an enum as possible select items.

I want to display the enum in the combobox as possible selects, but I want to show the longer attribute "name" on mouseover / tooltip.

I saw that there has been the same question for older versions of Vaadin (and there was no solution apparently) and was wondering if there is an option to do that by now.

ComboBox

ComboBox<MyEnum> cb = new ComboBox<>();
cb.setLabel("MyComboBox");
cb.setItems(MyEnum.values());

//cb.setDescription --> does not exist for ComboBox?

My enum class:

public enum MyEnum {

    HIGH("High long name explanation"),
    MEDIOCRE("Mediocre long name explanation"),
    LOW("Low long name explanation");

    private final String name;

    private MyEnum(String name) {
        this.name = name;
    }

    public String getValue(){
      return name;
    }

}

回答1:


On the HTML level, creating a tooltip is done by defining a title property on the element.

But that title property must be placed on the options and not the comboBox itself, and the ComboBox doesn't have a java API for doing that like comboBox.setItemTooltipProvider(..).

However, there is a java API for defining a Renderer, which will then be applied to each item. Instead of using a Renderer that simply returns the name of the option as String, we can also use a ComponentRenderer to be applied to each item. There you create a Span component containing the displayed item name (e.g. "HIGH"), and on that Span element you define the title property.

ComboBox<MyEnum> comboBox = new ComboBox<>();
comboBox.setLabel("MyComboBox");
comboBox.setItems(MyEnum.values());
comboBox.setRenderer(new ComponentRenderer<>(item -> {
    Span span = new Span(item.name());
    span.getElement().setProperty("title", item.getValue());
    return span;
}));



来源:https://stackoverflow.com/questions/61202914/vaadin14-tooltip-on-combobox-selection-mouseover

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!