2016-11-22 63 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())); 
} 
相關問題