-1

I have multiple Hboxes in JavaFX like this:

HBox hb = new HBox(10);
HBox hb2 = new HBox(10);
HBox hb3 = new HBox(10);
HBox hb4 = new HBox(10);
etc..

I want to put the hbox creation in a loop, but I am not really sure how to do that.

I've tried it like this:

HBox[] array = new HBox[4];
for (int i = 0; i < 3; i++){
    array[i] = new HBox(10);
}

But I'm getting this error when I try to add some content to the hboxes:

Exception in Application start method
Exception in thread "main" java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:767)
Caused by: java.lang.RuntimeException: Exception in Application start method
    at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:917)
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$155(LauncherImpl.java:182)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.NullPointerException
    at OptieScherm.start(OptieScherm.java:74)
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$162(LauncherImpl.java:863)
    at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$175(PlatformImpl.java:326)
    at com.sun.javafx.application.PlatformImpl.lambda$null$173(PlatformImpl.java:295)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.application.PlatformImpl.lambda$runLater$174(PlatformImpl.java:294)
    at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
    at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
    ... 1 more`

Thanks,

Wouter
  • 25
  • 5

2 Answers2

0

Like this:

ArrayList<HBox> boxes = new ArrayList<HBox>();
for(int i = 0;i<10;i++){
    Hbox h = new HBox(10);
    boxes.add(h);
}

Then just access them out of the list

Jamal H
  • 934
  • 7
  • 23
-2

Yes, you can by doing the following:

first: find your element taht you want to add the HBoxes to it.

Second create a global HBox like:

HBox hb = null;

Then loop and assign to the variable the HBox instance Then assign the created HBox to the root elemnt:

for(int i =0: i < your_number_of_HBoxes; i++){
   hb = HBox hb = new HBox(10);
   root.getChildren().add(rect);
}
Fady Saad
  • 1,169
  • 8
  • 13