如何调整JavaFX滚动窗格内容的大小以适应当前大小



我有一个以ScrollPane为中心元素的BorderPane。它会自动调整大小以填充屏幕。在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);
}

部分代码取自此处:如何访问ScrollPane 的滚动条

尝试

ScrollPane scrollPane = new ScrollPane();
scrollPane.setFitToHeight(true);
scrollPane.setFitToWidth(true);

而不覆盖CCD_ 8方法。

通过XMLCSS:设置fitToHeightfitToWidth属性

FXML:

<ScrollPane fx:id="myScrollPane" fitToHeight="true" fitToWidth="true" />

CSS:

.my-scroll-pane {
    -fx-fit-to-height: true;
    -fx-fit-to-width: true;
}

最新更新