简体   繁体   中英

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

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM