SWT:使用组件重新填充shell时布局中断

时间:2015-08-17 17:35:19

标签: java swt

我想定期清除shell中的所有内容并重新创建其中的组件。这是我尝试做的最小测试用例。首先,标签按照布局的规定并排放置,但是当updateThread在五秒钟后触发时,新创建的标签全部放在一起,完全忽略了布局。

package testpkg;

import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.*;

public class Test {
    public static void main(String[] args){
        Display display = new Display();
        Shell testShell = new Shell(display);
        FillLayout testLayout = new FillLayout();
        testShell.setLayout(testLayout);
        for(int i = 1; i<20; i++){
            Label label = new Label(testShell, SWT.BORDER);
            label.setText("HELLO"+i);
            label.pack();
        }
        testShell.open();
        Thread updateThread = new Thread(new Runnable(){
            public void run(){
                try {Thread.sleep(5000);} catch (Exception e){};
                display.getDefault().syncExec(new Runnable(){
                    public void run(){
                        for(Control control : testShell.getChildren()){
                            control.dispose();
                        }
                        for(int i = 1; i<20; i++){
                            Label label = new Label(testShell, SWT.BORDER);
                            label.setText("HELLO"+i);
                            label.pack();
                        }
                    }
                });
            }
        });
        updateThread.start();
        while (!testShell.isDisposed()) {
            if (!display.readAndDispatch())
                display.sleep();
        }
        display.dispose();
    }
}

我想定期更新(可变数量)标签,但是当我这样做时,布局会完全断开。

2 个答案:

答案 0 :(得分:2)

你可以把这一行放在for循环之后:

    testShell.layout(true);

所以最终的run()方法如下:

    public void run() {
      for (Control control : testShell.getChildren()) {
        control.dispose();
      }
      for (int i = 1; i < 20; i++) {
        Label label = new Label(testShell, SWT.BORDER);
        label.setText("HELLO"+i);
        label.pack();
      }
      testShell.layout(true);
    }

答案 1 :(得分:1)

我注意到调整窗口大小修复了一切。因此,如果我使窗口变大,然后缩小一秒钟,它就会起作用。