簡體   English   中英

當我的應用程序失去焦點時如何監聽?

[英]How to listen for when my application loses focus?

當應用程序窗口失去焦點時,我需要觸發一個事件。 我將如何在窗口上設置一個監聽器?

正如上面的評論所暗示的,簡單地聽你的舞台的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();
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM