当我的应用程序失去焦点时该如何监听?

时间:2019-01-22 22:58:01

标签: javafx focus applicationwindow

当应用程序窗口失去焦点时,我需要触发一个事件。我该如何在窗口上设置一个侦听器?

1 个答案:

答案 0 :(得分:1)

正如上面的评论所建议的那样,简单地聆听舞台的focusedProperty是正确的方法。

请参阅下面的简单示例应用程序以了解其工作原理:

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