JavaFX 图像适合 ScrollPane 的宽度

问题描述

我正在尝试在 ScrollPane 中加载图像并使图像始终适合 ScrollPane 的宽度,即使在调整窗口大小时也是如此,这样您只需垂直滚动即可。我正在使用 Scene Builder 8.5.0 并且 ScrollPane 的适合宽度属性设置为 true,但它不起作用并且图像仍然扩展到超出 ScrollPane 的可见宽度。保留比率也设置为 true。这是我用于此的组件层次结构:

enter image description here

我也尝试使用代码设置适合宽度属性,但这也不起作用

imgScrollPane.setFitToWidth(true);

我错过了什么吗?

解决方法

正如您所注意到的,您使用 AnchorPane 的方法没有按预期工作。

我同意 James_D 的评论并创建了两个示例。第一个例子是„quick-and-dirty way“,在Binding的{​​{1}}和fitWidthProperty之间有一个简单的ImageView widthProperty。第二个示例包含一个根据您的需要定制的小示例类,它覆盖了 ScrollPane 方法。

示例 1(使用 layoutChildren() 快速而肮脏):

Binding

示例 2(带有 package org.example; import javafx.application.Application; import javafx.beans.binding.Bindings; import javafx.geometry.Orientation; import javafx.scene.Scene; import javafx.scene.control.ScrollBar; import javafx.scene.control.ScrollPane; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.stage.Stage; import java.util.Optional; public class App extends Application { @Override public void start(Stage stage) { String imageUrl = "https://images.freeimages.com/images/large-previews/2e9/fisherman-in-the-lighthouse-1496152.jpg"; Image image = new Image(imageUrl); ImageView imageView = new ImageView(image); imageView.setPreserveRatio(true); ScrollPane scrollPane = new ScrollPane(imageView); scrollPane.setHbarPolicy(ScrollPane.ScrollBarPolicy.NEVER); scrollPane.setVbarPolicy(ScrollPane.ScrollBarPolicy.AS_NEEDED); // Example of how the Binding could be (here: take into account if the vertical scroll bar is showing or not): imageView.fitWidthProperty().bind(Bindings.createDoubleBinding(() -> { // Find the vertical scroll bar of the scroll pane: Optional<ScrollBar> verticalScrollBarOpt = scrollPane.lookupAll(".scroll-bar").stream() .filter(node -> node instanceof ScrollBar) .map(node -> (ScrollBar) node) .filter(scrollBar -> scrollBar.getOrientation() == Orientation.VERTICAL).findAny(); if (verticalScrollBarOpt.isPresent() && verticalScrollBarOpt.get().isVisible()) return scrollPane.getWidth() - verticalScrollBarOpt.get().getWidth(); else return scrollPane.getWidth(); },scrollPane.widthProperty())); stage.setScene(new Scene(scrollPane,1300,600)); stage.show(); } public static void main(String[] args) { launch(); } } 的自定义类):

layoutChildren()