I’m creating an application with Swing, and I’ve got a problem. I want to handle the focusLost() and focusGained() events, but I think my code is buggy.
I’ve got the following, test code:
addWindowFocusListener(new WindowFocusListener() {
@Override
public void windowLostFocus(WindowEvent e) {
System.out.println("Lost!");
System.out.println(e.toString());
}
@Override
public void windowGainedFocus(WindowEvent e) {
System.out.println("Gained!");
System.out.println(e.toString());
}
});
And, when I activate the window, it seems that app handles 2 events at once:
Gained! java.awt.event.WindowEvent[WINDOW_GAINED_FOCUS,opposite=null,oldState=0,newState=0] on frame0 Lost! java.awt.event.WindowEvent[WINDOW_LOST_FOCUS,opposite=null,oldState=0,newState=0] on frame0
And, when I deactivate the window, the program prints nothing.
There’s also more interesting thing. When I open a new JFrame that belongs to my app, the event system works properly, even when I close this second Window.
I just don’t know why it is happening. Please help.
System specs:
- OS: Ubuntu 12.04 x86_64
- JVM: OpenJDK 7
m4tx@m4tx-EP35-DS4:~$ java -version Picked up _JAVA_OPTIONS: -Dawt.useSystemAAFontSettings=lcd java version "1.7.0_03" OpenJDK Runtime Environment (IcedTea7 2.1.1pre) (7~u3-2.1.1~pre1-1ubuntu3) OpenJDK 64-Bit Server VM (build 22.0-b10, mixed mode)
Well, I can’t see much wrong with your code; so I put together a quick demo, and it seems to be working fine:
On start up it prints:
and when the window is minimized, or the mouse is clicked somewhere else on screen besides the
JFrameis prints: