0

I've got something like this:

public void actionPerformed(ActionEvent a) {    
    ((JButton)a.getSource()).setBackground(Color.red);              
}

The color changes successfully, but I need to change a value in a int array according to the clicked button. How can I get the X and Y coordinates of the location where the mouse is clicked in a JButton array?

3
  • 2
    Use some kind of Map instead or use an Action which provides a single unit of work which can applied to buttons, menu items and key bindings Jun 24, 2014 at 1:50
  • won;t the simple getX() and getY() functions work? Jun 24, 2014 at 2:20
  • @user2837260: that will get the x and y location of the pressed JButton component, not the row and column index. Jun 24, 2014 at 2:29

1 Answer 1

1

One way: use a 2D array of JButton and iterate through the array via nested for loops to get the row and column value. For example...

int r = -1;
int c = -1;
for (int row = 0; row < buttons.length; row++) {
  for (int col = 0; col < buttons[row].length; col++) {
    if (buttons[row][col] == e.getSource()) {
      r = row;
      c = col;
    }
  }
}

Edit: other options (as mentioned by MadProgrammer), use a Map to map your JButton or its Action, to a Color.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.