Bartosz Kolej
Bartosz Kolej

Reputation: 117

Vaadin save theme

In app i want give possibility of change theme, but if I refresh page it is going back to default theme i don't know how to save theme for all app, someone can help me ?

import com.vaadin.ui.ComboBox;
import com.vaadin.ui.CustomComponent;


public class ThemeSelectorComboBox extends CustomComponent
{
    private static final String SELECT_THEME = "Select theme:";
    private final ComboBox<CustomTheme> comboBox = new ComboBox<>();

public ThemeSelectorComboBox()
{
    init();
}

private void init()
{
    comboBox.setCaption(SELECT_THEME);
    comboBox.setItems(CustomTheme.values());
    comboBox.setSelectedItem(CustomTheme.MATERIAL_DARK);
    comboBox.addValueChangeListener(event -> flipTheme(event.getValue()));
    setCompositionRoot(comboBox);

    // Set the size as undefined at all levels
    comboBox.setSizeUndefined();
    setSizeUndefined();
}

private void flipTheme(CustomTheme theme)
{
    if (theme != null)
    {
        getCompositionRoot().getUI().setTheme(theme.getThemeName());


    }
}

}

Upvotes: 0

Views: 100

Answers (1)

eeq
eeq

Reputation: 2118

By default Vaadin executes the UI.init on browser reload which resets the theme. You have basically two options:

  1. Store the selected theme in a class variable and also call setTheme in your UI.init() if this variable has been set.
  2. Use @PreserveOnRefresh annotation to UI class to automatically maintain the the full UI state. When using this annotation this case the UI.init only called once on session start.

Upvotes: 2

Related Questions