我问的原因是因为我收到了NullPointerException.
我现在这很容易,但是我是相当新的编程人员,发现这有点令人困惑.
可以这么说,我已经在一个类中初始化了一个对象,并想从另一个类访问该对象.
像现在一样,例如,我正在开发一个小型国际象棋游戏,在我的模型Game类中,我有一个Board实例,一个对象.董事会又拥有一系列的正方形.广场[][].
游戏有局,局有Square [] [].
现在,如果我想通过Board类型的对象面板(在游戏中)访问Square [] [].
我是否只声明具有相同名称和类型的变量,还是必须再次对其进行初始化?
董事会或董事会= new Board();
请注意,我已经在游戏类中初始化了棋盘,所以如果我再做一次,难道它们不是两个完全不同的棋盘对象吗?
引用“ board”的类:
public class View extends JFrame {
Board board;
JFrame gameWindow = new JFrame("Chess");
JPanel gamePanel = new JPanel();
JPanel[][] boardPanel = new JPanel[8][8];
JMenuBar gameMenu = new JMenuBar();
JButton newGame = new JButton("New game");
JButton pauseGame = new JButton("Pause");
JButton actionLog = new JButton("Action log");
View(){
gameWindow.setDefaultCloseOperation(EXIT_ON_CLOSE);
gameWindow.setSize(400, 400);
gameWindow.getContentPane().add(gamePanel);
gameWindow.setVisible(true);
gamePanel.setVisible(true);
gameMenu.add(newGame);
gameMenu.add(pauseGame);
gameMenu.add(actionLog);
for(JPanel[] row : boardPanel){
for(JPanel box : row){
gamePanel.add(box);
}
}
}
public void drawBoard(){
for(int y = 0; y < 8; y++){
for(int x = 0; x < 8; x++){
Box box = new Box();
box.setColour(board.getSquare(x, y).getColour());
box.setCol(x);
box.setRow(y);
box.repaint();
boardPanel[x][y].add(box);
}
}
}
}
class Box extends JComponent{
JPanel[][] boardPanel;
Board board;
Color boxColour;
int col, row;
public Box(){
repaint();
}
public void paint(Graphics drawBox){
drawBox.setColor(boxColour);
drawBox.drawRect(50*col, 50*row, 50, 50);
drawBox.fillRect(50*col, 50*row, 50, 50);
}
public void setColour(Color boxColour){
this.boxColour = boxColour;
}
public void setCol(int col){
this.col = col;
}
public void setRow(int row){
this.row = row;
}
}
…以及实例化“ board”的类:
public class Game {
@SuppressWarnings("unused")
public static void main(String[] args)
throws Throwable{
Board board = new Board();
View view = new View();
}
}
这里发生异常:
for(JPanel[] row : boardPanel){
for(JPanel box : row){
gamePanel.add(box);
}
}
解决方法:
Note, I have already initialized board in the class Game so if I do it again, won’t they be two totally different Board objects?
是的,您将拥有两个完全不同的实例.您已经有了基本的想法-程序中有对象的实例,现在必须使它们协同工作.
Now if I want to access the Square[][] through the object board (in Game) of type Board. Do I just declare a variable with the same name and type or do I have to initialize it again?
您可以通过2种方式使Game进入方块(根据您的观看方式,可能不止2种):
1让委员会提供对Square的访问权限(例如,板上的getter方法返回Squares数组),以便Game可以访问它们.然后,Board可以保存引用(具有自己的实例变量以将引用保存为正方形,或者可以每次都向Board请求引用).
2让棋盘提供执行Game想要在方块上做的事情的方法,即游戏要求棋盘对方块做某事,然后棋盘在方块上执行动作.