Get the "real" width of LabelField (BlackBerry)

275 Views Asked by At

If I new a LabelField like this:

LabelField label = new LabelField("long longgggg long text");

it shows:

-----------------------
| long longggg     |
| long text            |
-----------------------

if I use label.getWidth(), it gives the width of:

| long longggg     |

but what I need is the width of:

| long longggg

Any solution?

2

There are 2 best solutions below

0
On

Here is the method I use to get real height of label with multiple lines:

public int getPreferredHeight() {
        String text = getText();

        int maxWidth = getManager().getPreferredWidth();
        String[] words = StringUtilities.stringToWords(text);
        int lastWordAdvance = 0;
        int lines = 1;
        for (int i = 0; i < words.length; i++) {
            int wordAdvance = getFont().getAdvance(words[i]);
            if (lastWordAdvance + wordAdvance < maxWidth ) {
                lastWordAdvance += wordAdvance;
            } else {
                lines++;
                lastWordAdvance = wordAdvance;
            }
        }
        return (int)lines * getFont().getHeight(); 
    }

It goes through words one by one and calculates advance, trying to find out how much lines our label really uses. Then I use getFont().getHeight() to determine total height.

You can use the part that calculates advance from my example to get the real width of the label. To do that you can use Math.max() method to determine maximum line width.

1
On

Check getPreferedWidth() to get length.

If you have applied any font than you need to get

<font object>.getAdvance(label.getText())