1

我想知道 SWT Composite 对象的正常/常见做法是什么。

我发现,每当我添加一个 Composite(使用任何 UI 示例:TextBox 或 Button)时,在 Composite 中创建的 UI 都不会与 Composite 的起始边缘对齐。(您可以通过设置 Composite 的背景颜色来观察这一点)

在 TextBox UI 之前的 Composite 中有一些空间/填充。如果之前的 UI 不是在 Composite 中创建的,这会导致我正在创建的 GUI 表单出现错位。

我想知道使它们对齐的常见做法是什么?通过设置一些负填充来将 Composite 向后移动,以便其中的 UI 看起来像是对齐的?

下面的示例代码!

public static void main(String[] args) {
        Display display = new Display();
        Shell shell = new Shell(display);
        GridLayout layout = new GridLayout();
        layout.numColumns = 1;
        layout.makeColumnsEqualWidth = false;
        shell.setLayout(layout);

        Text t1 = new Text(shell, SWT.SINGLE | SWT.BORDER);
        t1.setText("Test box...");

        Composite c = new Composite(shell, SWT.NONE);
        // c.setBackground(new Color(shell.getDisplay(), 255,0,0));
        layout = new GridLayout();
        layout.numColumns = 2;
        layout.makeColumnsEqualWidth = true;
        c.setLayout(layout);

        Text t2 = new Text(c, SWT.SINGLE | SWT.BORDER);
        t2.setText("Test box within Composite... not aligned to the first textbox");

        Button b = new Button(c, SWT.PUSH);
        b.setText("Button 1");

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

2 回答 2

6

这将解决它:

public static void main(String[] args) {
    Display display = new Display();
    Shell shell = new Shell(display);
    shell.setLayout(new GridLayout(1, false));

    Text t1 = new Text(shell, SWT.SINGLE | SWT.BORDER);
    t1.setText("Test box...");

    Composite c = new Composite(shell, SWT.NONE);
    GridLayout layout = new GridLayout(2, true);

    layout.marginWidth = 0; // <-- HERE

    c.setLayout(layout);

    Text t2 = new Text(c, SWT.SINGLE | SWT.BORDER);
    t2.setText("Test box within Composite... not aligned to the first textbox");

    Button b = new Button(c, SWT.PUSH);
    b.setText("Button 1");

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

只需将marginWidthif设置GridLayout0

在此处输入图像描述

只是一个提示:您可以在GridLayout.

于 2012-10-17T08:10:11.610 回答
1

GridLayout具有与之关联的默认边距。我建议你阅读这篇文章

http://www.eclipse.org/articles/article.php?file=Article-Understanding-Layouts/index.html

于 2012-10-17T05:51:05.333 回答