我需要获取Java中2d数组对象的索引

问题描述 投票:0回答:2

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

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'

java arrays javafx fxml
2个回答
0
投票

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

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

0
投票

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

  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;
   }
  }
© www.soinside.com 2019 - 2024. All rights reserved.