JavaFX - 以编程方式滚动 ScrollPane 的约束

JavaFX - Constraints in programmatically scrolling a ScrollPane

我正在尝试通过代码滚动包含 XYChart 的 ScrollPane

@FXML
private ScrollPane graphSP;

例如,将其滚动到 half-way point 可以使用以下序列:

Stage stage = new Stage();
stage.show();
graphSP.setHvalue(.5);

问题是,如果我在别处调用 setHvalue(),它什么也不做。

所以想知道,实际导致 ScrollPane 滚动的约束是什么?或者,在我的程序中哪里可以调用setHvalue()

场景可见后需要设置ScrollPane的Hvalue/Vvalue即stage.isShowing()为真

编辑

调用它的一种方法是在调用 stage.show() 之后。

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception {
        LineChart<Number, Number> chart = new LineChart<>(new NumberAxis(), new NumberAxis());
        ScrollPane scrollPane = new ScrollPane(chart);
        primaryStage.setScene(new Scene(scrollPane, 300, 300));
        primaryStage.show();
        scrollPane.setVvalue(0.5);
        scrollPane.setHvalue(0.5);
    }

    public static void main(String[] args) {
        launch(args);
    }
}

但是,在某些情况下可能无法引用舞台。在这种情况下,您可以使用以下内容:

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception {
        LineChart<Number, Number> chart = new LineChart<>(new NumberAxis(), new NumberAxis());
        ScrollPane scrollPane = new ScrollPane(chart);
        primaryStage.setScene(new Scene(scrollPane, 300, 300));

        scrollPane.getScene().getWindow().showingProperty().addListener((observable, oldValue, newValue) -> {
            if (newValue) {
                scrollPane.setVvalue(0.5);
                scrollPane.setHvalue(0.5);
            }
        });
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}