对齐按钮中的SWT问题

时间:2018-08-13 09:48:34

标签: java eclipse swt

我写了一个小程序,其中有2个列表视图和一个用于选择和取消选择所选组合的按钮。问题是我无法将按钮对齐到列的中心。

public static void main(String[] args) {
    Display display = new Display();
    Shell shell = new Shell(display);
    shell.setLayout(new FillLayout());
    shell.setLayout(new GridLayout(3, true));
    GridData data = new GridData(GridData.FILL_BOTH);

    // Creating Label
    new Label(shell, SWT.NONE).setText("This is a plain Text");
    new Label(shell, SWT.NONE).setText("");
    new Label(shell, SWT.NONE).setText("This is a plain Text");
    // Create a single-selection list
    List single = new List(shell, SWT.BORDER | SWT.SINGLE | SWT.V_SCROLL);
    single.setLayoutData(data);

    // Add the items, one by one
    for (int i = 0, n = ITEMS.length; i < n; i++) {
        single.add(ITEMS[i]);
    }
    single.setSelection(0);

    //////////////////////////////////////////////////////
    // Button button1=new Button(shell, SWT.ARROW | SWT.RIGHT);

    Group first = new Group(shell, SWT.CENTER);
    first.setLayout(new RowLayout(SWT.VERTICAL));
    Button button1 = new Button(first, SWT.NONE);

    // GridData bdata = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING);

    Button button3 = new Button(first, SWT.PUSH);
    // button3.setLayoutData(bdata);
    button1.setText("Select    ");
    button3.setText("UnSelect");

    //////////////////////////////////////////////
    // Create a single-selection list
    List single2 = new List(shell, SWT.BORDER | SWT.SINGLE | SWT.V_SCROLL);
    single2.setLayoutData(data);
    single2.add("");

    single2.setSelection(0);

    shell.open();

    System.out.println(single.getItem(single.getSelectionIndex()));

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

实际输出:

enter image description here

预期输出:

enter image description here

1 个答案:

答案 0 :(得分:1)

不要尝试在多个控件上重用GridData,这会引起问题,因为布局信息存储在数据中。您必须为每个控件使用新的GridData。所以:

List single = new List(shell, SWT.BORDER | SWT.SINGLE | SWT.V_SCROLL);
single.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));


List single2 = new List(shell, SWT.BORDER | SWT.SINGLE | SWT.V_SCROLL);
single2.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));

要在GridData上将Group上设置的按钮居中:

Group first = new Group(shell, SWT.NONE);
first.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, true, true));

GridData请求水平和垂直居中。

要使按钮的宽度相同,请为组使用GridLayout并使用水平填充和抓取空间:

first.setLayout(new GridLayout());

Button button1 = new Button(first, SWT.NONE);
button1.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));

Button button3 = new Button(first, SWT.PUSH);
button3.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));

请注意,不再建议使用GridData.FILL_BOTH和类似的常量。