如何在不指定元素高度的情况下将文本包装在标签中

How to wrap text in the Label without specifying height of the element

问题是我无法设置标签的高度。对于长文本,我的标签应该有 2 行的高度,而短文本只有 1 行。 有代码示例:

public MyComposite(Composite parent) {
    super(parent, SWT.NONE);
    setLayout(new GridLayout(1, false));

    description = new Label(this, SWT.WRAP);
    description.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 2, 1));
    description.setText("Looooooooooooooooooooooooooooooooooooooo" + 
    "oooooooooooooooooooooooooooooooooooooooooooooooooooooo" + 
    "ooooooooooooooooooooooooooooooooooooong text");
}

要在 GridLayout 中启用换行文本,您必须将 GridData (grabExcessHorizontalSpace) 的第三个参数设置为 true。还要确保父组合的大小由其 layoutData 定义,否则它将被 Label 扩展。以下代码段包含标签文本:

Shell shell = new Shell( parentShell );
shell.setSize( 400, 300 );
shell.setLayout( new GridLayout(1, false) );
Label description = new Label(shell, SWT.WRAP);
description.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, false));
description.setText("Looooooooooooooooooooooooooooooooooooooo" +
    "oooooooooooooooooooooooooooooooooooooooooooooooooooooo" +
    "ooooooooooooooooooooooooooooooooooooong text");
shell.open();

另请注意,换行是作为自动换行实现的,非常长的非空白字符序列不会被拆分成行。