How do I scroll to a certain component in Java FX?

2020-04-01 04:07发布

问题:

I need to scroll down to a certain label component in Java FX. How do I do that ? I have ids attached to label component.

<ScrollPane>
    <VBox fx:id="menuItemsBox">
        <Label text="....."/>
        <Label text="....."/>
        <Label text="....."/>
        ....
        <Label text="....."/>
   </VBox>
</ScrollPane>

回答1:

You can set the scrollPane's vValue to the Node's LayoutY value. Since the setVvlaue() accepts value between 0.0 to 1.0, you need to have computation to range your input according to it.

scrollPane.setVvalue(/*Some Computation*/);

This must be set after the stage's isShowing() is true.

Complete Example

public class Main extends Application {
    @Override
    public void start(Stage primaryStage) throws Exception {
        ScrollPane pane = new ScrollPane();
        VBox box = new VBox();
        IntStream.range(1, 10).mapToObj(i -> new Label("Label" + i)).forEach(box.getChildren()::add);
        pane.setContent(box);
        Scene scene = new Scene(pane, 200, 50);
        primaryStage.setScene(scene);
        primaryStage.show();

        // Logic to scroll to the nth child
        Bounds bounds = pane.getViewportBounds();
        // get(3) is the index to `label4`.
        // You can change it to any label you want
        pane.setVvalue(box.getChildren().get(3).getLayoutY() * 
                             (1/(box.getHeight()-bounds.getHeight())));
    }
}