Search code examples
javaswingjpaneljscrollpanejcheckbox

JCheckBox components doesn't show on JPanel after re adding them


i am trying to make a JCheckBox list inside a JScrollPanel which is contained in a JDialogBox.Here is my code:

public void initTableChoices(DatabaseInit db){

    checkList = new ArrayList<>();

    //containerToScroll is the JPane, with boxLayout, that contains all the JCheckBoxes

    scrollPane = new JScrollPane(containerToScroll); 
    scrollPane.setSize((this.getSize().width/2),this.getSize().height - 10);
    scrollPane.setLocation((ExportDialogBox.getSize().width)/2, 0);

    ExportDialogBox.setSize(defaultSize);

    for(int i = 0; i < db.numberOfTables; i++){

        checkList.add(new JCheckBox(db.fileNames[i], false));
        containerToScroll.add(checkList.get(i));

    }

    ExportDialogBox.add(scrollPane, BorderLayout.CENTER);

    containerToScroll.revalidate();
    containerToScroll.repaint();
    containerToScroll.updateUI();
    scPane.revalidate();
    scPane.repaint(); 
    ExportDialogBox.revalidate();
    ExportDialogBox.repaint();
}

The above method, when is called for the first time, does what i want and has the following outcome:

The DialogBox after calling the method InitTableChoices for the first time

When i want to delete all the JCheckBoxes to create a few new ones, and later call the initTableChoices method to paint them,i first call the below method to remove them:

    public void deleteTableChoices(DatabaseInit db){


    checkList.removeAll(checkList);
    containerToScroll.removeAll();

    scPane.revalidate();
    scPane.repaint();
    containerToScroll.revalidate();
    containerToScroll.repaint();
    ExportDialogBox.revalidate();
    ExportDialogBox.repaint();

}

and then call the InitTableChoices method again,and i have the following outcome:

The DialogBox after calling the methods DeleteTableChoices and InitTableChoices after the first time

So it only shows the first JCheckBox i have on the list without showing the others.

Does anyone have any idea why this is happening?


Solution

  • In your initTableChoices method line

    scrollPane = new JScrollPane(containerToScroll);
    

    will add containerToScroll as a child of the scrollPane component.

    When you run initTableChoices a second time, containerToScroll will be assigned to a new JScrollPane instance but this new JScrollPane instance is not added into the component hierarchy. As a result, you are effectively removing containerToScroll from your component hierarchy.

    My suggestion would be to extract the loop that actually adds check boxes to containerToScroll into a new method, have initTableChoices call this method, and replace the second call of initTableChoices with a call to the new method.