JavaFX autoscroll down scroll
Is there a way for the ScrollPane to automatically scroll as its content height increases? For example, I have a TitledPane at the bottom of the screen (inside a ScrollPane) and when I expand it, I would like the ScrollPane to scroll down so I can see all the content of the TitledPane.
source to share
You must tell the scrollpane where the current coordinates are before passing the value to the vertical or horizontal bar.
This code works really well for me:
// the owner node of your scrollPane;
titledPane.layout();
// the maxValue for scrollPane bar ( 1.0 it the default value )
scrollPane.setVvalue( 1.0d );
You need to code this when your scrollpane grows. For example, if you are adding nodes to an internal scrollpane node, add a list of listeners to it.
If the inner scroll node changes its height, add a listener to heightProperty.
For example, the inner node of your scrollPane is an AnchorPane and you are adding nodes to that panel, so follow these steps:
anchorPane.getChildren().addListener(
( ListChangeListener.Change<? extends Node> c ) -> {
titledPane.layout();
scrollPane.setVvalue( 1.0d );
}
);
If it is a height that grows ...
heightProperty().addListener(
(observable, oldValue, newValue) -> {
titledPane.layout();
scrollPane.setVvalue( 1.0d );
}
);
What is it!
source to share
I did it using AnimationTimer. I had to wait 100,000,000 nanoseconds to make sure the ScrollPane responded to the extended 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();
}
source to share