如何访问ScrollPane的滚动条 [英] How to access the Scrollbars of a ScrollPane
问题描述
我试图获取有关ScrollPane
中标准包含的ScrollBar
组件的一些信息.特别是我对阅读水平Scrollbar
的height
感兴趣.我该如何引用?
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屋!