如何调整JavaFX ScrollPane内容的大小以适应当前大小

Len*_*ert 49 resize javafx scrollpane autolayout

我有一个BorderPaneScrollPane为中心元素.它会自动调整大小以填充屏幕.里面ScrollPane是一个HBox没有内容但是是一个拖放目标.因此,我希望它填补其父母ScrollPane.

这样做的首选方法是什么?

到目前为止我所尝试的是重写ScrollPane.resize(...)调整大小的方法,HBox但它似乎相当复杂和非正统.

编辑:要为此添加一些有用的代码,这就是我可以解决问题的方法,但我相信必须有更好的方法来做到这一点:

@Override
public void resize(double width, double height) {
    super.resize(width, height);

    double scrollBarHeight = 2;
    double scrollBarWidth = 2;

    for (final Node node : lookupAll(".scroll-bar")) {
        if (node instanceof ScrollBar) {
            ScrollBar sb = (ScrollBar) node;
            if (sb.getOrientation() == Orientation.HORIZONTAL) {
                System.out.println("horizontal scrollbar visible = " + sb.isVisible());
                System.out.println("width = " + sb.getWidth());
                System.out.println("height = " + sb.getHeight());
                if(sb.isVisible()){
                    scrollBarHeight = sb.getHeight();
                }
            }
            if (sb.getOrientation() == Orientation.VERTICAL) {
                System.out.println("vertical scrollbar visible = " + sb.isVisible());
                System.out.println("width = " + sb.getWidth());
                System.out.println("height = " + sb.getHeight());
                if(sb.isVisible()){
                    scrollBarWidth = sb.getWidth();
                }
            }
        }
    }

    hBox.setPrefSize(width-scrollBarWidth, height-scrollBarHeight);
}
Run Code Online (Sandbox Code Playgroud)

代码部分取自此处:如何访问ScrollPane的Scrollbars

Ulu*_*Biy 81

尝试

ScrollPane scrollPane = new ScrollPane();
scrollPane.setFitToHeight(true);
scrollPane.setFitToWidth(true);
Run Code Online (Sandbox Code Playgroud)

没有覆盖resize()方法.

  • @ Andrew121007它是`<ScrollPane fx:id ="scrollPane"fitToHeight ="true"fitToWidth ="true">` (8认同)

NDY*_*NDY 22

通过或设置fitToHeightfitToWidth属性:XMLCSS

FXML:

<ScrollPane fx:id="myScrollPane" fitToHeight="true" fitToWidth="true" />
Run Code Online (Sandbox Code Playgroud)

CSS:

.my-scroll-pane {
    -fx-fit-to-height: true;
    -fx-fit-to-width: true;
}
Run Code Online (Sandbox Code Playgroud)

  • 我想添加此选项在Scene Builder中可用.在"布局"下的任何滚动窗格中 - >"特定"(从顶部开始) - >适合宽度/高度.我花了一段时间才发现这有助于某人. (3认同)