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

时间:2013-11-23 20:31:15

标签: java arrays swing jbutton

下面的代码应该为特定类型(比如颜色)创建和对象实例我希望在网格中表示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

1 个答案:

答案 0 :(得分:4)

您只能将一个组件添加到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?如果它是四,那么你可能没问题(只要你使用每个按钮),但如果它更多,那么你就麻烦了。在您的6x6网格board = new JButton [6][6];中,看起来您正在尝试显示36个JButton,如果这是真的,那么您就遇到了问题。

但是,如果仍然卡住,请考虑创建并发布sscce