How can I click a GridPane Cell and have it perform an action?

前端 未结 1 1189
小鲜肉
小鲜肉 2021-01-24 03:22

I\'m new to JavaFX (Java for that matter) and I want to be able to click a GridPane and have it display my room attributes in a side-panel(or to console at this point). I\'ve ma

相关标签:
1条回答
  • 2021-01-24 03:43

    Since you register the event handler at the GridPane, the source of the event is the GridPane itself. You did not set the row/column index for the GridPane and it wouldn't contain any useful information.

    In this case you need to get the node that was actually clicked from the MouseEvent:

    public void clickGrid(javafx.scene.input.MouseEvent event) {
        Node clickedNode = event.getPickResult().getIntersectedNode();
        if (clickedNode != gridmane) {
            // click on descendant node
            Integer colIndex = GridPane.getColumnIndex(clickedNode);
            Integer rowIndex = GridPane.getRowIndex(clickedNode);
            System.out.println("Mouse clicked cell: " + colIndex + " And: " + rowIndex);
        }
    }
    

    In this case the code works like this since the children of your GridPane don't have children of their own that could be the intersected node.

    If you want to add children that could have children of their own you need to go up through the node hierarchy until you find a child of the GridPane:

    if (clickedNode != gridmane) {
        // click on descendant node
        Node parent = clickedNode.getParent();
        while (parent != gridmane) {
            clickedNode = parent;
            parent = clickedNode.getParent();
        }
        Integer colIndex = GridPane.getColumnIndex(clickedNode);
        Integer rowIndex = GridPane.getRowIndex(clickedNode);
        System.out.println("Mouse clicked cell: " + colIndex + " And: " + rowIndex);
    }
    
    0 讨论(0)
提交回复
热议问题