2013-05-14 73 views
0

我有下面的構造,如果任何三個JButton S的已經被點擊它定義了一個board和檢查:如何訪問布爾數組的Java

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

你在哪裏定義'board'? – 2013-05-14 15:36:14

回答

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(); 
    } 
}); 

爲了能夠使用board變量您的匿名內部類中,你需要取出this或使用類似Board.this.board(如果你想更清楚了) 。

+0

這是實際的問題。 – 2013-05-14 15:39:29

+1

從非靜態內部類(即使是匿名類),只要刪除'this'(只需使用'board = randomBoard();') – 2013-05-14 15:47:11

+0

就可以訪問外部類的成員變量感謝指出,@Heuster我編輯相應 – Cemre 2013-05-14 15:48:58

0

這應該工作:

Board.this.board = randomBoard(); 

的問題是this相關類的ActionListener沒有一個板變量。然而,Board.this指定您是指董事會類的董事會成員。這是您需要使用嵌套類訪問外部類變量的語法。