0

I am trying to create a grid of buttons. This is my code to create the grid (which works), but if I want to access a single button later on how would I go about doing that?

    for(int i = 1; i<= row; i++){
        for( int p=1; p<= col; p++){
           boardPanel.add(new JButton());   
        }
    }

Many Thanks

A Clements;

4
  • What type is boardPanel ? Commented Dec 3, 2015 at 17:47
  • 1
    Hmm, any number of ways. You could save those buttons in an array and access them there. Or in an EvenListener, call getSource() on the Event to find the button that fired the event. It really boils down to how you want to access the button, i.e. what are your requirements? Commented Dec 3, 2015 at 17:49
  • boardPanel is a JPanel Commented Dec 3, 2015 at 17:50
  • Basically it's a minesweeper game. I see that with the actionlistener I need to at least call some form of button first. I just don't know what I could call from this e.g buttonName.addActionListener... Commented Dec 3, 2015 at 17:52

1 Answer 1

1

From your question title I'm assuming that you want to be able to access these buttons from a 2d array, but in your code the button is not in an array. If you did something like the following:

JButton[][] buttons = new JButton[row][col];
for(int i = 1; i<= row; i++){
    for( int p=1; p<= col; p++){
       buttons[i][p] = new JButton();
       boardPanel.add(buttons[i][p]);   
    }
}

Then you are maintaining a 2d array that contains references to the buttons in your JPanel. So now you can access the buttons from the array like this:

buttons[i][j];
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.