如何访问ScrollPane的滚动条 [英] How to access the Scrollbars of a ScrollPane

查看:67
本文介绍了如何访问ScrollPane的滚动条的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图获取有关ScrollPane中标准包含的ScrollBar组件的一些信息.特别是我对阅读水平Scrollbarheight感兴趣.我该如何引用?

I'm trying to get some information about the ScrollBar components that are by standard included in a ScrollPane. Especially i'm interested in reading the height of the horizontal Scrollbar. How can i reference it?

推荐答案

由于上述方法并不适合所有人(包括我),因此我对其进行了更多调查,并找到了问题的根源.

Since the mentioned methods did not work for everybody (including me), I investigated it a bit more and found the source of the problem.

通常,这两种方法都有效,但仅在 ScrollPane skin 属性已设置.就我而言,使用skin仍然是null. "nofollow noreferrer"> FXMLLoader .

In general, both methods work, but only as soon as the ScrollPane's skin property has been set. In my case, skin was still null after loading my view using FXMLLoader.

通过在未初始化skin属性的情况下延迟调用(使用单发侦听器)解决了该问题.

By delaying the call in case the skin property has not been initialized (using a one-shot listener) solves the problem.

工作样板代码:

ScrollPane scrollPane;
// ...
if (scrollPane.getSkin() == null) {
    // Skin is not yet attached, wait until skin is attached to access the scroll bars
    ChangeListener<Skin<?>> skinChangeListener = new ChangeListener<Skin<?>>() {
        @Override
        public void changed(ObservableValue<? extends Skin<?>> observable, Skin<?> oldValue, Skin<?> newValue) {
            scrollPane.skinProperty().removeListener(this);
            accessScrollBar(scrollPane);
        }
    };
    scrollPane.skinProperty().addListener(skinChangeListener);
} else {
    // Skin is already attached, just access the scroll bars
    accessScrollBar(scrollPane);
}

private void accessScrollBar(ScrollPane scrollPane) {
    for (Node node : scrollPane.lookupAll(".scroll-bar")) {
        if (node instanceof ScrollBar) {
            ScrollBar scrollBar = (ScrollBar) node;
            if (scrollBar.getOrientation() == Orientation.HORIZONTAL) {
                // Do something with the horizontal scroll bar

                // Example 1: Print scrollbar height
                // System.out.println(scrollBar.heightProperty().get());

                // Example 2: Listen to visibility changes
                // scrollBar.visibleProperty().addListener((observable, oldValue, newValue) -> {
                //     if(newValue) {
                //         // Do something when scrollbar gets visible
                //     } else {
                //         // Do something when scrollbar gets hidden
                //     }
                // });
            }
            if (scrollBar.getOrientation() == Orientation.VERTICAL) {
                // Do something with the vertical scroll bar
            }

        }
    }
}

这篇关于如何访问ScrollPane的滚动条的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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