2016-12-05 30 views
0

起初我是Java的初學者。我在線程標題中提到的checkstyle錯誤有問題。ActionListener中的Checkystyle問題:引用實例變量'x'需要'this'。在Java中

考慮讓similiar代碼:

public class myClass { 
    JButton[] buttons; 

     public myClass() { 
     this.buttons = new JButton[2]; 
     //constructor code.... 

     this.buttons[0].addActionListener(new ActionListener() { 
        public void actionPerformed(ActionEvent e) {     
         firstMethod(0, 1); 
         secondMethod(5, 10); 
        } 
       }); 

     } 

     public void firstMethod(int x, int y) { 
     // do something 

    } 

     public void secondMethod(int x, int y) { 
     // do something 

    } 

    } 

在constructior我從屬性buttons,在點擊按鈕時,將執行方法firstMethod(int, int)secondMethod(int, int)創建onclick事件的按鈕,當然一切工作,但checkstyle會引發錯誤。 由於某些原因,我不能只使用this.firstMethod(),因爲我在另一個對象(ActionListener)內。

任何想法如何將myClass引用放入actionListener?

+0

可能,但checkstyle錯誤未在您發佈的帖子中提及,因此我沒有找到解決方案。 – t4dohx

回答

1

new ActionListener() { ... };塊實際上創建了一個新的匿名類。在該塊內部,this指的是ActionListener。要引用外部myClass對象,請使用myClass.this

+0

是的,這是我一直在尋找的東西。非常感謝! :) – t4dohx

1

使用myClass.this而不是普通的this來引用外部類實例。也可以使用大寫字母,因此MyClass,而不是myClass

+0

是的,我知道,編寫快速示例時我犯了一個錯誤。謝謝你的回答。 – t4dohx