views:

33

answers:

2

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  A: 

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

Curtis
I'll tell more about my problem.I'm using a linux system. I've a JDialog box with jEditPane. This window have fixed size. When the focus is lost I want to make this window minimized to tray.
Joe
The WindowListeners suggested below seems likely to work.My gut feeling is that this will end up being a bit annoying to a good number of users. Have you considered just putting it in a JWindow with fixed size, and then letting the user just minimize it when they don't want it?
Curtis
A: 

Use a WindowListener and handle the windowDeactivated event.

camickr