行布局不适用于嵌套合成

时间:2017-04-09 09:03:25

标签: java swt

这是我想要实现的,使用SWT:

The goal

为此,我尝试使用RowLayout作为嵌套Composite,根据可用空间包装复合控件。以下代码完美无缺:

public class RowLayoutExample {

    public static void main(String[] args) {
        Display display = new Display();
        Shell shell = new Shell(display);
        shell.setText("SWT RowLayout test");

        shell.setLayout(new RowLayout(SWT.HORIZONTAL));

        for (int i = 0; i < 10; i++) {
            new Label(shell, SWT.NONE).setText("Label " + i);
        }

        shell.setSize(400, 250);
        shell.open();
        while (!shell.isDisposed()) {
            if (!display.readAndDispatch())
                display.sleep();
        }
        display.dispose();
    }
}

显示(请注意下一行上最后一个标签的精美包装 - 同样,在shell调整大小时,组件包装到可用的水平空间中):

Row layout on shell works!

当我这样做时,改为:

public class RowLayoutExample {

    public static void main(String[] args) {
        Display display = new Display();
        Shell shell = new Shell(display);
        shell.setText("SWT RowLayout test");

        shell.setLayout(new RowLayout(SWT.HORIZONTAL));
        Composite comp = new Composite(shell, SWT.NONE);
        comp.setLayout(new RowLayout(SWT.HORIZONTAL));

        for (int i = 0; i < 10; i++) {
            new Label(comp, SWT.NONE).setText("Label " + i);
        }

        shell.setSize(400, 250);
        shell.open();
        while (!shell.isDisposed()) {
            if (!display.readAndDispatch())
                display.sleep();
        }
        display.dispose();
    }
}

我有以下行为。如果我调整外壳的大小,标签不会包装成多行。

Row layout no longer works on shell control

在下图中,我们可以看到复合扩展出shell客户端区域,而不是包装到第二行。调整shell大小不会影响这种错误行为。

enter image description here

我使用的是以下SWT版本:

<dependency>
    <groupId>org.eclipse.swt</groupId>
    <artifactId>org.eclipse.swt.cocoa.macosx.x86_64</artifactId>
    <version>4.3</version>
</dependency>

那么,为什么第二种情况不起作用?此外,是否可以将GridLayout用于shell,但RowLayout用于此shell的子级?

1 个答案:

答案 0 :(得分:4)

以下是使用GridLayout作为Shell布局的示例:

public static void main(String[] args) {
    Display display = new Display();
    Shell shell = new Shell(display);
    shell.setText("SWT RowLayout test");

    shell.setLayout(new GridLayout());
    Composite comp = new Composite(shell, SWT.NONE);
    comp.setLayout(new RowLayout(SWT.HORIZONTAL));
    comp.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));

    for (int i = 0; i < 10; i++) {
        new Label(comp, SWT.NONE).setText("Label " + i);
    }

    shell.setSize(400, 250);
    shell.open();

    while (!shell.isDisposed()) {
        if (!display.readAndDispatch())
            display.sleep();
    }
    display.dispose();
}

产生与第一个例子相同的结果。

&#34;技巧&#34;是使用GridDataGridLayout设置为元素的子元素。