JavaFX自动向下滚动滚动窗格

当内容的高度增加时,是否有任何方法可以自动向下滚动ScrollPane控件? 例如,我在屏幕底部(ScrollPane内部)有一个TitledPane,当我展开它时,我希望ScrollPane向下滚动,这样我就能看到TitledPane的全部内容。

使用titledPane.localToScene()scrollPane.setVvalue()组合可以实现该行为

第一个是获得titledPane的坐标,而第二个是设置scrollPane的垂直条位置。 请注意,它的范围介于0 – 1之间。

您可以bind ScrollPane vvalue属性与内部容器的heightProperty bind 。 例如,如果您的ScrollPaneVBox

 scrollPane.vvalueProperty().bind(vBox.heightProperty()); 

在将值传递给垂直或水平条之前,您必须告诉scrollpane当前坐标的位置。

这段代码对我来说很好用:

 // the owner's node of your scrollPane; titledPane.layout(); // the maxValue for scrollPane bar ( 1.0 it's the default value ) scrollPane.setVvalue( 1.0d ); 

您必须在滚动窗格增长的地方对此进行编码。 例如,如果将节点添加到滚动窗格内部节点,则向其添加一个侦听器的子列表。

如果scrollpane的内部节点更改了它的高度,请向heightProperty添加一个侦听器。

例如,您的scrollPane的内部节点是一个AnchorPane,您将节点添加到此窗格,所以这样做:

 anchorPane.getChildren().addListener( ( ListChangeListener.Change c ) -> { titledPane.layout(); scrollPane.setVvalue( 1.0d ); } ); 

如果它是增长的高度……

 heightProperty().addListener( (observable, oldValue, newValue) -> { titledPane.layout(); scrollPane.setVvalue( 1.0d ); } ); 

而已!

你可以像这样在TitledPane的height属性中添加一个监听器:

 titledPane.heightProperty().addListener((observable, oldValue, newValue) -> vvalueProperty().set(newValue.doubleValue())); 

我是通过使用AnimationTimer完成的。 我不得不等待100000000纳秒才能确保ScrollPane对扩展的Titlepane做出反应。

 public void scrollNodeInTopScrollPane(Node n, ScrollPane s) { final Node node = n; final ScrollPane clientTopScrollPane = s; AnimationTimer timer = new AnimationTimer() { long lng = 0; @Override public void handle(long l) { if (lng == 0) { lng = l; } if (l > lng + 100000000) { if (node.getLocalToSceneTransform().getTy() > 20) { clientTopScrollPane.setVvalue(clientTopScrollPane.getVvalue() + 0.05); if (clientTopScrollPane.getVvalue() == 1) { this.stop(); } } else { this.stop(); } } } }; timer.start(); }