行布局不适用于嵌套复合材料

Row layout does not work on nested composites

这就是我要使用 SWT 实现的目标:

为此,我尝试将 RowLayout 用于嵌套 Composite,以根据可用的 space 包装复合控件。以下代码完美运行:

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 调整大小时,组件换行到可用的水平方向 space):

当我这样做时,改为:

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

我遇到了以下行为。如果我调整 shell 的大小,标签不会换行。

在下图中,我们可以看到合成图扩展到了 shell 客户区之外,而不是包裹到第二行。调整 shell 的大小不会影响此错误行为。

我正在使用以下 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 的子代?

这是一个使用 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();
}

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

"trick"是将GridData设置为GridLayout元素的子元素。