如何检测舞台外的鼠标点击事件并关闭它 [英] How to detect mouseclick event outside the stage and close it

查看:190
本文介绍了如何检测舞台外的鼠标点击事件并关闭它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个充当弹出窗口的舞台,如果用户在该舞台外点击,我想关闭舞台,如何实现,舞台充当弹出窗口的代码如下:

I have a stage that acts as popup,I want to close the stage if the user clicks outside that stage,how to achieve that,My code for the stage acting as popup is as follows:

    Stage stage = new Stage();
    Parent root = FXMLLoader.load(getClass().getResource("colorchange.fxml"));
    Scene sce = new Scene(root,400,400);
    stage.initModality(Modality.APPLICATION_MODAL);
    stage.initOwner(color.getScene().getWindow());
    stage.setScene(sce);
    stage.showAndWait(); 


推荐答案

使用阶段注册一个监听器.focusedProperty()并调用 stage.hide()如果焦点属性更改为 false

Register a listener with stage.focusedProperty() and call stage.hide() if the focused property changes to false.

SSCCE:

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 (! isNowFocused) {
                    popup.hide();
                }
            });
            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);
    }
}

这篇关于如何检测舞台外的鼠标点击事件并关闭它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆