JavaFX:窗口关闭事件阻止按钮操作

时间:2014-05-21 14:15:35

标签: button popup javafx focus

我确实在新阶段实现了一个弹出窗口,我现在正试图关闭它,无论我点击哪里(不包括弹出窗口本身)。这很好用。虽然当我点击背景上的另一个元素(例如按钮)时弹出窗口消失,但我仍然希望获得该按钮的事件。有关如何实现这一目标的任何建议?我把一个简短的例子放在一起。

package application;

import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.Pane;

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) {
        try {
            BorderPane root = new BorderPane();
            Scene scene = new Scene(root, 400, 400);
            scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
            primaryStage.setScene(scene);

            // the popup
            Pane p = new Pane();
            p.setPrefSize(100, 100);
            p.setStyle("-fx-background-color: #660066");
            final Stage popUp = new Stage();
            Scene popUpScene = new Scene(p);

            popUp.setScene(popUpScene);

            Button btnShow = new Button("Show popUp");
            root.setCenter(btnShow);
            btnShow.setOnMouseClicked(new EventHandler<Event>() {

                @Override
                public void handle(Event event) {
                    ChangeListener stageFocusListener = new ChangeListener<Boolean>() {
                        @Override
                        public void changed(ObservableValue<? extends Boolean> arg0, Boolean oldPropertyValue, Boolean newPropertyValue) {
                            if (!newPropertyValue) {
                                popUp.hide();
                            }
                        }
                    };
                    popUp.focusedProperty().addListener(stageFocusListener);
                    popUp.show();

                }
            });

            Button btnTest = new Button("test");
            root.setRight(btnTest);
            btnTest.setOnMouseClicked(new EventHandler<Event>() {

                @Override
                public void handle(Event event) {
                    System.out.println("Button test clicked");
                }
            });

            primaryStage.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

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

1 个答案:

答案 0 :(得分:0)

您可以将隐藏事件放入队列,而不会干扰按钮的事件处理过程

if (!newPropertyValue) {
    Platform.runLater(new Runnable() {
        @Override
        public void run() {
            popUp.hide();
        }
    });
}