How to Add Language flags in Vaadin 10 Combo box

女生的网名这么多〃 提交于 2019-12-31 03:15:12

问题


How to Add Language flags in Vaadin 10 Como box


回答1:


You can use comboBox.setRenderer() to build your own layout that will be used.

comboBox.setRenderer(new ComponentRenderer<HorizontalLayout, MyLanguageClass>(language -> {
    HorizontalLayout layout = new HorizontalLayout();
    layout.add(new Image(language.getPathToFlag(), language.getName()));
    layout.add(new Label(language.getName()));
    return layout;
}));

This example will do a basic HorizontalLayout with an Image and a Label. You can of course adjust this further to your needs. I used a ComponentRenderer here, but you can also use a TemplateRenderer

Please note that you still have to use comboBox.setItemLabelGenerator() in addition to comboBox.setRenderer(), because the renderer is not used for the selected item - only for the item list. As far as I know, there is no way yet to use a renderer for the selected item.


Edit for Vaadin 13 / Vaadin 14:
With Vaadin 13+, you can use the Component Select to achieve exactly what you want - the selected option also shows a flag!

private ComponentRenderer<HorizontalLayout, Locale> languageRenderer = new ComponentRenderer<>(item -> {
    HorizontalLayout hLayout = new HorizontalLayout();
    Image languageFlag = new Image("img/languageflags/"+item.getLanguage()+".png", "flag for "+item.getLanguage());
    languageFlag.setHeight("30px");
    hLayout.add(languageFlag);
    hLayout.add(new Span(getTranslation("LanguageSelection."+item.getLanguage())));
    hLayout.setDefaultVerticalComponentAlignment(Alignment.CENTER);
    return hLayout;
});
private Select<Locale> langSelect;

private Select<Locale> buildLanguageSelection() {
    langSelect = new Select<>();
    langSelect.setEmptySelectionAllowed(false);
    langSelect.setRenderer(this.languageRenderer);
    langSelect.setItems(new Locale("de"), new Locale("fr"), new Locale("en"));
    langSelect.setValue(UI.getCurrent().getLocale());
    langSelect.addValueChangeListener(change -> UI.getCurrent().getSession().setLocale(change.getValue()));
    return langSelect;
}

@Override
public void localeChange(LocaleChangeEvent event) {
    // because the renderer uses `getTranslation()`, this will re-translate the shown values using the new Locale.
    // if langSelect.refreshItems() ever becomes public, use that instead
    langSelect.setRenderer(languageRenderer);
}

Edit 2: I published the Class LanguageSelect as an add-on in the vaadin repository which bases on this code but is much simpler to use. Available for Vaadin 14 only.

LanguageSelect langSelect = new LanguageSelect(new Locale("de"), new Locale("fr"), new Locale("en"));
add(langSelect);

// in localeChange() 
langSelect.refresh();



来源:https://stackoverflow.com/questions/53763178/how-to-add-language-flags-in-vaadin-10-combo-box

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