简体   繁体   English

从JButton获取鼠标单击事件的位置

[英]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. 颜色更改成功,但是我需要根据单击的按钮更改int数组中的值。 How can I get the X and Y coordinates of the location where the mouse is clicked in a JButton array? 如何获取JButton数组中单击鼠标的位置的X和Y坐标?

One way: use a 2D array of JButton and iterate through the array via nested for loops to get the row and column value. 一种方法:使用JButton的2D数组,并通过嵌套的for循环遍历该数组以获取行和列的值。 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. 编辑:其他选项(如MadProgrammer所述),使用Map将JButton或其Action映射为Color。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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