如何查看是否在 GridPane 中选择了特定的 CheckBox?

How do I see if a specific CheckBox is selected within a GridPane?

我创建了一个 10x10 的 CheckBoxes GridPane。我需要查看是否选择了特定的 CheckBox,但 GridPane 是由节点组成的。因此,如果我使用 another thread 中的函数访问特定节点,我将无法使用 isSelected,因为它是错误的类型。

我试过修改函数 getNodeByRowColumnIndex 或强制类型为 CheckBox 但我不确定如何。

@FXML
private GridPane Grid;

@FXML
public void initialize() {
    for (int x = 0; x < 10; x++) {
        for (int y = 0; y < 10; y++) {
            this.Grid.add(new CheckBox(), x, y);
            //Problem here
            boolean bln = getNodeByRowColumnIndex(y,x,this.Grid).isSelected();
        }
    }
}

getNodeByRowColumnIndexreturns一个Node。您需要将其转换为 CheckBox :

Node node = getNodeByRowColumnIndex(y,x,this.Grid);
    if(node instanceof CheckBox){
          boolean bln = ((CheckBox)node).isSelected();
          //todo use bln
}

旁注 1:不清楚您为什么要检查 isSelected 以查找刚刚添加的 CheckBox
旁注 2:根据 java naming conventions 使用 GridPane grid.

请参考下方源码

@FXML 私有 GridPane imageGridPane;

imageGridPane.addEventFilter(MouseEvent.MOUSE_CLICKED, new EventHandler() {

@Override
public void handle(MouseEvent e) {
    Node clickedNode = (Node) e.getTarget();
    if (clickedNode != imageGridPane) {
        Node parent = clickedNode.getParent();
        while (parent != imageGridPane) {
            clickedNode = parent;
            parent = clickedNode.getParent();
        }
        Integer colIndex = GridPane.getColumnIndex(clickedNode);
        Integer rowIndex = GridPane.getRowIndex(clickedNode);
        System.out.println("Mouse clicked cell: " + colIndex + " And: " + rowIndex);
        CheckBox itemNoCheckBox = (CheckBox) ((BorderPane) clickedNode).getTop();
        System.out.println("itemNo: " + itemNoCheckBox.getText());
        if (itemNoCheckBox.isSelected()) {
            System.out.println("Selected");
        } else {
            System.out.println("Deselected");
        }
    }
}

});