是否可以在应用程序中的任何窗口创建或关闭时得到通知?
目前我正在进行民意调查,Window.getWindows()
但我更愿意收到通知.
是)我有的:
ListpreviousWindows = new ArrayList<>(); while (true) { List 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); }
我想要的是什么:
jvm.addWindowListener(this); @Override public void windowWasDisplayed(Window w) { //window was created } @Override public void windowWasClosed(Window w) { //window was closed }
John Bolling.. 8
您可以通过窗口注册接收任何类型的AWT事件子集的侦听器Toolkit
.从那些你可以选择和处理WindowEvent
窗口打开和关闭,如下所示:
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); } }
我建议使用替代方案2,其中Component
您获得的Toolkit
是您应用程序的主框架(应该只有一个),但如果您必须在不参考任何特定组件的情况下执行此操作,则替代方案1应该适合您(对于实例,在创建之前).
但请注意,注册AWTEventListener
是否需要进行安全检查.
您可以通过窗口注册接收任何类型的AWT事件子集的侦听器Toolkit
.从那些你可以选择和处理WindowEvent
窗口打开和关闭,如下所示:
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); } }
我建议使用替代方案2,其中Component
您获得的Toolkit
是您应用程序的主框架(应该只有一个),但如果您必须在不参考任何特定组件的情况下执行此操作,则替代方案1应该适合您(对于实例,在创建之前).
但请注意,注册AWTEventListener
是否需要进行安全检查.