Reputation: 940
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();
}
Upvotes: 2
Views: 401
Reputation: 18792
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();
}
Upvotes: 3
Reputation: 5463
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
Upvotes: 5