Search code examples
javaswingfocuswindowlistener

Why only windowGainedFocus() does not work?


I have the following code, where I add a WindowListener to my JFrame, and I want to override the method 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");
         }        
    }); 

But it is not working, when I focus this frame it doesn't print "TEST". But when I override the method windowClosing it works:

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

What's the problem with windowGainedFocus()?


Solution

  • jd.addWindowListener(new WindowAdapter() {
         public void windowGainedFocus(WindowEvent windowEvent){
               System.out.println("TEST");
         }        
    }); 
    

    Should be:

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

    I knew there was a good reason I hated the adapter classes.. I would recommend using the listener rather than the adapter.