Search code examples
javaarraysjavafxvboxhbox

Adding an ObservableList to HBox?


I have an array of JavaFX Labels to add to a HBox .However I understand that HBox.add method does not accept Collection types. Therefore , I add it through a loop instead. Unfortunately , Only one label is executed at a time and not all gets displayed . Any ideas why?

 for(int m=0;m<test.length;m++)
        {
            HBox hb = new HBox();

            System.out.println("Test.length's size : " + test.length);
            System.out.println("TeacherLabels's count : " + teacherlabels.size());
            hb.getChildren().addAll(teacherlabels.get(m),eachlecturertotstudents.get(m),subincome.get(m),teacherpayments.get(m));
            hb.setSpacing(10);
            VBox vb = new VBox();
            vb.getChildren().addAll(tuitionreport,totStudents,totalFees);
            vb.setSpacing(10);
            VBox vbez = new VBox();
            vbez.getChildren().addAll(vb,instructors,hboxtitle,hb,linez,allpaymenta,tuitionincomea);
            this.setScene(new Scene(vbez, 2000, 2000));
            this.show();
        }
  • I have four ObservableLists of the same size. OutofboundsException is not an issue here. test.length is the same size as all four lists.

  • This is a big project with a lot codes therefore it would be inappropriate for me to share all of it here. However you can checkout my github for the detailed example https://github.com/ariff20/UPSR

Only the Cikgu Suraya row of Labels is being added eventhough test.length is more than 1.

OUTPUT :

Only the Cikgu Suraya row of Labels is getting displayed

Test.length's size output :

enter image description here

It runs twice but only one row of label is being displayed.


Solution

  • Your for loop has the wrong scope, as you update the scene and show it inside the loop, this results in only showing the contents of the last iteration through the loop. As it is hard to guess what your intention is on how the output should look like do something like this:

    VBox vb = new VBox();
    vb.getChildren().addAll(tuitionreport,totStudents,totalFees);
    vb.setSpacing(10);
    
    VBox vbez = new VBox();
    vbez.getChildren().addAll(vb,instructors,hboxtitle);
    
    for(int m=0;m<test.length;m++) {
      HBox hb = new HBox();
    
      System.out.println("Test.length's size : " + test.length);
      System.out.println("TeacherLabels's count : " + teacherlabels.size());
      hb.getChildren().addAll(teacherlabels.get(m),eachlecturertotstudents.get(m),subincome.get(m),teacherpayments.get(m));
      hb.setSpacing(10);
    
    
      vbez.getChildren().add(hb);
    
    }
    
    vbez.getChildren().addAll(linez,allpaymenta,tuitionincomea);
    this.setScene(new Scene(vbez, 2000, 2000));
    this.show();
    

    In essence, only add one HBox to the VBox in each iteration.