【问题标题】:How do I adjust a ScrollPane to make one of its child Nodes visible within the viewport?如何调整 ScrollPane 以使其子节点之一在视口中可见?
【发布时间】:2016-11-22 20:44:31
【问题描述】:

我正在试图弄清楚如何滚动 ScrollPane 以便可以使嵌套在其内容中的任何 Node 可见。目标Node 可能有很多我无法预测的嵌套级别。

这大约是我所能得到的。它可以工作,但它是一个相当黑客,并且有一个错误会在某些条件下产生无限的递归调用循环。必须有更好的方法。

private void ensureVisible(ScrollPane scrollPane, Node node) {

    Bounds viewportBounds = scrollPane.localToScene(scrollPane.getBoundsInLocal());
    Bounds nodeBounds = node.localToScene(node.getBoundsInLocal());

    if (!viewportBounds.contains(nodeBounds)) {
        if (nodeBounds.getMaxY() > viewportBounds.getMaxY()) {
            // node is below of viewport
            scrollPane.setVvalue(scrollPane.getVvalue() + 0.01);

            if (scrollPane.getVvalue() != 1.0) {
                ensureVisible(scrollPane, node);
            }
        } else if (nodeBounds.getMinY() < viewportBounds.getMinY()) {
            // node is above of viewport
            scrollPane.setVvalue(scrollPane.getVvalue() - 0.01);

            if (scrollPane.getVvalue() != 0.0) {
                ensureVisible(scrollPane, node);
            }
        } else if (nodeBounds.getMaxX() > viewportBounds.getMaxX()) {
            // node is right of viewport
            scrollPane.setHvalue(scrollPane.getHvalue() + 0.01);

            if (scrollPane.getHvalue() != 1.0) {
                ensureVisible(scrollPane, node);
            }
        } else if (nodeBounds.getMinX() < viewportBounds.getMinX()) {
            // node is left of viewport
            scrollPane.setHvalue(scrollPane.getHvalue() - 0.01);

            if (scrollPane.getHvalue() != 0.0) {
                ensureVisible(scrollPane, node);
            }
        }
    }
}

【问题讨论】:

    标签: javafx java-8 javafx-8


    【解决方案1】:

    只需将坐标从Node 的坐标系转换为内容的坐标系即可。根据内容大小、视口大小和转换后的坐标,您可以确定滚动位置:

    public static void scrollTo(ScrollPane scrollPane, Node node) {
        final Node content = scrollPane.getContent();
        Bounds localBounds = node.getBoundsInLocal();
        Point2D position = new Point2D(localBounds.getMinX(), localBounds.getMinY());
    
        // transform to content coordinates
        while (node != content) {
            position = node.localToParent(position);
            node = node.getParent();
        }
    
        final Bounds viewportBounds = scrollPane.getViewportBounds();
        final Bounds contentBounds = content.getBoundsInLocal();
    
        scrollPane.setHvalue(position.getX() / (contentBounds.getWidth() - viewportBounds.getWidth()));
        scrollPane.setVvalue(position.getY() / (contentBounds.getHeight() - viewportBounds.getHeight()));
    }
    

    【讨论】:

      猜你喜欢
      • 2012-10-02
      • 1970-01-01
      • 2020-09-15
      • 1970-01-01
      • 1970-01-01
      • 2023-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多