ExternalResource in Vaadin 10 - Custom Icons for Button

1k views Asked by At

I would like to use a custom icon from a picture file in Vaadin 10.

Up to Vaadin 8 it was possibleto load the icon file via ExternalResource:

public final static Resource MY_ICON    = new ExternalResource("VAADIN/images/my_icon.png");

and then just use the resource as icon:

Button button = new Button("My Button text");
button.setIcon(MY_ICON);

The setIcon method in Vaadin 10 requires a Component as parameter. How can i load my Icon into a Component? Is there some out of the box solution in vaadin 10?

I would prefer a solution with pure java like in vaadin 7/8.

2

There are 2 answers

0
d2k2 On BEST ANSWER

I will post also my own solution since its specific for Button Icon Styling. You have to load the icon file into a vaadin Image (com.vaadin.flow.component.html.Image) first. but it also requires some additional styling to position the icon correctly in the button.

import com.vaadin.flow.component.html.Image;

public enum MyIcons {

    ICON_1("frontend/img/icon_1.png", ""),
    ICON_2("frontend/img/icon_2.png", ""):

    private String url;
    private String alt;

    MyIcons(String url, String alt) {
        this.url = url;
        this.alt = alt;
    }



    public Image create() {
        Image image = new Image(url, alt);
        image.getStyle().set("vertical-align", "middle"); // otherwise the icon will be just on the top left corner in the button
        return image;
    }

    /**
     * marign right distance if using Icon in Button with Text. so there is space between the icon and the button text
     * @param margin_right
     * @return
     */
    public Image create(int margin_right) {
        Image image = create();
        image.getStyle().set("margin-right", margin_right+"px"); //some space between icon and button text
        return image;
    }

}

usage:

Button button = new Button();
button.setIcon(MyIcons.ICON_1.create());

Button buttonWithText = new Button("My button text");
buttonWithText.setIcon(MyIcons.ICON_1.create(), 10); //10px space between icon and button text
1
Leif Åstrand On

I'd recommend putting your icon file as /src/main/webapp/my_icon.png (or /src/main/resources/META-INF/resources/my_icon.png if packaging as a .jar). You can then use it anywhere in your application using the built-in com.vaadin.flow.component.html.Image component, e.g. add(new Image("my_icon.png", "My icon"));.