组件不会在带有 GridLayout 的 SWT 中调整大小

Components won't resize in SWT with a GridLayout

几天前我发现了 SWT,并决定将我的插件界面从 Swing 切换到 SWT。我可以根据需要放置组件,但是当我调整 window 大小时,组件根本没有调整大小。此外,当我用一个大字符串填充一个小文本(文本区域)时,我找不到调整它大小的方法...... 下面的代码是定义布局和组件的代码,我想有人会发现我的错误在哪里。

P.S :我在网上看到一些教程在声明 shell 之前先声明 Display 对象。当我这样做时,我遇到了 InvalidThreadAccess 异常。

    Shell shell = new Shell();
    GridLayout gridLayout = new GridLayout(2, false);
    shell.setLayout(gridLayout);

    tree = new Tree(shell, SWT.CHECK | SWT.BORDER);

    Text tips = new Text(shell, SWT.READ_ONLY);
    tips.setText("Pick the files and nodes to refactor : ");
    oldFileViewer = new Text(shell, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
    oldFileViewer.setText("here is the old file viewer\t\t\t\t\t\t\t\t\t\n\n\n\n\n\n");
    oldFileViewer.setSize(400, 400);

    newFileViewer = new Text(shell, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
    newFileViewer.setText("and here is the new file viewer\t\t\t\t\t\t\t\t\t\n\n\n\n\n\n");
    newFileViewer.setSize(400, 400);
    Button ok = new Button(shell, SWT.PUSH);

感谢阅读。

不要尝试将布局与 setSizesetBounds 混合使用,否则不会起作用。

使用布局,您的代码可能如下所示:

GridLayout gridLayout = new GridLayout(2, false);
shell.setLayout(gridLayout);

tree = new Tree(shell, SWT.CHECK | SWT.BORDER);
GridData data = new GridData(SWT.FILL, SWT.FILL, true, true);
tree.setLayoutData(data);

Text tips = new Text(shell, SWT.READ_ONLY);
tips.setText("Pick the files and nodes to refactor : ");
tips.setLayoutData(new GridData(SWT.BEGINNING, SWT.CENTER, false, false));

oldFileViewer = new Text(shell, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
oldFileViewer.setText("here is the old file viewer\t\t\t\t\t\t\t\t\t\n\n\n\n\n\n");
data = new GridData(SWT.FILL, SWT.FILL, false, false);
data.heightHint = 400;
oldFileViewer.setLayoutData(data);

newFileViewer = new Text(shell, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
newFileViewer.setText("and here is the new file viewer\t\t\t\t\t\t\t\t\t\n\n\n\n\n\n");
data = new GridData(SWT.FILL, SWT.FILL, false, false);
data.heightHint = 400;
newFileViewer.setLayoutData(data);

Button ok = new Button(shell, SWT.PUSH);
ok.setLayoutData(new GridData(SWT.BEGINNING, SWT.CENTER, false, false));

我在每个控件上调用了 setLayoutData,提供了一个 GridDataGridLayout 将使用它来决定如何布局控件。

注意:如果您正在编写 Eclipse 插件,您永远不会调用 new Display() - 仅在编写独立的 SWT 程序时使用。 Eclipse 已经创建了一个显示。

与其创建一个新的 Shell,不如考虑使用 JFace Dialog class,它可以为您处理很多基本的对话框。