Search code examples
javaswtdisposecomposite

How to dispose all children of Composite object?


I hava a

Composite descComp

with some stuff in it... basically it is a container for a form, consisting of number of labels, Combos and buttons, all aligned in a line. My form is not finite, I have a button that adds one extra line for extra input. However for that to work it seams I have to dispose old children of my descComp...

private void populateConstantMain(ContentData tariffConstantsOfType, Composite descComp,GridLayout descCompLayout, Boolean resize) {

    int arraySize;

    if (resize == false) {
        arraySize = tariffConstantsOfType.getQueryRowCount();
    } else {
        for (int i = 0 ; i < descComp.getChildren().length; i++) {
            System.out.println("Disposing: " + i + " " + descComp.getChildren()[i].toString());
            //descComp.getChildren()[i].setEnabled(false);
            descComp.getChildren()[i].dispose();
        }
        arraySize = tariffConstantsOfType.getQueryRowCount() + 1;
    }
......
}

For some reason

descComp.getChildren()[i].dispose();

does not work, meaning it wont dispose all children, that results in errors in inserting new children, therefore spoiling the layout :/ Interesting thing is that

descComp.getChildren()[i].setEnabled(false);

works, when I uncoment it, for all children...


Solution

  • I have a hunch that calling getChildren() on a composite returns you only the non-disposed children at the time you call it. So calling descComp.getChildren()[i].dispose(); is all messed up as your index is incrementing but your array is decreasing in size. Why don't you try:

        for (Control control : descComp.getChildren()) {
            control.dispose();
        }
    

    This way you get a static view of the children in the composite before you start disposing of each of them.

    I've also switched the code to use the nicer J5 for-each syntax. If you are stuck on J1.4 then unfortunately you'll need to stick to the for(;;) loop:

        Control[] children = descComp.getChildren();
        for (int i = 0 ; i < children.length; i++) {
            children[i].dispose();
        }