13

How can I run a piece of code (or more exactly: close the stage) when the JavaFX stage lost it's focus?

For example in Dropbox or Chrome: if you click the tray icon, a small window opens. If you click anywhere on the screen now, the window closes. Exactly this is the behaviour I want to create in my JavaFX application.

I searched a long time already for a solution, but couldn't find one...
So, I'm looking for something something like this:

stage.addEventHandler(EventType.FOCUS_LOST, new EventHandler() { /*...*/ } );


Thank you for helping me out!

dumazy
  • 13,857
  • 12
  • 66
  • 113
momar
  • 171
  • 1
  • 7

1 Answers1

25

Add a listener to stage.focusedProperty().

primaryStage.focusedProperty().addListener(new ChangeListener<Boolean>()
{
  @Override
  public void changed(ObservableValue<? extends Boolean> ov, Boolean onHidden, Boolean onShown)
  {
    <Your code here>
  }
});
Hassan Mahmud
  • 484
  • 4
  • 13
OttPrime
  • 1,878
  • 1
  • 15
  • 24
  • 1
    just a note: `t` is an old value, `t1` is a new one. so, for this case `t` stands for `onHidden`, `t1` - `onShown` – Enigo Oct 19 '17 at 21:55