Hide JDialog window when the window lost focus

梦想与她 提交于 2019-12-24 07:29:03

问题


Hi I have only one JDialog box in my Java application.I want to make it invisible if it lost the focus. I've tried different method, But didn't able to trigger any of the window focus events. Here is my code:

  public void windowGainedFocus(WindowEvent e) {
    System.out.println("gained focus");
  }

  public void windowLostFocus(WindowEvent e) {
    System.out.println("lost focus");
  }

回答1:


Responding to Focus events can be really tricky. My experience has been that pretty much any time someone has attempted to do non-standard things with focus, they come to regret it eventually. Not least among the issues is that it's not really all that portable - a lot of X-Windows based displays use focus-follows-mouse, which can result in the focus being transferred away when you're not expecting it to, resulting in early dismissal of your dialog.

That said, Sun's official tutorial is here: http://java.sun.com/docs/books/tutorial/uiswing/misc/focus.html . If I remember right, you can attach a PropertyChangeListener to the KeyboardFocusManager, and that will be triggered for focus changes: http://java.sun.com/javase/6/docs/api/java/awt/KeyboardFocusManager.html#addPropertyChangeListener%28java.beans.PropertyChangeListener%29




回答2:


Use a WindowListener and handle the windowDeactivated event.



来源:https://stackoverflow.com/questions/3109148/hide-jdialog-window-when-the-window-lost-focus

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!