Rikkin
Rikkin

Reputation: 509

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()?

Upvotes: 3

Views: 463

Answers (1)

Andrew Thompson
Andrew Thompson

Reputation: 168845

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.

Upvotes: 5

Related Questions