Search code examples
labelswtsizeword-wrap

Get size of SWT Label with word wrap


Is there a way to get the exact size computed by a label before laying it out.

In other words, let us say there is a label with a really long sentence:

Hi how are you doing, my name is bond, I have no name, I live in London, but yet the world is my Home. I am here to play and enjoy.

This is a single line. however if the window is not large enough, then the label wraps into two lines.

I want to find out the final height that it will take up, before laying it out (this is so that I can adjust the font size accordingly so that it displays in a single line).

However if I do label.computeSize(SWT.DEFAULT, SWT.DEFAULT) it only returns the size that it needs without wrapping.

If there is a way to do it that would be great.


Solution

  • Fist of all the Label must be created with the SWT.WRAP style. Otherwise it will never wrap its text.

    Then you need to tell computeSize what width the label should have. Otherwise computeSize doesn't know where to wrap and computes the size for the unwrapped text.

    If you specify the desired width of the label, computeSize will return the neccesary height.

    For example

    Label label = new Label( shell, SWT.WRAP );
    label.setText( "Snippets are minimal stand-alone programs that demonstrate specific techniques or functionality." );
    Point size = label.computeSize( 200, SWT.DEFAULT );
    System.out.println( size );  // Point {202, 47}
    

    The returned size is a Point whose x field is (almost) the desired width and the y field denotes the necessary height to display the wrapped text.

    On my system, the size is { 202, 47 } (the text spans two lines) but this may vary depending on the platform and font size.