非預設間距和邊距

通過利用 GridLayout 例項中的一些成員變數,我們可以更改佈局周圍的邊距和單元格之間的間距。在此示例中,我們設定以下內容:

  1. verticalSpacing = 0 - 將單元格之間的垂直間距設定為 0px
  2. horizontalSpacing = 20 - 將單元格之間的水平間距設定為 20px
  3. marginWidth = 10 - 將佈局的左右邊距設定為 10px

注意:我們不修改 marginHeight,因此它保持預設的 5px

public class GridLayoutExample {

    private final Display display;
    private final Shell shell;

    public GridLayoutExample() {
        display = new Display();
        shell = new Shell(display);

        // Create a layout with two columns of equal width
        final GridLayout shellLayout = new GridLayout(2, true);
        shellLayout.verticalSpacing = 0; // Vertical spacing between cells
        shellLayout.horizontalSpacing = 20; // Horizontal spacing between cells
        shellLayout.marginWidth = 10; // Horizontal margin around the layout
        shell.setLayout(shellLayout);

        final Button buttonA = new Button(shell, SWT.PUSH);
        buttonA.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
        buttonA.setText("Button A");

        final Button buttonB = new Button(shell, SWT.PUSH);
        buttonB.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
        buttonB.setText("Button B");

        final Button buttonC = new Button(shell, SWT.PUSH);
        buttonC.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
        buttonC.setText("Button C");

        final Button buttonD = new Button(shell, SWT.PUSH);
        buttonD.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
        buttonD.setText("Button D");
    }

    public void run() {
        shell.pack();
        shell.open();

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

    public static void main(final String... args) {
        new GridLayoutExample().run();
    }

}

結果是:

StackOverflow 文件