【问题标题】:How do I show a lot of text using Vaadin?如何使用 Vaadin 显示大量文本?
【发布时间】:2024-01-06 09:18:01
【问题描述】:

我需要处理一些数据并在网页上显示处理日志。 (大约 300 行文本)。
我尝试使用标签。起初它工作得很好 - 页面变得可滚动并且可以看到所有文本。但是在大约 100 个标签页面变得没有响应之后。
如何管理这个任务?
(我试图在 webcomponents.org 上寻找其他一些组件,但找不到任何东西。)

【问题讨论】:

  • 您尝试过使用 TextArea 吗?
  • @btreport 不,因为我找不到将文本附加到 TextArea 并执行 textArea.setValue(textArea.getValue() + newLineOfText); 300 次的方法,在我看来这不是一个好的解决方案。
  • 不太确定,但如果您认为 DOM 就是 2-way 绑定的工作方式,那么当值更新时您会更新 DOM 上的元素。

标签: vaadin vaadin10 vaadin-flow


【解决方案1】:

TextArea

我尝试了Answer by Leif Åstrand 中提到的一种方法,使用TextArea

当我预加载 300 条短线时,没问题。单击一个按钮一次添加 10 多行可以顺利进行。使用 Web 浏览器的窗口滚动条可以流畅地上下滚动。

我使用 Vaadin 10.0.4 和 Java 10.0.1 (Zulu by Azul Systems),在 macOS High Sierra 上的浏览​​器 Safari 11.1.2 上连接到 MacBook Pro Retina 的外部 4K 显示器。

这是整个 Vaadin 应用程序。

package com.basilbourque.example;

import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.dependency.HtmlImport;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.component.textfield.TextArea;
import com.vaadin.flow.router.Route;

import java.time.Instant;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * The main view contains a button and a template element.
 */
@HtmlImport ( "styles/shared-styles.html" )
@Route ( "" )
public class MainView extends VerticalLayout {
    TextArea textArea;

    // Constructor.
    public MainView () {
        this.setWidth( "100%" );

        this.textArea = new TextArea( "Logs" );
        this.textArea.setWidth( "100%" );
        this.textArea.setReadOnly( true );
        this.appendRows( 300 );

        Button button = new Button( "Add 10 more rows" , event -> {
            this.appendRows( 10 );
        } );

        this.add( button , this.textArea );
        this.setClassName( "main-layout" );
    }

    private void appendRows ( int countRows ) {
        List< String > entries = new ArrayList<>( countRows );
        for ( int i = 1 ; i <= countRows ; i++ ) {
            entries.add( Instant.now().toString() );
        }
        Collections.reverse( entries ); // Put newest on top.
        String s = entries.stream().collect( Collectors.joining( "\n" ) );
        textArea.setValue( s + "\n" + this.textArea.getValue() );
    }
}

【讨论】:

    【解决方案2】:

    您可以将所有文本仅放在一个组件中,而不是为每一行创建一个单独的组件。如果您希望文本中的换行符(即\n)换行到下一行,您可以将元素的white-space CSS 属性调整为例如pre-linepre-wrap 代替。您可以使用component.getElement().getStyle().set("white-space", "pre-wrap") 执行此操作。

    如果您想直观地指示文本的状态,另一种选择可能是只读TextArea 组件。

    我还建议在 Vaadin 10 中使用 Span 组件而不是 LabelLabel 在浏览器中使用 &lt;label&gt; 元素,它实际上仅用于标记输入字段,但不用于一般用途一堆文字。

    【讨论】: