我尝试通过对齐两个javafx.scene.control.ScrollPane的垂直滚动位置。
sp1.vvalueProperty().bindBidirectional(sp2.vvalueProperty());
问题是其中一个ScrollPanes可能有一个水平滚动条。所以我越往下滚动ScrollPanes,它们就越不对准(见截图)。我该怎么处理呢?
发布于 2018-09-03 08:01:20
除非在两个ScrollPane
中都显示滚动条,否则不可能在2个ScrollPane
和相同高度的内容中执行此操作:
考虑这样一种情况,即内容恰好适合左侧ScrollPane
的viewport
。右侧ScrollPane
的viewPort
可以按ScrollBar
高度滚动。无法修改左侧的ScrollPane
。
由于预期的结果似乎是某种比例,您可以简单地使用带有应用transformY
的子对象的Pane
和一个剪辑。计算要放在顶部的像素的公式,使用
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();
}
https://stackoverflow.com/questions/52139630
复制相似问题