SWT 从 Composite 中移除边距

SWT removing margin from Composite

当我在 ViewPart 中嵌入 Composite 控件时,在文本框和按钮(按钮是另一个 Composite 的一部分)之间添加了一个垂直的 margin/padding,如附图所示。

如何删除它?

public class View extends ViewPart {
    public static final String ID = "xyyx.view";

    public void createPartControl(Composite parent) {

        GridLayout layout = new GridLayout(1, false);
        parent.setLayout(layout);


        Text infoText = new Text(parent, SWT.BORDER);

        GridData gridDataInfo = new GridData();
        gridDataInfo.horizontalSpan = 1;
        gridDataInfo.grabExcessHorizontalSpace = true;
        gridDataInfo.horizontalAlignment = GridData.FILL;
        infoText.setLayoutData(gridDataInfo);       

        new NewComposite(parent, SWT.NONE);         

    }

    public class NewComposite extends Composite{

        public NewComposite(Composite parent, int style) {
            super(parent, style);           

            GridLayout layout = new GridLayout(1, false);
            setLayout(layout);      

            Button btn = new Button(parent, SWT.PUSH);
            btn.setText("Button");                  
        }

    }

    @Override
    public void setFocus() {
        // TODO Auto-generated method stub

    }

}

GridLayout#marginHeightGridLayout#marginWidth 可以设置为 0 以删除边距。

在您的情况下,设置 NewCompositeGridLayout#marginTop 可能就足够了。

JavaDoc of GridLayout#marginHeight

像这样:

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

    Composite first = new Composite(shell, SWT.NONE);
    Composite second = new Composite(shell, SWT.NONE);

    GridLayout firstLayout = new GridLayout(1, false);
    first.setLayout(firstLayout);

    GridLayout secondLayout = new GridLayout(1, false);
    secondLayout.marginHeight = 0;
    secondLayout.marginWidth = 0;
    second.setLayout(secondLayout);

    Button firstButton = new Button(first, SWT.PUSH);
    firstButton.setText("Margin");
    Button secondButton = new Button(second, SWT.PUSH);
    secondButton.setText("No Margin");

    first.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
    second.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
    firstButton.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
    secondButton.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));

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

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

    display.dispose();
}

看起来像这样:

如果你想进一步减少复合材料之间的间距,你也可以将 GridLayout#verticalSpacing 设置为 0:

GridLayout layout = new GridLayout(1, false);
layout.verticalSpacing = 0;
shell.setLayout(layout);

看起来像这样:

GridLayout#horizo​​ntalSpacingGridLayout#verticalSpacing 可以设置为 0 以删除列和行之间的间距。

在您的情况下,设置父组合的 GridLayout#verticalSpacing 应该可以解决问题。