Search code examples
javaarraysjavafxfxml

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


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'.


Solution

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