2013-05-14 4 views
0

를 액세스하기 위해이 세 가지 JButton 어떤 것인가가 클릭 된 경우 board 및 검사를 정의하는 다음과 같은 생성자 :어떻게 부울 배열 자바

Timer timer = new Timer(500, this); 

private boolean[][] board; 
private boolean isActive = true; 
private int height; 
private int width; 
private int multiplier = 40; 

JButton button1; 
JButton button2; 
JButton button3; 
public Board(boolean[][] board) { 
    this.board = board; 
    height = board.length; 
    width = board[0].length; 
    setBackground(Color.black); 
    button1 = new JButton("Stop"); 
    add(button1); 
    button1.addActionListener(new ActionListener() { 
     public void actionPerformed(ActionEvent e) { 
      isActive = !isActive; 
      button1.setText(isActive ? "Stop" : "Start"); 
     } 
    }); 
    button2 = new JButton("Random"); 
    add(button2); 
    button2.addActionListener(new ActionListener() { 
     public void actionPerformed(ActionEvent e) { 
      this.board = randomBoard(); 
     } 
    }); 
    button3 = new JButton("Clear"); 
    add(button3); 
    button3.addActionListener(new ActionListener() { 
     public void actionPerformed(ActionEvent e) { 
      this.board = clearBoard(); 
     } 
    }); 
} 

을하지만이 오류가 반환

Exception in thread "main" java.lang.Error: Unresolved compilation problems: 
    board cannot be resolved or is not a field 
    board cannot be resolved or is not a field 

왜 이런가요? 생성자에서 this.board에 어떻게 액세스합니까?

+0

여기서 '보드'를 정의 했습니까? –

답변

0

이 문제는

button2.addActionListener(new ActionListener() { 
    public void actionPerformed(ActionEvent e) { 
     this.board = randomBoard(); 
    } 
}); 

당신의 button2JButton 여기이며, 그것은 board 필드가 없습니다. this.board으로 액세스하지 마십시오. board에 액세스하는 다른 방법을 찾아보십시오.


할 수있는 신속하고 더러운 방법은 board 정적 수 있도록하는 것입니다,하지만 난 JButton 당신이 부모 (보드 클래스)를 지정하는 방법을 가지고 있음을 확신하고 board 필드에 액세스하는 방법.

The documentation for JButton을 잠시 살펴본 후 getParent 메서드를 발견했습니다. 나는 그것으로 시작할 것입니다.

4

익명의 내부 클래스에서 this.board에 액세스하려고했기 때문에 문제가 발생했습니다. board 필드가 정의되어 있지 않으므로 오류가 발생합니다. 예를 들어이 들어

:

button2.addActionListener(new ActionListener() { 
    public void actionPerformed(ActionEvent e) { 
     this.board = randomBoard(); 
    } 
}); 

this을 제거하거나 (더 명시 할 경우) Board.this.board 같은 것을 사용할 필요하거나 익명의 내부 클래스 안에 당신을 board 변수를 사용할 수있게하기 위해서 .

+0

이것은 실제 문제입니다. –

+1

정적이 아닌 내부 클래스 (심지어 익명의 클래스)에서 'this'를 제거하는 한 외부 클래스의 멤버 변수에 액세스 할 수 있습니다 (따라서 'board = randomBoard();'를 사용하십시오) –

+0

감사합니다 그걸 지적 @Huster 내가 그에 따라 편집 – Cemre

-1

다른 사람과 컴파일러에서 말한 것처럼 필드 (instance member)는 없지만 생성자가 종료되는 즉시 범위를 벗어나는 local variable 보드 만 있습니다.

0

이 작동합니다 :

Board.this.board = randomBoard(); 

문제는 보드 변수를 가지고 있지 않은 클래스의 ActionListener 관련 this입니다. 그러나 Board.this을 사용하면 Board 클래스의 보드 멤버를 의미합니다. 이것은 외부 클래스의 변수에 액세스하기 위해 중첩 클래스에 사용해야하는 구문입니다.