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

标签 java arrays javafx fxml

我有 81 个 Java 二维数组按钮对象。 (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'.

最佳答案

最好的方法是创建一个自定义按钮类,该类扩展 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;
    }
}

关于java - 我需要在Java中获取二维数组对象的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60487764/

相关文章:

java - Truncate 不会物理释放磁盘空间

javascript - 在 React JS 中导入数组函数后无法检索我的电影数据

java - 将菜单调整为图层大小

css - JavaFX:获取TextArea的行高

java - 我可以将字典指定为另一个类实例的属性吗?

java - 如果 OOP 为空,如何设置位置

java - 为什么 Google 应用引擎中的请求和安全请求配额增加了?

java - 如何有效地随机重新插入数组中的元素

c++ - 什么 C++ 代码编译成 x86 REP 指令?

javafx - 如何使用 Set 作为 TableView 的基础