简体   繁体   中英

How to listen for when my application loses focus?

I need to trigger an event when the application window loses focus. How would I set up a listener on the window for that?

As the comments above suggest, simply listening to your stage's focusedProperty is the right way to do this.

Refer to the simple example application below to see how it works:

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class WindowFocusExample extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) {

        // Simple interface
        VBox root = new VBox(5);
        root.setPadding(new Insets(10));
        root.setAlignment(Pos.CENTER);

        // A label to show our current focus status
        Label label = new Label("Window has focus.");

        // Let's listen for our window to get/lose focus
        primaryStage.focusedProperty().addListener((observable, oldValue, newValue) -> {
            if (newValue) {
                label.setText("Window HAS focus.");
            } else {
                label.setText("Window has LOST focus!");
            }

            System.out.println(label.getText());
        });

        root.getChildren().add(label);

        // Show the Stage
        primaryStage.setWidth(300);
        primaryStage.setHeight(300);
        primaryStage.setScene(new Scene(root));
        primaryStage.show();
    }
}

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