TabSheet always (lazy) initialise the first tab

Hi,

I use TabSheet with lazy loading tabs as mentioned in the docs

I store the index of the last selected tab in session in order to restore this selection if the view is shown again.

Unfortunately, after lazy initializing the tab with the stored index id, also the first tab is initialized, but thankfully the content is not switched. Surprisingly, the order of those lazy initialising is

  • first the stored tab index (correct)
  • then the tab #0 (wrong)

See the following MRE:

var tab1 = new Tab("Tab 1");
var tab2 = new Tab("Tab 2");
var tab3 = new Tab("Tab 3");

TabSheet tabSheet = new TabSheet();
tabSheet.addThemeVariants(TabSheetVariant.LUMO_TABS_CENTERED);
tabSheet.setSizeFull();

tabSheet.add(tab1, new LazyTabComponent(() -> {log.debug("tab1"); return new Div("Tab 1"); }));
tabSheet.add(tab2, new LazyTabComponent(() -> {log.debug("tab2"); return new Div("Tab 2"); }));
tabSheet.add(tab3, new LazyTabComponent(() -> {log.debug("tab3"); return new Div("Tab 3"); }));

tabSheet.setSelectedIndex(2);
add(tabSheet);

The logs shows the order of execution as

DEBUG de.hub28.steel42.ui.TestView             tab3
DEBUG de.hub28.steel42.ui.TestView             tab1

Is this a bug or how can I prevent the initializing of tab #0 ?

That happens because the underlying Tabs component is instantiated with autoselect=true and you don’t have a sensible way of configuring them. As a workaround you might need to use reflection.

Opening a ticket is definitely worth it.

Hi @knoobie,

thanks for your fast and helpful response … what would we do without you :slight_smile:

For the record, with the following helper method based on reflection, the problem could be fixed. I will definitely create a ticket to extend the API.

private void setAutoselect(TabSheet tabSheet, boolean value) {
    try {
        Field field = TabSheet.class.getDeclaredField("tabs");
        field.setAccessible(true);
        Method method = Tabs.class.getMethod("setAutoselect", boolean.class);
        Tabs tabs = (Tabs) field.get(tabSheet);
        method.invoke(tabs, value);
    } catch (NoSuchFieldException | NoSuchMethodException | IllegalAccessException | InvocationTargetException ex) {
        ex.printStackTrace();
    }
}

Thanks again

kind regards
Dominik