Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 397
Rikkin Avatar asked Dec 05 '25 11:12

Rikkin


1 Answers

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.

like image 118
Andrew Thompson Avatar answered Dec 07 '25 23:12

Andrew Thompson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!