【发布时间】:2013-12-08 16:05:04
【问题描述】:
下面的代码应该为我想在网格中表示的特定类型(比如颜色)JButton 创建和对象实例。当我遍历 for 循环以将按钮添加到 jframe 时,它什么也没添加。但是,如果我添加一个实例变量,它将添加它。有人有想法吗?
public class Grid {
protected JButton [][] board;
private JButton player;
private JButton openCell;
private JButton wall;
private JButton closedCell;
public Grid(String [] args) { // args unused
// Instantiation
board = new JButton [6][6];
layout = new String [6][6];
blueCell = new JButton("BLUE CELL");
redCell = new JButton("RED CELL");
greenCell = new JButton("GREEN CELL");
whiteCell = new JButton("WHITE CELL");
// Configuration (add actions later)
// Decoration
blueCell.setBackground(Color.blue);
redCell.setBackground(Color.red);
greenCell.setBackground(Color.green);
whiteCell.setBackground(Color.white);
for (int rows = 0; rows < 6; rows++) {
for (int cols = 0; cols < 6; cols++) {
if ((layout[rows][cols]).equals('*')) {
board[rows][cols] = blueCell;
}
else if ((layout[rows][cols]).equals('.')) {
board[rows][cols] = redCell;
}
else if ((layout[rows][cols]).equals('x')) {
board[rows][cols] = greenCell;
}
else {
board[rows][cols] = whiteCell;
}
}
}
JFrame game = new JFrame();
game.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
game.setLayout(new GridLayout (6, 6));
game.setSize(500, 500);
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board.length; j++) {
if ((board[i][j]).equals(blueCell)) {
grid.add(blueCell);
}
else if ((board[i][j]).equals(redCell)) {
grid.add(redCell);
}
else if ((board[i][j]).equals(greenCell)) {
grid.add(greenCell);
}
else {
grid.add(whiteCell);
}
}
}
grid.setVisible(true);
} // end of constructor
} // end of Grid class
【问题讨论】:
-
请不要删除您的代码和问题,因为它会使原始问题的所有答案都过时,这意味着我浪费了时间来帮助您。请恢复您之前的代码,如果您希望添加新代码作为问题的编辑,因为我已经编辑了我的答案。
-
我已经回滚了你的问题。如果您想编辑此内容并将信息添加到底部,请执行此操作。或者,如果您的新想法完全不同,请考虑在此网站上提出一个全新的问题。