Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to react to getting focus from another application?

My JavaFX 8 application has to doStuff() when it gets focused. That's pretty simple:

primaryStage.focusedProperty().addListener((observable, wasFocused, nowFocused) -> {
    doStuff();
});

However, when I display a dialog and user closes it, doStuff() fires. I want it to fire only when user switches from another app to mine, for example Alt+Tab from a browser.

In other words, I want to doStuff() iff other app's window loses focus and my app's window gets focus.

Is it possible?

Edit: Answers posted by FibreFoX and Appelemac require explicitly performing additional step before showing a dialog. This solution is far from perfect, because I (or any developer, in general) have to remember about this step before showing a dialog. Forgetting about it will introduce hard to find bugs.

Extending Dialog to do it automatically isn't an option, because I want to use built-in dialogs that already extend original Dialog.

That's pretty basic feature, I'd be surprised if there's no easy way to achieve this in JavaFX.

like image 498
gronostaj Avatar asked Nov 27 '25 13:11

gronostaj


2 Answers

You could use a global boolean when opening such dialogs, and only when that global switch is true/false/whatever-you-choose then you could react on that state-switch.

public class GlobalDialogMemory{
    public static boolean dialogShown = false;
}

When using CDI you could inject the application-scoped current instance (but you should use getter/setter and non-static booleans instead ;)

like image 84
FibreFoX Avatar answered Nov 29 '25 01:11

FibreFoX


I'd suggest adding a listener to your Dialog, which then allows you to not doStuff() if the Dialog was just closed/lost focus.

Easiest way I can think of is setting an Instant (with Instant.now) when the dialog is closed, and if the application regains focus, create another Instant, and check whether the Duration.between(instantLostFocusDialog, instantGainedFocusApp).getSeconds() exceeds 1 (or add getNano() to that to be more specific). Only then would you doStuff()

like image 29
Appelemac Avatar answered Nov 29 '25 02:11

Appelemac



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!