6

如果我有一个带有 SWT 的文本字段,我怎样才能让该字段填充到 100% 或某个指定的宽度。

例如,此文本字段只能水平达到这么多。

public class Tmp {
    public static void main (String [] args) {
        Display display = new Display ();
        Shell shell = new Shell (display);
        GridLayout gridLayout = new GridLayout ();
        shell.setLayout (gridLayout);

        Button button0 = new Button(shell, SWT.PUSH);
        button0.setText ("button0");

        Text text = new Text(shell, SWT.BORDER | SWT.FILL);
        text.setText ("Text Field");

        shell.setSize(500, 400);
        //shell.pack();
        shell.open();

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

2 回答 2

5

做这样的事情:

Text text = new Text(shell, SWT.BORDER);
text.setText ("Text Field");
text.setLayoutData(new GridData(SWT.FILL, SWT.CENTER));

/:由于这是公认的答案,因此我删除了错误。谢谢纠正我。

于 2009-01-12T08:26:12.140 回答
5

组件中元素的定位取决于您使用的 Layout 对象。在提供的示例中,您使用的是 GridLayout。这意味着,您需要提供一个特定的 LayoutData 对象来指示您希望组件如何显示。在 GridLayout 的情况下,对象是 GridData。

为了实现你想要的,你必须创建一个 GridData 对象来抓取所有水平空间并填充它:

// Fills available horizontal and vertical space, grabs horizontal space,grab
// does not  grab vertical space
GridData gd = new GridData(SWT.FILL, SWT.FILL, true, false);
text.setLayoutData(gd);

替代方法包括使用不同的 LayoutManager,例如 FormLayout。此布局使用 FormData 对象,该对象还允许您指定组件在屏幕上的放置方式。

您还可以阅读这篇关于 Layouts 的文章以了解 Layouts 的工作原理

作为旁注,构造函数 new GridData(int style) 在文档中被标记为“不推荐”。此示例中显示的显式构造函数是首选。

于 2009-01-12T11:32:10.330 回答