user3511875
user3511875

Reputation: 3

Getting the location of a mouse click event from a JButton

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?

Upvotes: 0

Views: 646

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285403

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.

Upvotes: 1

Related Questions