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

前端 未结 1 1960
野的像风
野的像风 2021-01-16 17:02

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.


    

        
相关标签:
1条回答
  • 2021-01-16 17:12

    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())));
        }
    }
    
    0 讨论(0)
提交回复
热议问题