0

I am currently coding a game board (using Java Swing). I wrote the following to display the board (rows go from A-I, and columns go from 1-12):

JPanel panel = new JPanel(new GridLayout(9,12,5,5));
panel.setBounds(10, 11, 800, 600);
frame.getContentPane().add(panel);

//board
for(int r = 0; r<9; r++)
{
    for(int c = 0; c<12; c++)
    {
        panel.add(new JButton((c+1) + numberList[r])).setBackground(Color.WHITE);
    }
}

The user is supposed to be able to buy certain slots on the board. For example, if User A buys A1 then that button, on the board, is supposed to turn RED and if User B buys A2 then that button is supposed to turn GREEN (User will have certain buttons that have the available tile coordinates and after the button is clicked, the tiles on the board are supposed to change color and stay). Since I created all the buttons in a loop and I didn't name each of them, can I still accomplish this? I don't want to create 108 buttons one by one.

I know I shouldn't have used buttons for the board, I am going to change it soon. I am going to use Graphics G to use rectangles. However, I want to figure out my plan first.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
ZeldaX
  • 49
  • 9
  • 1) See also [Making a robust, resizable Swing Chess GUI](http://stackoverflow.com/q/21142686/418556). 2) *"I know I shouldn't have used buttons for the board"* Why not? It seems the perfect choice for a grid based board game like chess, battleship, minefield.. – Andrew Thompson May 23 '17 at 18:43
  • See also [*How to get X and Y index of element inside GridLayout?*](https://stackoverflow.com/a/7706684/230513). – trashgod May 23 '17 at 19:57

1 Answers1

0

There's no need to create them one by one, just keep a reference to each button in an array so you can access it later:

public static void main(String[] args)
{
    JFrame frame = new JFrame();

    JPanel panel = new JPanel(new GridLayout(9, 12, 5, 5));
    panel.setBounds(10, 11, 800, 600);
    frame.getContentPane().add(panel);

    JButton[][] buttons = new JButton[9][12];
    char [] numberList = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'};

    // board
    for (int r = 0; r < 9; r++)
    {
        for (int c = 0; c < 12; c++)
        {
            buttons[r][c] = new JButton("" + (c + 1) + numberList[r]);
            buttons[r][c].setBackground(Color.WHITE);
            panel.add(buttons[r][c]);
        }

    }

    frame.setContentPane(panel);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
    frame.setVisible(true);
}

And next time please include a complete code sample!

Amber
  • 2,413
  • 1
  • 15
  • 20