窗口打开时运行的 Java 方法

标签 java swing user-interface jframe show

我需要设置一个监听器,每次调用 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/

相关文章:

Java方法: Finding object in array list given a known attribute value

java - 如何通过 Hibernate 将枚举字段设置为 Integer 到 db?

java - 在 Java 中使用 CardLayout

ios - 如何让 iOS Button 在按下时提供视觉反馈?

java - 使用同一窗口内更改面板显示

windows - 创建独立于操作系统的 GUI 软件的可能性

java - 如何以编程方式将 TableRow 从 xml 添加到 TableLayout?

java - Log4J Swing 附加程序

java - 使用java 2D图形旋转的黑色区域?

java - 带有用于 javadoc doclet 的自定义 xml 序列化程序的 ClassNotFoundException