SWT网格布局宽度

时间:2013-03-28 14:13:14

标签: java swt

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

enter image description here

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

感谢您的帮助!

1 个答案:

答案 0 :(得分:7)

实现此目的的通常方法是使用GridData。此GridData告诉组件如何在其父级中执行操作,例如如何在父母身上传播。

使用:

component.setLayoutData(new GridData(SWT.FILL, SWT.BEGINNING, true, false));

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

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

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

这是启动后的样子:

enter image description here

并在调整大小后:

enter image description here


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

相关问题