java-带有窗口焦点事件的意外行为

我正在用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,事件系统也可以正常工作.

我只是不知道为什么会这样.请帮忙.

系统规格:

>操作系统: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)

解决方法:

好吧,我看不出您的代码有多大错.所以我整理了一个快速演示,它似乎运行良好:

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 method called: windowGainedFocus.

并且当窗口最小化或单击鼠标时,除了打印JFrame之外,还会在屏幕上其他位置进行打印:

WindowFocusListener method called: windowLostFocus.

上一篇:java-全屏框架图像加载


下一篇:GUI编程详解