2015-04-01 47 views
3

我有下面的代碼,在那裏我一個的WindowListener添加到我的JFrame,我想覆蓋的方法windowGainedFocus爲什麼只有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"); 
     }   
    }); 

但它不工作,當我關注這個框架不打印「測試」。 但是,當我覆蓋的方法windowClosing它的工作原理:

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

什麼是與windowGainedFocus()問題?

+1

變化'公共無效windowGainedFocus(..''到@覆蓋公共無效windowGainedFocus(..' – 2015-04-01 18:55:57

+0

它仍然不工作:/方法的windowClosing工作沒有了'@ Override' – Rikkin 2015-04-01 19:01:01

+0

是它編譯 – Rikkin 2015-04-01 19:04:28

回答

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

應該是:

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

知道有一個很好的理由我討厭適配器類..我會建議使用監聽器,而不是適配器。

相關問題