使 Vaadin 在替换组件时不滚动

Make Vaadin not scroll when replacing components

我有一个 VerticalLayout 包含两个(大)组件:一个 grid 和一个 chart. 图表会根据网格中的选择进行更新。为此,我正在使用 VerticalLayoutreplaceComponent 方法。因此,当在网格中选择一个项目时,图表会更新,但 浏览器会向上滚动 而不是 保持滚动位置 。这可能是因为 Vaadin 首先从 DOM 中删除图表,然后添加新图表。

是否可以在更换组件时保持滚动位置?

到目前为止,我没有在网上找到任何答案。如有必要,我可以制作 SSCCE

UI objectgetScrollTopsetScrollTop 方法。

有了这些应该可以处理您的要求。 在删除组件之前使用 getScrollTop 检索滚动条位置,在修改对象之后使用 setScrollTop 到先前保存的值。

感谢 André,我发现在替换组件上设置固定高度可以解决问题。这是一个 SSCCE:

@Override
protected void init(VaadinRequest request) {
    VerticalLayout layout = new VerticalLayout();
    layout.setMargin(true);
    layout.setSpacing(true);
    setContent(layout);

    TextField t1 = new TextField("Big field (1)");
    t1.setWidth("300px");
    t1.setHeight("1000px");
    layout.addComponent(t1);

    TextField t2 = new TextField("Big field (2)");
    t2.setWidth("300px");
    t2.setHeight("1000px");
    layout.addComponent(t2);

    final Component[] toReplace = new Component[] { t2 };

    Button button = new Button("Click Me");
    button.addClickListener(event -> {
        Table t = new Table();
        t.addContainerProperty("Name", String.class, null);
        for (int i = 0; i < 20; i++) {
            t.addItem(new Object[] { "" + i }, i);
        }
        //t.setHeight("200px");

        layout.replaceComponent(toReplace[0], t);
        toReplace[0] = t;
    });
    layout.addComponent(button);

    setContent(layout);
}

未设置高度时出现滚动问题