2016-11-22 49 views
1

我想弄清楚如何滚动ScrollPane,这样嵌套在其内容中的任何Node都可以显示出来。目标Node可能有很多层次的嵌套,我无法预测。如何调整ScrollPane以使其某个子节点在视口内可见?

这与我所能得到的差不多。它的工作原理,但它是一个骇客,并有一个错误,在特定条件下产生一个无限的递归调用循环。一定有更好的方法。

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); 
      } 
     } 
    } 
} 

回答

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())); 
} 
相关问题