首页 > 解决方案 > Javafx 如何在 GridPane 中定位特定按钮

问题描述

我正在制作一个带有按钮的跳棋游戏。要杀死另一块,您必须将您的块沿对角线移动到另一块上方,但我不确定如何确保您的块移到另一块上方。

我解决这个问题的想法是获取第二个按钮的行和列,这是您的作品移动到的按钮,然后从每个行和列中减去 1,然后从该按钮获取文本以测试它是否是“黑色”或“红色”。

第一个和第二个 = 按钮

System.out.println((GridPane.getColumnIndex(second) + " vs " + (GridPane.getColumnIndex(second) - 1)));


    if (GridPane.getColumnIndex(second) > 0) {
        System.out.println("checking if a button has been jumped");
        GridPane.setRowIndex(second, (GridPane.getRowIndex(second) - 1));
        GridPane.setColumnIndex(second, (GridPane.getColumnIndex(second) - 1));
        System.out.println("this is a printing of the second button name for location " + (GridPane.getColumnIndex(second)) + " " + (GridPane.getRowIndex(second)) + " " + second.getText());

        if (second.getText().contains("black")) {
            System.out.println("it's a kill");
        } 
        else {
            System.out.println("no kill");
            GridPane.setRowIndex(second, (GridPane.getRowIndex(second) + 1));
            GridPane.setColumnIndex(second, (GridPane.getColumnIndex(second) + 1));
        }
    }

我可以将行和列更改为与另一部分的位置匹配的内容,但是当我从该按钮(第二个)获取文本时,它不会以“黑色”或“红色”的名称返回,而只是空白按钮的名称。
我的猜测是 GridPane 可能不会像这样工作,我只需要想出另一个解决方案,希望我不必将整个代码重做为二维数组或其他东西。

标签: javabuttonjavafxgridpane

解决方案


所以这是可能的,我从这篇文章中找到了答案。他只需要自己想办法找到具体的位置。 javafx GridPane 检索特定的单元格内容

private Node getNodeFromGridPane(GridPane gridPane, int col, int row) {
for (Node node : gridPane.getChildren()) {
    if (GridPane.getColumnIndex(node) == col && GridPane.getRowIndex(node) == row) {
        return node;
    }
}
return null;

}

虽然,出于我自己的目的,我仍然需要弄清楚如何能够测试节点是否包含“红色”或“黑色”,所以我只是添加了这个,现在一切正常!

private Boolean getNodeFromGridPane(GridPane gridPane, int col, int row) {

    for (Node node : gridPane.getChildren()) {
        if (GridPane.getColumnIndex(node) == col && GridPane.getRowIndex(node) == row) {

            if (node.toString().contains("black")) {

                System.out.println("The second button is black = " + node.toString().contains("black"));

                return true;
            }

            if (node.toString().contains("red")) {

                System.out.println("The second button is red = " + node.toString().contains("red"));

                return true;
            }

        }
    }
    return false;

}

推荐阅读