将JButton的多个实例添加到网格中的JFrame

下面的代码应该为我想要在网格中表示的特定类型(比如颜色)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 

您只能将一个组件添加到GUI一次。 如果将其添加到另一个组件,它将从上一个组件中删除。 你试图多次添加相同的JButton,这是行不通的。 相反,你将不得不创建更多的JButton。 考虑让您的按钮共享允许的操作。

如果您需要更多帮助,请考虑发布可编译代码(您当前的代码不是),这是一个小型可运行,可编译的程序,可以演示您的问题,换句话说,就是sscce 。


编辑
你评论:

但是,这些不算作JButton不同JButton的实例吗? (我不明白你的答案是什么意思……)

用数学的方式考虑一下……你在上面的代码中创建了多少JButton? 嗯,这很容易计算,恰好4:

 blueCell = new JButton("BLUE CELL"); redCell = new JButton("RED CELL"); greenCell = new JButton("GREEN CELL"); whiteCell = new JButton("WHITE CELL"); 

那么,现在问问自己,您尝试使用这四个JButton在GUI中显示多少JButton? 如果它是四,那么你可能没问题(只要你使用每个按钮),但如果它更多,那么你就麻烦了。 从你的6×6网格, board = new JButton [6][6]; ,看起来你正试图显示36个JButton,如果这是真的,你就会遇到问题。

但同样,如果仍然卡住,请考虑创建和发布sscce 。