[英]How can we return a Button from a grid in Javafx?
I am trying to write a function that will return a button from the desired index of a GridPane.我正在尝试编写一个 function ,它将从所需的 GridPane 索引返回一个按钮。 I am not getting the desired results.
我没有得到想要的结果。 Here is my code
这是我的代码
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;
}
Is there any other way to do this?有没有其他方法可以做到这一点?
You are providing limited information.您提供的信息有限。 Why are you not getting the desired results?
为什么你没有得到想要的结果?
I wrote the following code in Java, filling the gridpane with a few labels and one button.我在 Java 中编写了以下代码,用几个标签和一个按钮填充网格窗格。
@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;
}
What the GridPane looks like: GridPane 的样子:
The programs output is:程序 output 是:
c0r0
c0r1
c1r0
c1r1
Button Test
This output is correct, based on the column and row indices which were passed.根据传递的列和行索引,此 output 是正确的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.