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

拜拜、爱过 提交于 2020-04-07 01:23:40

问题


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())));
    }
}


来源:https://stackoverflow.com/questions/29330435/how-do-i-scroll-to-a-certain-component-in-java-fx

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!