Is it possible to be notified whenever any window in the application was created or closed?
At the moment I'm polling Window.getWindows()
but I would prefer to get notified instead.
What I have:
List<Window> previousWindows = new ArrayList<>();
while (true) {
List<Window> currentWindows = Arrays.asList(Window.getWindows());
for (Window window : currentWindows) {
if (!previousWindows.contains(window)) {
//window was created
}
}
for (Window window : previousWindows) {
if (!currentWindows.contains(window)) {
//window was closed
}
}
previousWindows = currentWindows;
Thread.sleep(1000);
}
What I'd like:
jvm.addWindowListener(this);
@Override
public void windowWasDisplayed(Window w) {
//window was created
}
@Override
public void windowWasClosed(Window w) {
//window was closed
}
You can register listeners that receive any subset of types of AWT events via the windowing Toolkit
. From those you can select and handle the WindowEvent
s for windows being opened and closed, something like this:
class WindowMonitor implements AWTEventListener {
public void eventDispatched(AWTEvent event) {
switch (event.getID()){
case WindowEvent.WINDOW_OPENED:
doSomething();
break;
case WindowEvent.WINDOW_CLOSED:
doSomethingElse();
break;
}
}
// ...
}
class MyClass {
// alternative 1
public void registerListener() {
Toolkit.getDefaultToolkit().addAWTEventListener(new WindowMonitor(),
AWTEvent.WINDOW_EVENT_MASK);
}
// alternative 2
public void registerListener(Component component) {
component.getToolkit().addAWTEventListener(new WindowMonitor(),
AWTEvent.WINDOW_EVENT_MASK);
}
}
I would recommend alternative 2, where the Component
from which you obtain the Toolkit
is the main frame of your application (there should be only one), but alternative 1 should work out for you if you have to do this without reference to any particular component (for instance, before any have been created).
Do note, however, that registering an AWTEventListener
is subject to a security check.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With