GridLayout和Dialog:如何正确对齐项目

时间:2015-07-22 06:07:40

标签: java dialog swt grid-layout

我想在SWT中创建一个对话框。我的代码如下所示:

Shell dialog = new Shell(dialogShell, SWT.DIALOG_TRIM
            | SWT.APPLICATION_MODAL);

    dialog.setSize(800, 500);
    dialog.setBounds(10, 10, 200, 240);

    dialog.setText("Dummy dialog for stackoverflow");

    GridLayout gridLayout = new GridLayout(4, false);

    dialog.setLayout(gridLayout);

    Button btnSave = new Button(dialog, SWT.PUSH | SWT.CENTER);
    btnSave.setText("Save");
    btnSave.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, true, true, 1, 1));

    Button btnCancel = new Button(dialog, SWT.PUSH | SWT.CENTER);
    btnCancel.setText("Cancel");
    btnCancel.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, true, true, 1,
            1));

    Tree tree = new Tree(dialog, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL);

    GridData gridData = new GridData(GridData.FILL);
    gridData.horizontalSpan = 4;
    gridData.verticalSpan = 10;

    tree.setLayoutData(gridData);

    TreeItem item = new TreeItem(tree, 0);
    item.setText("Item 1");
    item = new TreeItem(item, 0);
    item.setText("Item 2");
    item = new TreeItem(item, 0);
    item.setText("Item 3");

    Label lblOne = new Label(dialog, SWT.NONE);
    lblOne.setText("Label One: ");

    Text textOne = new Text(dialog, SWT.SINGLE | SWT.BORDER);
    gridData = new GridData();
    gridData.horizontalAlignment = SWT.FILL;
    gridData.grabExcessHorizontalSpace = true;
    gridData.horizontalSpan = 3;
    textOne.setLayoutData(gridData);

    Label lblTwo = new Label(dialog, SWT.NONE);
    lblTwo.setText("Label Two: ");
    gridData = new GridData();
    gridData.verticalAlignment = SWT.TOP;
    lblTwo.setLayoutData(gridData);

    Text textTwo = new Text(dialog, SWT.SINGLE | SWT.BORDER);
    gridData = new GridData();
    gridData.horizontalAlignment = SWT.FILL;
    gridData.grabExcessHorizontalSpace = true;
    gridData.horizontalSpan = 3;
    textTwo.setLayoutData(gridData);

    dialog.pack();
    dialog.open();

结果如下: My SWT dialog

我无法达到以下“目标”:

  • 放大宽度对话框,使标题文字完全可读
  • 放大树,使其至少有八行高度
  • 设置文本控件的最小宽度,以便在尚未填充任何数据时不会缩小它们

感谢您的帮助!

2 个答案:

答案 0 :(得分:1)

使用GridData heightHintwidthHint值指定树和文本控件的建议高度和宽度。

例如:

gridData.widthHeight = 200;

答案 1 :(得分:0)

请尝试不要使用dialog.pack(),而是在开头提供任意大小的元素。然后你可以在某个事件处理程序中pack(),当你看到它适合时。另外,我暂时没有在SWT中做任何事情,但你尝试了minimumWidth属性吗?