我正在研究一个java教程,看到在GridLayout中找到JButton的x/y索引的方法是遍历与布局关联的按钮b的二维数组,并检查是否
b[i][j] == buttonReference.
@Override
public void actionPerformed(ActionEvent ae) {
JButton bx = (JButton) ae.getSource();
for (int i = 0; i < 5; i++)
for (int j = 0; j < 5; j++)
if (b[i][j] == bx)
{
bx.setBackground(Color.RED);
}
}
Run Code Online (Sandbox Code Playgroud)
是否有更简单的方法来获取按钮的X/Y索引?
就像是:
JButton button = (JButton) ev.getSource();
int x = this.getContentPane().getComponentXIndex(button);
int y = this.getContentPane().getComponentYIndex(button);
Run Code Online (Sandbox Code Playgroud)
this是一个GameWindow实例,ev当用户按下按钮时触发ActionEvent.

在这种情况下,它应该得到:x == 2,y == 1
@ GameWindow.java:
package javaswingapplication;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.*;
import javax.swing.*;
public class …Run Code Online (Sandbox Code Playgroud)