我需要设置一个监听器,每次调用 show()
方法来显示窗口时,该监听器都可以调用一个方法。我怎样才能做到这一点?
最佳答案
您可能对 WindowListener
感兴趣。
来自the tutorial, "How to Write Window Listeners" :
The following window activities or states can precede a window event:
- Opening a window — Showing a window for the first time.
- Closing a window — Removing the window from the screen.
- Iconifying a window — Reducing the window to an icon on the desktop.
- Deiconifying a window — Restoring the window to its original size.
- Focused window — The window which contains the "focus owner".
- Activated window (frame or dialog) — This window is either the focused window, or owns the focused window.
- Deactivated window — This window has lost the focus. For more information about focus, see the AWT Focus Subsystem specification.
如果您不想实现所有这些,您可以使用 WindowAdapter
,如下:
myFrame.addWindowListener(new WindowAdapter() {
@Override
public void windowOpened(WindowEvent we) {
System.out.println("this window was opened for the first time");
}
@Override
public void windowActivated(WindowEvent we) {
System.out.println("this window or a subframe was focused");
}
});
关于窗口打开时运行的 Java 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15469904/