为什么只有 windowGainedFocus() 不起作用?

Rik*_*kin 3 java swing focus windowlistener

我有以下代码,其中我将 WindowListener 添加到 JFrame,并且我想重写该方法windowGainedFocus

    final JFrame jd = new JFrame();
    jd.setLocationRelativeTo(null);
    jd.setSize(300, 425);
    jd.setLayout(null);
    jd.setResizable(false);

    jd.addWindowListener(new WindowAdapter() {
         public void windowGainedFocus(WindowEvent windowEvent){
               System.out.println("TEST");
         }        
    }); 
Run Code Online (Sandbox Code Playgroud)

但它不起作用,当我聚焦此框架时,它不会打印“TEST”。但是当我重写该方法时windowClosing它会起作用:

    jd.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
               System.out.println("TEST");
         }        
    }); 
Run Code Online (Sandbox Code Playgroud)

有什么问题吗windowGainedFocus()

And*_*son 5

jd.addWindowListener(new WindowAdapter() {
     public void windowGainedFocus(WindowEvent windowEvent){
           System.out.println("TEST");
     }        
}); 
Run Code Online (Sandbox Code Playgroud)

应该:

jd.addWindowFocusListener(new WindowAdapter() {
     public void windowGainedFocus(WindowEvent windowEvent){
           System.out.println("TEST");
     }        
}); 
Run Code Online (Sandbox Code Playgroud)

知道我讨厌适配器类是有充分理由的。我建议使用侦听器而不是适配器。