如何滚动到Java FX中的某个组件? [英] How do I scroll to a certain component in Java FX?

查看:41
本文介绍了如何滚动到Java FX中的某个组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要向下滚动到Java FX中的某个标签组件.我怎么做 ?我在标签组件上附加了ID.

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>

推荐答案

您可以将scrollPane的vValue设置为Node的LayoutY值.由于 setVvlaue() 接受0.0 to 1.0之间的值,您需要进行计算才能根据它调整输入范围.

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*/);

必须在舞台的 isShowing() true.

完整示例

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

这篇关于如何滚动到Java FX中的某个组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆