SWT网格布局宽度

Jam*_*rpe 1 java swt

我正在尝试使用SWT创建一个简单的显示.到目前为止,我已成功显示数据库中的信息并使用RowLayout显示它,每行包含一个GridLayout.它看起来像这样:

在此输入图像描述

我真正想要的是扩展行以占据窗口的整个宽度.我该如何实现这一目标?

谢谢你的帮助!

Baz*_*Baz 7

通常的方法是使用GridData.这GridData告诉组件如何在其父节点内表现,例如如何在父节点上传播.

通过使用:

component.setLayoutData(new GridData(SWT.FILL, SWT.BEGINNING, true, false));
Run Code Online (Sandbox Code Playgroud)

告诉组件水平占用尽可能多的空间,但只能垂直占用必要的空间.

这是一个小例子,它应该按照你期望的方式运行:

public class StackOverflow
{
    public static void main(String[] args)
    {
        Display display = Display.getDefault();
        Shell shell = new Shell(display);

        /* GridLayout for the Shell to make things easier */
        shell.setLayout(new GridLayout(1, false));

        for(int i = 0; i < 5; i++)
        {
            createRow(shell, i);
        }

        shell.pack();
        shell.open();

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

    private static void createRow(Shell shell, int i)
    {
        /* GridLayout for the rows, two columns, equal column width */
        Composite row = new Composite(shell, SWT.NONE);
        row.setLayout(new GridLayout(2, true));

        /* Make each row expand horizontally but not vertically */
        row.setLayoutData(new GridData(SWT.FILL, SWT.BEGINNING, true, false));

        /* Create the content of the row, expand horizontally as well */
        Button first = new Button(row, SWT.PUSH);
        first.setText("FIRST " + i);
        first.setLayoutData(new GridData(SWT.FILL, SWT.BEGINNING, true, false));
        Button second = new Button(row, SWT.PUSH);
        second.setText("SECOND " + i);
        second.setLayoutData(new GridData(SWT.FILL, SWT.BEGINNING, true, false));
    }
}
Run Code Online (Sandbox Code Playgroud)

这是启动后的样子:

在此输入图像描述

调整大小后:

在此输入图像描述


作为旁注:如果您还没有阅读过,我建议您阅读Eclipse关于Layouts的教程.每个SWT开发人员都应该阅读它.