WindowListener无法按预期工作 [英] WindowListener does not work as expected
问题描述
我希望我的GUI在出现JOptionPane时进行一些检查。
因为我找不到任何其他方式,我虽然每次应用程序窗口失去焦点时都可以执行这些操作(它只是检查字符串)。出于这个原因,我在我的JFrame上添加了以下代码:
I want my GUI to make some checks when a JOptionPane appears. Because I can't find any other way, I though I can do those each time the application window loses focus(its just checking a string). For that reason I added the following code on my JFrame:
appFrame.addWindowListener(new WindowAdapter() {
@Override
public void windowLostFocus(WindowEvent e) {
System.out.println("Focus Lost");
}
@Override
public void windowClosing(WindowEvent e) {
//some other stuff here that work
}
});
窗口关闭监听器工作正常。虽然当JFrame没有集中时没有任何反应。每次从JFrame切换到其他窗口时,不应该打印Focus Lost吗?此外,当显示JOptionPane时会触发此方法吗?
The window closing listener works fine. Although when the JFrame isn't focused nothing happens. Shouldn't "Focus Lost" be printed each time I switch from JFrame to some other window? Also, will this method be triggered when a JOptionPane is shown?
推荐答案
我不打算讨论你为什么这么做你正在做什么,但由于以下原因它没有按预期工作:
I'm not going to go into why you are doing what you are doing, but it is not working as you expect for the following reason:
WindowAdapter
是一个便利类,因此你可以创建一个监听器并为多种类型的事件注册。您只为一组事件注册了它,您还需要通过以下方式注册焦点事件: Window.addWindowFocusListener()
WindowAdapter adapter = new WindowAdapter() {
@Override
public void windowLostFocus(WindowEvent e) {
System.out.println("Focus Lost");
}
@Override
public void windowClosing(WindowEvent e) {
//some other stuff here that work
}
};
appFrame.addWindowListener(adapter);
appFrame.addWindowFocusListener(adapter);
这篇关于WindowListener无法按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!