如何处置Composite对象的所有子节点?

men*_*tis 1 java swt dispose composite

我有一个

Composite descComp
Run Code Online (Sandbox Code Playgroud)

有一些东西...基本上它是一个表单的容器,由多个标签,组合和按钮组成,所有标签都排成一行.我的表单不是有限的,我有一个按钮,可以添加一行额外的输入.然而,为了工作它接缝我必须处理我的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;
    }
......
}
Run Code Online (Sandbox Code Playgroud)

由于某些原因

descComp.getChildren()[i].dispose();
Run Code Online (Sandbox Code Playgroud)

不起作用,意味着它不会处理所有的孩子,这会导致插入新孩子的错误,从而破坏布局:/有趣的是,

descComp.getChildren()[i].setEnabled(false);
Run Code Online (Sandbox Code Playgroud)

当我解开它时,为所有孩子工作......

Mal*_*ith 15

我有一种预感,即在一个复合体上调用getChildren()会在你调用它时只返回未处理的子节点.所以descComp.getChildren()[i].dispose();当你的索引递增但是你的数组的大小正在减小时,调用就会搞砸了.你为什么不试试:

    for (Control control : descComp.getChildren()) {
        control.dispose();
    }
Run Code Online (Sandbox Code Playgroud)

这样,在开始处理每个子组件之前,您将获得组合中子组件的静态视图.

我还将代码切换为使用更好的J5 for-each语法.如果你被困在J1.4上,那么不幸的是你需要坚持for(;;)循环:

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