developer
developer

Reputation: 603

JavaFx how to hide popup when mouse is clicked on owner window?

Hi i have javafx app which has only one stage.On tab key press event of text field, a popup showed on primary stage of application. like below

    private void tripNoKeyPressEventAction(KeyEvent event){
            if(event.getCode() == KeyCode.TAB || event.getCode() == KeyCode.ENTER) {
                popup.show(GateIn.primaryStage);
            }
        }
popup.requestFocus();
        popup.focusedProperty().addListener(new ChangeListener<Boolean>
        () {

            @Override
            public void changed(ObservableValue<? extends Boolean> ov, Boolean t, Boolean t1) {
               if(t1==false)
               {
                   System.out.println("focus lost");
                   popup.hide();
               }
            }
        });

I don't click on the popup and don't select anything in popup. I will just click on the stage behind it.I expect popup to be closed but It gives me IllegalArgumentException before executing popup's focusedProperty Listener.

If popup is on a different stage (other than primary stage of aaplication),based on stage focusedProperty() i can hide popup. How to hide popup in case popup is shown on primary stage?

Upvotes: 0

Views: 4452

Answers (2)

Ricardo Meneghin Filho
Ricardo Meneghin Filho

Reputation: 414

With FX 8, you can simply do

popup.setAutoHide(true)

Upvotes: 4

gordonpro
gordonpro

Reputation: 281

You should set a event dispatcher for most top level window then all event will cross it.

In the popup window:

getScene().getWindow().setEventDispatcher((event, tail) -> {
        if (event.getEventType() == RedirectedEvent.REDIRECTED) {
            //  RedirectedEvent is a box that contains original event from other target
            RedirectedEvent ev = (RedirectedEvent) event;
            if (ev.getOriginalEvent().getEventType() == MouseEvent.MOUSE_PRESSED) {
                hide();
            }
        }else {
            //  if click in the popup window. handle the event by default
            tail.dispatchEvent(event);
        }
        return null;
    });

More information please see javafx.event.EventDispatcher

Upvotes: 1

Related Questions