简体   繁体   中英

JavaFX - Constraints in programmatically scrolling a ScrollPane

I am trying to scroll a ScrollPane that contains an XYChart via code.

@FXML
private ScrollPane graphSP;

Scrolling it, for instance, to the half-way point works with this sequence:

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

The problem is, if I place that call to setHvalue() elsewhere, it just does nothing.

So wondering, what are the constraints to actually cause the ScrollPane to scroll? Or, where can I call setHvalue() in my program.

You need to set the Hvalue/Vvalue of the ScrollPane after the scene is visible ie stage.isShowing() is true.

EDIT

One way to call it is after the stage.show() is called.

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);
    }
}

But, there may be cases where a reference to stage is not available. In those case you can use the following :

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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM