How to dispose all children of Composite object?

不羁的心 提交于 2019-12-13 02:57:29

问题


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...


回答1:


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();
    }



回答2:


When disposing children (or anything in an array) I use the for next loop but go through from end to start, not start to end. (And get the length before the loop or it changes.)

int i = length-1;i>=0;i--

otherwise you delete every other one.



来源:https://stackoverflow.com/questions/10762415/how-to-dispose-all-children-of-composite-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!