简体   繁体   中英

Retain JavaFX stage position when hiding

Is there a simple way to retain the position of a JavaFX Stage that has been hidden? In Swing, when a Frame was hidden and made visible again, it would retain the position and dimensions it had when it was hidden. Is there a simple way this behavior can be achieved in JavaFX?

In my application, I have a main window with toggle buttons which are meant to be tied to showing / hiding secondary windows. Unfortunately, every time a user hides one of those secondary windows (using the toggle buttons), they open up at the center of the screen again if the user tries to make them visible again.

Any simple way around this?

public static void main(final String[] args) {
    Platform.startup(() -> {});
    Platform.runLater(() -> testStagePos());
}

protected static void testStagePos() {
    final BorderPane p = new BorderPane();
    p.setCenter(new Label("Random label"));
    p.setPadding(new Insets(100));  // Just so window isn't too small

    final Stage popup = new Stage();
    popup.setScene(new Scene(p));

    final BorderPane cp = new BorderPane();
    final ToggleButton b = new ToggleButton("Show popup");
    b.setOnAction(e -> {
        if (b.isSelected())
            popup.show();
        else
            popup.hide();
    });
    cp.setPadding(new Insets(50));
    cp.setCenter(b);

    final Stage control = new Stage();
    control.setScene(new Scene(cp));
    control.show();
}

If you set any initial position to popup, it will retain its last position when hidden.
All you have to change is add this after defining popup :
popup.setX(50);popup.setY(50);

Test it by:

private static void testStagePos() {
    final BorderPane p = new BorderPane();
    p.setCenter(new Label("Random label"));
    p.setPadding(new Insets(100));  // Just so window isn't too small

    final Stage popup = new Stage();
    popup.setScene(new Scene(p));
    popup.setX(50);popup.setY(50); //set initial position

    final BorderPane cp = new BorderPane();
    final ToggleButton b = new ToggleButton("Show popup");
    b.setOnAction(e -> {
        if (b.isSelected()) {
            popup.show();
            b.setText("Hide popup");
        } else {
            System.out.println(popup == null );
            popup.hide();
            b.setText("Show popup");
        }
    });
    cp.setPadding(new Insets(50));
    cp.setCenter(b);

    final Stage control = new Stage();
    control.setScene(new Scene(cp));
    control.show();
}

Add this just after creating the popup.

    popup.setOnShown((e) -> {
        popup.setX(popup.getX());
        popup.setY(popup.getY());
    });

Building up on https://stackoverflow.com/a/48822302/600379

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