2016-12-05 3 views
0

처음에는 자바로 초보자입니다. 스레드 제목에 언급 된 checkstyle 오류에 문제가 있습니다.ActionListener의 Checkystyle 문제 : 인스턴스 변수 'x'를 참조하면 'this'가 필요합니다. Java에서

는 비슷한 코드를 가진 고려 : 모든 물론 작업, 내가 버튼을 클릭 할 때이 방법 firstMethod(int, int)secondMethod(int, int)을 수행 속성 buttons에서 버튼의 onclick 이벤트를 만들었습니다 constructior에서

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 

    } 

    } 

을하지만, checkstyle이 오류를 throw합니다. 다른 개체 (ActionListener) 안에 들어 있기 때문에 어떤 이유로을 사용할 수 없습니다.

myClass 참조를 actionListener에 던지기위한 아이디어가 있으십니까?

+0

가능성이 있지만 checkstyle 오류가 게시 된 게시물에 언급되어 있지 않아 해결책을 찾지 못했을 수 있습니다. – t4dohx

답변

1

new ActionListener() { ... }; 블록은 실제로 새로운 익명 클래스를 만듭니다. 해당 블록 안에서 thisActionListener을 나타냅니다. 바깥 쪽 myClass 개체를 참조하려면 myClass.this을 사용하십시오.

+0

네, 그게 내가 찾고 있던 것입니다. 고마워요! :) – t4dohx

1

this 대신 myClass.this을 사용하여 외부 클래스 인스턴스를 참조하십시오. 수업에도 대문자를 사용하십시오 (MyClass이 아니라 myClass).

+0

예, 저는 간단한 예를 쓰는 동안 실수를했습니다. 대답 해줘서 고마워요. – t4dohx

관련 문제