java—如何在javafx中从网格返回按钮?

y1aodyip  于 2021-06-27  发布在  Java
关注(0)|答案(1)|浏览(355)

我正在尝试编写一个函数,它将从gridpane的所需索引返回一个按钮。我没有得到想要的结果。这是我的密码

public Node getNodeFromGridPane(GridPane gridPane)
{
    int[] cord = new int[2];
    cord=getCord(count);
    int row=cord[0];
    int col=cord[1];
    System.out.println("Getting Label");
      for (Node node : gridPane.getChildren())
      {
        if (GridPane.getColumnIndex(node) == col && GridPane.getRowIndex(node) == row)
        {
            System.out.println("AAA");
          return node;
        }
      }
      return null;
}

还有别的办法吗?

wb1gzix0

wb1gzix01#

你提供的信息有限。为什么你没有得到想要的结果?
我用java编写了以下代码,用几个标签和一个按钮填充gridpane。

@Override
public void start(Stage primaryStage) throws Exception{
    primaryStage.setTitle("Hello World");
    GridPane gridPane = new GridPane();
    primaryStage.setScene(new Scene(gridPane, 300, 275));

    gridPane.setHgap(15);            // Improve readibility, can ignore
    gridPane.setVgap(15);            // Improve readibility, can ignore

    gridPane.add(new Label("c0r0"), 0,0);           // Add label on column 0, row 0
    gridPane.add(new Label("c0r1"), 0,1);           // Add label on column 0, row 1
    gridPane.add(new Label("c1r0"), 1, 0);          // Add label on column 1, row 0
    gridPane.add(new Label("c1r1"), 1,1);           // Add label on column 1, row 1
    gridPane.add(new Button("Button Test"), 2, 2);  // Add button on column 2, row 2

    int c, r;                                       // Column and row variable

    c=0; r=0;  // We want the Node on 0,0       
    System.out.println(((Label)findNodeByRowAndColumn(gridPane, c, r)).getText());
    c=0; r=1;  // We want the Node on 0,1
    System.out.println(((Label)findNodeByRowAndColumn(gridPane, c, r)).getText());
    c=1; r=0;  // We want the Node on 1,0
    System.out.println(((Label)findNodeByRowAndColumn(gridPane, c, r)).getText());
    c=1; r=1;  // We want the Node on 1,1
    System.out.println(((Label)findNodeByRowAndColumn(gridPane, c, r)).getText());
    c=2; r=2;  // We want the node on 2,2
    System.out.println(((Button)findNodeByRowAndColumn(gridPane, c, r)).getText());

    primaryStage.show();
}

public static Node findNodeByRowAndColumn(GridPane gridPane, int c, int r) {
    for(Node node : gridPane.getChildren()) {
        if (GridPane.getColumnIndex(node) == c && GridPane.getRowIndex(node) == r)
        {
            return node;
        }
    }
    return null;
}

gridpane的外观:

程序输出为:

c0r0 
c0r1
c1r0
c1r1
Button Test

根据传递的列和行索引,此输出是正确的。

相关问题