Search code examples
javafxindexoutofboundsexceptionscenebuildergluon

java fx vbox IndexOutOfBoundsException


Hey guys ım a newbie in java fx. My code changes labels design with the output of the rand func(1-16). Initially my code works without an error but I want my design auto-resizing responsive page, so I put my 16 label in a Vbox and it is now a responsive page. Problem starst here. I do not figure it out how to access a vbox by code. My code cant access labels and it give errors. When I put my labels out of vbox code is working again. I am wondering that the using vbox is okey ? Any suggestions would be appreciated.

int myrand = rand.nextInt(15)+1;
System.out.println(myrand + "blue");
root.getChildrenUnmodifiable().get(myrand).setStyle("-fx-background-color: blue"); 

However; the code points this line without any error sign on the row numbers.

root.getChildrenUnmodifiable().get(myrand).setStyle("-fx-background-color: blue");

Here is the full error log

Exception in thread "Timer-0" java.lang.IndexOutOfBoundsException: Index: 10, Size: 2
10blue
    at java.util.ArrayList.rangeCheck(ArrayList.java:653)
    at java.util.ArrayList.get(ArrayList.java:429)
    at com.sun.javafx.collections.ObservableListWrapper.get(ObservableListWrapper.java:89)
    at com.sun.javafx.collections.VetoableListDecorator.get(VetoableListDecorator.java:306)
    at javafx.collections.FXCollections$UnmodifiableObservableListImpl.get(FXCollections.java:936)
    at javafxapp.Lighproject$1.run(Lighproject.java:42)
    at java.util.TimerThread.mainLoop(Timer.java:555)
    at java.util.TimerThread.run(Timer.java:505) 

As you see it work with 1 loop and give the error. And this is my Hierarchy gluon scene builder Eror belongs top Vbox.


Solution

  • Try using int myrand = rand.nextInt(root.getChildren().size());.

    This is happening because your myrand variable is bigger than how many nodes are in the root group.