JavaFX - Array of Controls


Question

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.

But despite of the compiler/IDE not displaying any error this code below doesn't work:

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 ?

1
1
5/7/2014 8:33:55 AM

Accepted Answer

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.

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

5
5/7/2014 8:39:19 AM

Your Array does not contain any Objects, so you will get a NullPointerException. Fill the array with an initialized Object to get it working.

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;
}

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon