Reputation:
So say I have a stage in JavaFX. Instead of closing the window by pressing the X close button I just hide the window or say switch to some other application on my computer. Whenever either I hide the window or switch to any other window of my PC I want the stage to close automatically.
I tried these three methods but all of these activate only when I close the window myself, not when I hide the window.
popupStage.setOnHidden(event -> Console.log("Hidden"));
popupStage.setOnHiding(event -> Console.log("Hidden"));
popupStage.setOnCloseRequest(event -> Console.log("Hidden"));
Any help would be greatly appreciated. Thanks.
Upvotes: 1
Views: 713
Reputation: 4712
Try using the focusedProperty of the Window object (stage inherits this from Window).
You can add a listener to this property to get notified as soon as the user switches the active window.
import javafx.application.Application;
import javafx.beans.value.ObservableValue;
import javafx.stage.Stage;
public class Example extends Application {
public static void main(String args[]) {
Application.launch(args);
}
@Override
public void start(Stage stage) {
stage.focusedProperty().addListener(this::focusChanged);
stage.setTitle("demo");
stage.show();
}
private void focusChanged(ObservableValue<? extends Boolean> property, Boolean wasFocused, Boolean isFocused) {
System.out.println("Window changed focus from " + wasFocused + " to " + isFocused);
}
}
Upvotes: 2