2013-05-14 35 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指定您是指董事会类的董事会成员。这是您需要使用嵌套类访问外部类变量的语法。