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

Jannes van Rüschen :

I have 81 2d array button objects in Java. (JavaFX) (9 buttons each 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]);
}

How do I get the index values when I click a button?

For example, when I click btn[5][2] I need the two values 5 and 2, not Button@277fbcb4[styleClass=button]'5/3'.

tgallei :

The best way would be to create a custom button class that extends Button and contains these values as instance variables.

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=19118&siteId=1