简体   繁体   English

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

[英]JavaFX - Constraints in programmatically scrolling a ScrollPane

I am trying to scroll a ScrollPane that contains an XYChart via code. 我试图通过代码滚动包含XYChart的ScrollPane

@FXML
private ScrollPane graphSP;

Scrolling it, for instance, to the half-way point works with this sequence: 例如,将其滚动到half-way point可按以下顺序进行:

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

The problem is, if I place that call to setHvalue() elsewhere, it just does nothing. 问题是,如果我setHvalue()调用setHvalue()其他位置,则它什么都不做。

So wondering, what are the constraints to actually cause the ScrollPane to scroll? 所以想知道,实际上使ScrollPane滚动的约束是什么? Or, where can I call setHvalue() in my program. 或者,在哪里可以在程序中调用setHvalue()

You need to set the Hvalue/Vvalue of the ScrollPane after the scene is visible ie stage.isShowing() is true. 您需要在可见的场景(即stage.isShowing()为true stage.isShowing()之后设置ScrollPane的Hvalue / stage.isShowing()

EDIT 编辑

One way to call it is after the stage.show() is called. 一种调用方法是在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);
    }
}

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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