Search code examples
javajavafxjavafx-8

For loop returns last item not iterating


I am trying to print an array of objects on a JavaFX panel which I created.

When I iterate like this:

Product[] arr = new Product[2];
arr[0] = new Food("Apple", 3.44, "fruit", false);
arr[1] = new Food("Orange", 3.14, "fruit", false);

for (int i= 0 ; i < arr.length; i++) {
    Label label = new Label(arr[i].name);
    label.setPadding(new Insets(5, 5, 5, 5));

    productGridPane.add(label, 0, 0);
}

it only returns the last item ( orange ) name.


Solution

  • @skidwiz is right. We are unaware of what productGridPane is. It is likely an instance of the JavaFX GridPane Class.

    If so, take a look at JavaFX 8 GridPane Docs

    In your call of the add() method you are adding each node (label) to the column-index of 0 and row-index of 0.

    This is just going to "stack" the nodes on top of each other. The last node you add will be the highest on this stack because it has the highest z-order.

    If you look at your second and third parameters, you'll see that both the second parameter (column index) and third parameter (row index) are set to 0.

    So, since you are looping the entire arr array and adding the label to the productGridPane, you keep "stacking" that value because it has the same coordinates as the other nodes in the GridPane, thus the last item in the array will be "highest on the stack", meaning it is the value you see. In this case the last value is the item with the name "Orange".

    Depending on how you want your GridPane to appear, the solution may vary.

    You likely want to change at least 1, but possibly (not likely) both parameters describing the column-index and row-index.

    Solution 1) Changing the column index to your loop counter variable i will add items along the columns (left to right):

    productGridPane.add(label, i, 0);
    

    Solution 2) Changing the row index to your loop counter variable i will add items along the rows (top to bottom):

    productGridPane.add(label, 0, i);
    

    Uncommon Solution 3) Changing both the column and row index to your loop counter variable i will add items by increasing both the column and row index. Highly unlikely you would do this. Consider the first two options as a solution.

    productGridPane.add(label, i, i);