我需要在 Java 中获取二维数组对象的索引

I need to get the Index of a 2d array object in Java

我在 Java 中有 81 个二维数组按钮对象。 (JavaFX)(每个 9 个按钮 HBox

HBox[] hb = new HBox[9];
Button[][] btn = new Button[9][9];

// A for loop in another for loop to create 2d button arrays.
for (int i = 0; i < hb.length; i++) {
    hb[i] = new HBox();
    for (int j = 0; j < btn.length; j++) {
        btn[i][j] = new Button();
        btn[i][j].setText(Integer.toString(i) + "/" + Integer.toString(j));

        btn[i][j].setOnAction(event -> {
            System.out.println(event.getSource()); // In this line I want to print out the 2d array index values of a clicked button
        });

        hb[i].getChildren().add(btn[i][j]);
    }

    mvb.getChildren().add(hb[i]);
}

单击按钮时如何获取索引值?

例如,当我单击 btn[5][2] 时,我需要两个值 5 和 2,而不是 Button@277fbcb4[styleClass=button]'5/3'

最好的方法是创建一个扩展 Button 并包含这些值作为实例变量的自定义按钮 class。

public void addButtons(Pane parentPane) {
    HBox[] hb = new HBox[9];
    Button[][] btn = new Button[9][9];
    // A for loop in another for loop to create 2d button arrays.

    for (int i = 0; i < hb.length; i++) {
        hb[i] = new HBox();
        for (int j = 0; j < btn.length; j++) {
            btn[i][j] = new CustomButton(i, j);

            hb[i].getChildren().add(btn[i][j]);
        }

        parentPane.getChildren().add(hb[i]);
    }
}

class CustomButton extends Button {
    private int i;
    private int j;

    public CustomButton(int i, int j) {
        super();
        this.i = i;
        this.j = j;

        setText(i + "/" + j);

        setOnAction(event -> {
            System.out.println(getI() + " " + getJ());
        });
    }

    public int getI() {
        return i;
    }

    public int getJ() {
        return j;
    }
}

您可以为此使用用户数据方法getUserData/setUserData,在创建按钮时设置一个值,然后在单击按钮时访问它

  for (int i = 0; i < buttons.length; i++) {
    for (int j = 0; j < buttons[i].length; j++) {
      String data = String.format("%d:%d", i, j); //or some similar format
      Button button = new Button();
      //set up button...
      button.setUserData(data);
      buttons[i][j] = button;
   }
  }