我正在使用Swing
创建一个应用程序,我遇到了问题。我想处理focusLost()
和focusGained()
事件,但我认为我的代码有问题。
我有以下测试代码:
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());
}
});
而且,当我激活窗口时,应用似乎会同时处理2个事件:
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
而且,当我停用窗口时,程序不会打印任何内容。
还有更有趣的事情。当我打开属于我的应用的新JFrame
时,事件系统正常,即使我关闭了第二个Window
。
我只是不知道为什么会这样。请帮忙。
系统规格:
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)
答案 0 :(得分:4)
好吧,我看不出你的代码有多大错;所以我整理了一个快速演示,它似乎工作正常:
import java.awt.event.WindowEvent;
import java.awt.event.WindowFocusListener;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class WindowEventDemo extends JFrame implements WindowFocusListener {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new WindowEventDemo("Window Event Demo").setVisible(true);
}
});
}
public WindowEventDemo(String name) {
super(name);
addWindowFocusListener(this);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 300);
}
@Override
public void windowGainedFocus(WindowEvent e) {
System.out.println("WindowFocusListener method called: windowGainedFocus.");
}
@Override
public void windowLostFocus(WindowEvent e) {
System.out.println("WindowFocusListener method called: windowLostFocus.");
}
}
在启动时打印:
WindowFocusListener方法调用:windowGainedFocus。
当窗口最小化,或者鼠标在屏幕上的其他位置点击除了JFrame
打印:
WindowFocusListener方法调用:windowLostFocus。