这是我使用 ScrollBar 的 ScrollPane 的解决方法。
public void setStyle() {
// In my program, TextField controls were generate at run-time, so the prefer height is calculated based on number of controls
int preHeight = 1000;
Group root = new Group();
// This anchor pane contains all control.
AnchorPane anchorPane = new AnchorPane();
// TODO: Add control into this anchor pane
// anchorPane.getChildren().addAll();
final ScrollBar sc = new ScrollBar();
root.getChildren().addAll(anchorPane, sc);
// Set default size for scene to 800 x 600
int sceneW = 800;
int sceneH = 600;
final Scene scene = new Scene(root, sceneW, sceneH);
// Setting for the scroll bar
sc.setLayoutX(scene.getWidth()- sc.getWidth()/2 - 1);
sc.setMin(0);
sc.setOrientation(Orientation.VERTICAL);
sc.setPrefHeight(sceneH);
sc.setMax(preHeight - sceneH);
// In case prefer height is smaller than scene height then hide the scroll bar
if(preHeight < sceneH) {
sc.setVisible(false);
}
scene.setRoot(root);
// Change the scroll bar and the anchor pane when user change scene's width
scene.widthProperty().addListener(new ChangeListener<Number>() {
@Override
public void changed(ObservableValue<? extends Number> arg0,
Number arg1, Number arg2) {
sc.setLayoutX(arg2.doubleValue()- sc.getWidth()/2 - 1);
anchorPane.setPrefWidth(arg2.doubleValue() - sc.getWidth());
}
});
// Change the scroll bar and the anchor pane when user change scene's height
scene.heightProperty().addListener(new ChangeListener<Number>() {
@Override
public void changed(ObservableValue<? extends Number> arg0,
Number arg1, Number arg2) {
sc.setMax(preHeight - arg2.doubleValue());
if(arg2.doubleValue() >= preHeight) {
sc.setVisible(false);
}
else {
sc.setVisible(true);
}
sc.setPrefHeight(arg2.doubleValue());
anchorPane.setPrefHeight(arg2.doubleValue());
}
});
// Change the Y position of anchor pane when user scroll the scroll bar
sc.valueProperty().addListener(new ChangeListener<Number>() {
public void changed(ObservableValue<? extends Number> ov,
Number old_val, Number new_val) {
anchorPane.setLayoutY(-new_val.doubleValue());
}
});
anchorPane.setPrefSize(scene.getWidth() - sc.getWidth(), scene.getHeight());
}
这种方法存在一个问题,即如果用户使用 Tab 键在屏幕中的控件之间导航,则滚动条的 Y 位置不会更改为相应的位置。您可以通过处理锚窗格中可聚焦控件的焦点事件并相应地设置滚动条的 Y 位置来解决此问题。