Vaadin 23如何实现Vaadin 8中Label的预格式化文本效果?
在Vaadin 23中实现预格式化文本展示
在Vaadin 23里,你可以通过以下几种方式实现和Vaadin 8中Label(..., ContentMode.PREFORMATTED)相同的效果,保留文本中的换行符\n和空格格式:
1. 使用Pre组件(推荐)
Vaadin 23提供了专门的Pre组件,用于展示预格式化文本,无需额外配置即可自动保留换行、空格等格式:
Pre preComponent = new Pre("Preformatted text is shown in an HTML <pre> tag.\n" + "Formatting such as\n" + " * newlines\n" + " * whitespace\n" + "and such are preserved. HTML tags, \n"+ "such as <b>bold</b>, are quoted.");
2. 基于Label组件实现
如果你更倾向于继续使用Label组件,有两种可行方案:
方案一:沿用ContentMode.PREFORMATTED
Vaadin 23的Label组件仍支持ContentMode.PREFORMATTED枚举,用法和Vaadin 8基本一致:
Label preLabel = new Label("Preformatted text is shown in an HTML <pre> tag.\n" + "Formatting such as\n" + " * newlines\n" + " * whitespace\n" + "and such are preserved. HTML tags, \n"+ "such as <b>bold</b>, are quoted.", ContentMode.PREFORMATTED);
方案二:通过CSS样式强制保留格式
通过设置Label的CSSwhite-space属性为pre,同样可以实现格式保留:
Label preLabel = new Label("Preformatted text is shown in an HTML <pre> tag.\n" + "Formatting such as\n" + " * newlines\n" + " * whitespace\n" + "and such are preserved. HTML tags, \n"+ "such as <b>bold</b>, are quoted."); preLabel.getStyle().set("white-space", "pre");
内容的提问来源于stack exchange,提问作者alexanoid
相关产品推荐
相关产品推荐

