Comment obtenir l'index X et Y de l'élément à l'intérieur de GridLayout?

J'étudie un tutoriel java et vu que la façon de trouver le x/y index d'un JButton à l'intérieur d'un GridLayout est de parcourir un tableau bidimensionnel de boutons b, qui est associé à la mise en page et de vérifier si

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);
        }
  }

Est-il un moyen plus facile d'obtenir le X/Y index sur un bouton?

Quelque chose comme:

JButton button = (JButton) ev.getSource();
int x = this.getContentPane().getComponentXIndex(button);
int y = this.getContentPane().getComponentYIndex(button);

this être un GameWindow instance et ev l'ActionEvent déclenché lorsque l'utilisateur appuie sur le bouton.

Comment obtenir l'index X et Y de l'élément à l'intérieur de GridLayout?

Dans ce cas, il doit obtenir: 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 GameWindow extends JFrame implements ActionListener
{
  JButton b[][] = new JButton[5][5];

  int v1[] = { 2, 5, 3, 7, 10 };
  int v2[] = { 3, 5, 6, 9, 12 };

  public GameWindow(String title)
  {
    super(title);

    setLayout(new GridLayout(5, 5));
    setDefaultCloseOperation(EXIT_ON_CLOSE );

    for (int i = 0; i < 5; i++)
      for (int j = 0; j < 5; j++)
      {
        b[i][j] = new JButton();
        b[i][j].addActionListener(this);
        add(b[i][j]);
      }
  }

  @Override
  public void actionPerformed(ActionEvent ae) {
    ((JButton)ae.getSource()).setBackground(Color.red);
  }
}

@JavaSwingApplication.java:

package javaswingapplication;

public class JavaSwingApplication {
  public static void main(String[] args) {
    GameWindow g = new GameWindow("Game");
    g.setVisible(true);
    g.setSize(500, 500);
  }
}

source d'informationauteur Răzvan Flavius Panda