开发者

How to use an array containing JButtons within a for loop to draw a grid?

开发者 https://www.devze.com 2023-03-04 08:08 出处:网络
public void loadBoard() { for(int row = 0; row < 5; row++) 开发者_开发问答for(int col = 0; col < 5; col++)
public void loadBoard()
{
for(int row = 0; row < 5; row++)
 开发者_开发问答    for(int col = 0; col < 5; col++)
    {
        buttons[row][col] = new JButton("");
            buttons[row][col].addActionListener(this);
            this.add(buttons[row][col]);
    }
}


Use a GridLayout, or any other Layout for that matter to lay them out.

JPanel panel = new JPanel();
panel.setLayout(new GridLayout(rows, cols));

for (int row = 0; row < rows; ++row)
{
    for (int col = 0; col < cols; ++col)
    {
        panel.add(buttons[row][col]);
    }
}

this.add(panel);
0

精彩评论

暂无评论...
验证码 换一张
取 消