Search code examples
javajavafxintgridpane

JavaFX: GridPane, add() an integer as a label


Forgive the horribly generic GridPane name... it'll be changed as soon as I get some input on this.

I'm adding items to a GridPane, it'll take a button, it'll take a label... it'll take pretty much anything but this int.

        int[] listObjA = {312,23,241};

        GridPane gridpane = new GridPane();

        gridpane.add(new Label("Item Listing"), 1, 1);
        gridpane.add(listObjA[0], 1, 2);

Of course, leaving it like that tells me "int cannot be converted to Node". Any advice? I'm mystified by how difficult it's been simply to print a variable in Java. By the way, it must be a variable because I'll have a method changing it continuously, so simply changing it to new Label("312") isn't an option.


Solution

  • Java is a strongly typed language. You can't just pretend that an int is some kind of UI component.

    Create a label for each element of the array:

    int[] listObjA = {312,23,241};
    
    GridPane gridpane = new GridPane();
    
    gridpane.add(new Label("Item Listing"), 0, 0);
    
    for (int i = 0 ; i < listObjA.length; i++) {
        Label label = new Label(Integer.toString(listObjA[i]));
        gridpane.add(label, i+1, 0);
    }