本文介绍了如何关闭JDialog并通知Window事件监听器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法通过代码关闭JDialog,以便仍然会通知Window事件监听器?我尝试过将visible设置为false并处理,但似乎都没有。

Is there a way to close a JDialog through code such that the Window event listeners will still be notified? I've tried just setting visible to false and disposing, but neither seem to do it.

推荐答案

关闭窗口(带 dispose())并隐藏它(使用 setVisible(false))是不同的操作,并产生不同的事件 - 和从操作系统关闭它是另一个产生不同事件的不同操作。

Closing a window (with dispose()) and hiding it (with setVisible(false)) are different operations, and produce different events -- and closing it from the operating system is yet another different operation that produces yet a different event.

所有三个都会产生 windowDeactivated 告诉你窗口失去焦点,但是 dispose()然后会产生 windowClosed ,而从操作系统关闭将首先生成 windowClosing 。如果要以相同的方式处理这两种方法,可以将窗口设置为在关闭时处理:

All three will produce windowDeactivated to tell you the window's lost focus, but dispose() will then produce windowClosed, while closing from the OS will first produce windowClosing. If you want to handle both of these the same way, you can set the window to be disposed when closed:

window.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);

通常, setVisible(false)表示您可能希望再次使用该窗口,因此它不会发布任何窗口事件(除了 windowDeactivated )。如果要检测窗口的隐藏,则需要使用 ComponentListener ;

In general, setVisible(false) implies that you might want to use the window again, so it doesn't post any window events (apart from windowDeactivated). If you want to detect the hiding of a window, you need to use a ComponentListener;

window.addComponentListener(new ComponentAdapter() {
  @Override
  public void componentHidden(ComponentEvent e) {
    System.out.println("componentHidden()");
  }
})

注意,这几乎只适用于显式 setVisible()来电。如果你需要更普遍地检测隐藏,你可以使用 HierarchyListener ,但它可能比它的价值更麻烦。

Note though that this will pretty much only work for explicit setVisible() calls. If you need to detect hiding more generally, you can use a HierarchyListener, but it's probably more trouble than it's worth.

  window.addHierarchyListener(new HierarchyListener() {
    @Override
      public void hierarchyChanged(HierarchyEvent e) {
        System.out.println("valid: " + window.isValid());
        System.out.println("showing: " + window.isShowing());
      }
  });

请注意,当你处理一个窗口时,你会得到几个 HierarchyEvent s,首先用于隐藏然后用于失效,但是当你用 setVisible()隐藏它时它仍然有效,所以你不会得到失效。

Note that when you dispose a window you'll get a couple of HierarchyEvents, first for hiding and then for invalidation, but when you hide it with setVisible() it's still valid, so you won't get the invalidation.

这篇关于如何关闭JDialog并通知Window事件监听器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 02:26