GUI之外的ClickListener

时间:2018-07-18 10:05:17

标签: java user-interface events event-handling onclicklistener

是否可以在后台运行一个程序(例如JavaFX GUI),并使clickEvents保持活动状态?例如如果单击则播放声音 谢谢!

1 个答案:

答案 0 :(得分:0)

您可以参考此答案How to detect mouseclick event outside the stage and close it

基本上,您需要向stage.focusedProperty()注册一个侦听器,并在focus属性更改为false时调用函数。

修改后的代码

    import javafx.application.Application;
    import javafx.scene.Scene;
    import javafx.scene.control.Button;
    import javafx.scene.control.Label;
    import javafx.scene.layout.StackPane;
    import javafx.stage.Modality;
    import javafx.stage.Stage;

    public class CloseWindowOnClickOutside extends Application {

        @Override
        public void start(Stage primaryStage) {
            Button showPopup = new Button("Show popup");
            showPopup.setOnAction(e -> {
                Stage popup = new Stage();
                Scene scene = new Scene(new Label("Popup"), 120, 40);
                popup.setScene(scene);
                popup.initModality(Modality.APPLICATION_MODAL);
                popup.initOwner(primaryStage);
                popup.focusedProperty().addListener((obs, wasFocused, isNowFocused) -> {
                  //if the click is outside the stage  
                    if (! isNowFocused) {
                        myFunction();
                    }
                });
                popup.show();
            });

            StackPane root = new StackPane(showPopup);
            Scene scene = new Scene(root, 350, 120);
            primaryStage.setScene(scene);
            primaryStage.show();
        }

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

        public void myFunction(){
         //handle the event here
        }
    }