eclipse-rap

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


Problem is that I can't set the height of the Label. For a long text my Label should have height for 2 rows, with a short text only 1 row. There is code example:

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");
}

Solution

  • To enable wrapping text in a GridLayout, you have to set the 3rd parameter of the GridData (grabExcessHorizontalSpace) to true. Also make sure that the parent composite's size is defined by its layoutData, otherwise it will be expanded by the Label. The following snippet has the label text wrapped:

    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();
    

    Also note that wrapping is implemented as word-wrap, a very long sequence of non-whitespace characters won't be split into lines.