【问题标题】:ExternalResource in Vaadin 10 - Custom Icons for ButtonVaadin 10 中的 ExternalResource - 按钮的自定义图标
【发布时间】:2018-11-06 21:17:55
【问题描述】:

我想在 Vaadin 10 中使用图片文件中的自定义图标。

直到 Vaadin 8 可以通过 ExternalResource 加载图标文件:

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

然后将资源用作图标:

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

Vaadin 10 中的 setIcon 方法需要一个组件作为参数。如何将我的图标加载到组件中? vaadin 10 中是否有一些开箱即用的解决方案?

我更喜欢纯 java 的解决方案,例如 vaadin 7/8。

【问题讨论】:

    标签: vaadin vaadin10 vaadin-flow


    【解决方案1】:

    我建议将您的图标文件设置为/src/main/webapp/my_icon.png(或者/src/main/resources/META-INF/resources/my_icon.png,如果打包为.jar)。然后,您可以使用内置的 com.vaadin.flow.component.html.Image 组件在应用程序中的任何位置使用它,例如add(new Image("my_icon.png", "My icon"));.

    【讨论】:

    • 感谢您的快速帮助。我也在论坛中找到了这个解决方案。我也会发布我的解决方案,因为它还需要一些样式才能在按钮中正确定位。
    【解决方案2】:

    我也会发布我自己的解决方案,因为它是专门针对按钮图标样式的。 您必须先将图标文件加载到 vaadin Image (com.vaadin.flow.component.html.Image) 中。但它还需要一些额外的样式才能在按钮中正确定位图标。

    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;
        }
    
    }
    

    用法:

    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
    

    【讨论】:

      猜你喜欢
      • 2018-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-07
      • 2016-07-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多