You need to enable JavaScript to run this app. 如何在Vaadin Flow(14.6版本)中使用Material icons
优惠活动
大模型
产品
解决方案
定价
更多

如何在Vaadin Flow(14.6版本)中使用Material icons

Vaadin 14.6 集成Material Icons 实现方案

以下是两种原生兼容方案,无需依赖不兼容的第三方组件:

方案一:基于Web字体实现(推荐,全图标支持)

  • 第一步:离线导入Material Icons字体资源
    将官方Material Icons字体包下载到项目frontend/fonts目录,在frontend/styles下新建material-icons.css文件,写入字体引入规则:
    @font-face {
      font-family: 'Material Icons';
      font-style: normal;
      font-weight: 400;
      src: url('../fonts/MaterialIcons-Regular.eot'); /* 适配IE6-8 */
      src: local('Material Icons'),
           local('MaterialIcons-Regular'),
           url('../fonts/MaterialIcons-Regular.woff2') format('woff2'),
           url('../fonts/MaterialIcons-Regular.woff') format('woff'),
           url('../fonts/MaterialIcons-Regular.ttf') format('truetype');
    }
    .material-icons {
      font-family: 'Material Icons';
      font-weight: normal;
      font-style: normal;
      font-size: 24px;  /* 默认图标大小 */
      display: inline-block;
      line-height: 1;
      text-transform: none;
      letter-spacing: normal;
      word-wrap: normal;
      white-space: nowrap;
      direction: ltr;
      -webkit-font-smoothing: antialiased;
      text-rendering: optimizeLegibility;
      -moz-osx-font-smoothing: grayscale;
      font-feature-settings: 'liga';
    }
    
    之后在你的UI类或者全局布局类上添加注解加载样式:
    @StyleSheet("./styles/material-icons.css")
    public class MainView extends VerticalLayout {
      // 你的布局逻辑
    }
    
  • 第二步:封装自定义图标组件
    新建通用MaterialIcon组件类,方便全局调用:
    import com.vaadin.flow.component.html.Span;
    
    public class MaterialIcon extends Span {
      public MaterialIcon(String iconName) {
        addClassName("material-icons");
        setText(iconName);
      }
    
      // 可选扩展:自定义图标大小
      public MaterialIcon withSize(String fontSize) {
        getStyle().set("font-size", fontSize);
        return this;
      }
    
      // 可选扩展:自定义图标颜色
      public MaterialIcon withColor(String color) {
        getStyle().set("color", color);
        return this;
      }
    }
    
  • 第三步:直接调用使用
    在任意布局中直接传入官方图标名即可使用:
    // 示例:显示红色20px大小的主页图标
    add(new MaterialIcon("home").withSize("20px").withColor("red"));
    

方案二:基于SVG文件实现(无需字体依赖)

如果不想引入字体包,可单独下载需要的Material Icons SVG文件,放入项目frontend/icons目录,直接用Vaadin自带的Icon组件加载即可:

import com.vaadin.flow.component.icon.Icon;

// 加载frontend/icons/home.svg图标
Icon homeIcon = new Icon("icons", "home.svg");
add(homeIcon);

以上两种方案均原生兼容Vaadin 14.6全版本,兼容性模式和NPM模式都可正常运行。

内容的提问来源于stack exchange,提问作者macnixde

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.15 22:15:05