【问题标题】:Misalignment of two synced ScrollPanes两个同步的 ScrollPanes 未对齐
【发布时间】:2019-02-07 21:55:21
【问题描述】:

我尝试通过对齐两个javafx.scene.control.ScrollPanes的垂直滚动位置

sp1.vvalueProperty().bindBidirectional(sp2.vvalueProperty());

问题是这些 ScrollPanes 之一可能有一个水平滚动条。所以我越向下滚动 ScrollPanes,它们就越错位(见截图)。我该如何处理?

【问题讨论】:

  • 你可以让两个/所有ScrollPanes 总是有一个水平滚动条或从不有一个水平滚动条。见ScrollPane.hbarPolicy

标签: java javafx vertical-alignment vertical-scrolling scrollpane


【解决方案1】:

除非您在两个ScrollPanes 中都显示滚动条,否则用 2 个ScrollPanes 和相同高度的内容是不可能做到这一点的:

考虑内容完全符合左侧ScrollPaneviewport 的情况。右侧ScrollPaneviewPort 可以滚动ScrollBar 高度。无法修改左边的ScrollPane

由于预期结果似乎是某种规模,您可以简单地将Pane 与您应用transformY 的孩子和剪辑一起使用。计算要放置在顶部的像素的公式,使用

top = vvalue * (contentHeight - viewportHeight)

示例

private static Label createLabel(int num, boolean mark) {
    Label label = new Label(Integer.toString(num));
    label.setPrefSize(50, 50);
    label.setMaxSize(Double.MAX_VALUE, Region.USE_PREF_SIZE);
    label.setStyle(mark ? "-fx-background-color: #FFFFFF" : "-fx-background-color: #BBBBBB;");
    return label;
}

@Override
public void start(Stage primaryStage) throws Exception {
    VBox scale = new VBox();
    scale.setMinHeight(Region.USE_PREF_SIZE);
    GridPane content = new GridPane();

    for (int i = 0; i < 40; i++) {
        boolean b = ((i % 2) == 0);
        scale.getChildren().add(createLabel(i, !b));

        for (int j = 0; j < 10; j++) {
            content.add(createLabel(i * 10 + j, b), j, i);
        }
    }

    AnchorPane scaleContainer = new AnchorPane(scale);
    scaleContainer.setMinWidth(30);
    scaleContainer.setMinHeight(0);
    AnchorPane.setLeftAnchor(scale, 0d);
    AnchorPane.setRightAnchor(scale, 0d);

    Rectangle clip = new Rectangle();
    scaleContainer.setClip(clip);
    clip.widthProperty().bind(scaleContainer.widthProperty());
    clip.heightProperty().bind(scaleContainer.heightProperty());

    ScrollPane scroll = new ScrollPane(content);

    scale.translateYProperty().bind(Bindings.createDoubleBinding(() -> {
        double contentHeight = content.getHeight();
        double viewportHeight = scroll.getViewportBounds().getHeight();
        if (contentHeight <= viewportHeight) {
            return 0d;
        } else {
            return -scroll.getVvalue() * (contentHeight - viewportHeight);
        }
    }, scroll.viewportBoundsProperty(), scroll.vvalueProperty(), content.heightProperty()));

    HBox root = new HBox(scaleContainer, scroll);
    root.setPadding(new Insets(10));

    Scene scene = new Scene(root, 400, 400);

    primaryStage.setScene(scene);
    primaryStage.show();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-03
    • 1970-01-01
    • 2021-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多