Search code examples
javajavafxfxmlgridpane

How to get column and row Index of each element in big GridPane(15x15)


I want to find the best solution for getting the column and row index of many elements in cells.

For example I have GridPane(15x15). Each cell has Button component. I want to get index of row and column when mouseClicked event is indicated. I know how to do this manually:

@FXML Button btn1;

btn1.setOnMouseClicked(e->{
            System.out.println("Row: "+ GridPane.getRowIndex(btn1));
            System.out.println("Column: "+ GridPane.getColumnIndex(btn1));
        });

But what to do this in my problem: 15x15 gridPane. It's not effective to declare every button and copying the same code for each component. Someone has a idea how to do this?

//============================================================

I have decided to prepare one method and link it to all button. It what I was looking for :).

Thanks for answer

    @FXML 
        private void testClicked(MouseEvent e){
            Node src = (Node)e.getSource();
            System.out.println("Row: "+ GridPane.getRowIndex(src));
            System.out.println("Column: "+ GridPane.getColumnIndex(src));
}

Solution

  • You could just loop through all elements of your GridPane and add your Eventhandler there.

        for (Node element : gridpane.getChildren()) {
            element.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() {
                @Override
                public void handle(MouseEvent event) {
                    System.out.println("Row: " + GridPane.getRowIndex(element));
                    System.out.println("Column: " + GridPane.getColumnIndex(element));
                }
            });
        }