我尝试对齐两个javafx.scene.control.ScrollPanes的垂直滚动位置
sp1.vvalueProperty().bindBidirectional(sp2.vvalueProperty());
问题是这些ScrollPanes中的一个可能有一个水平滚动条。因此,我向下滚动ScrollPanes的次数越多,它们就越不对齐(见截图)。我怎么处理这个?
除非你在两个ScrollPane
s中显示滚动条,否则不可能使用2个ScrollPane
s和相同高度的内容执行此操作:
考虑内容完全符合左viewport
的ScrollPane
的情况。右viewPort
的ScrollPane
可以通过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();
}