JavaFX - 控件数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23510648/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaFX - Array of Controls
提问by Mansueli
I want to create an Array of JavaFX controllers in order to be easier to work with them e.g. you could loop adding/setting elements in a GridPane.
我想创建一个 JavaFX 控制器数组,以便更轻松地使用它们,例如,您可以在 GridPane 中循环添加/设置元素。
But despite of the compiler/IDE not displaying any error this code below doesn't work:
但是尽管编译器/IDE 没有显示任何错误,但下面的代码不起作用:
public GridPane drawPane(){
GridPane grid = new GridPane();
Button[] btn = new Button[10];
grid.add(btn[0], 0,0);
return grid;
}
however this one does work:
但是这个确实有效:
public GridPane drawPane(){
GridPane grid = new GridPane();
Button btn = new Button();
grid.add(btn, 0,0);
return grid;
}
Am I instancing the controllers wrong? Why this code doesn't work with arrays ?
我实例化控制器错了吗?为什么此代码不适用于数组?
采纳答案by Patrick
Try this...
It will create an Array of Buttons and if you call your getGrid()
Method it iterates through this Array of Buttons and adds them to the GridPane.
试试这个...它会创建一个按钮数组,如果你调用你的getGrid()
方法,它会遍历这个按钮数组并将它们添加到 GridPane。
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
public class App extends Application {
private Button[] btns = new Button[10];
@Override
public void start(Stage primaryStage) {
initBtnsArray();
Group root = new Group();
root.getChildren().add(getGrid());
Scene scene = new Scene(root, 800, 600);
primaryStage.setTitle("Hello Controller-Array-World!");
primaryStage.setScene(scene);
primaryStage.show();
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
private Pane getGrid() {
int i = 0;
GridPane gridPane = new GridPane();
for(Button b : btns) {
// do something with your button
// maybe add an EventListener or something
gridPane.add(b, i*(i+(int)b.getWidth()), 0);
i++;
}
return gridPane;
}
private void initBtnsArray() {
for(int i = 0; i < btns.length; i++) {
btns[i] = new Button("Button-"+i);
}
}
}
Patrick
帕特里克
回答by Simulant
Your Array does not contain any Objects, so you will get a NullPointerException
. Fill the array with an initialized Object to get it working.
您的 Array 不包含任何对象,因此您将获得一个NullPointerException
. 用初始化的对象填充数组以使其工作。
public GridPane drawPane(){
GridPane grid = new GridPane();
Button[] btn = new Button[10];
btn[0] = new Button(); //add this line
grid.add(btn[0], 0,0);
return grid;
}