0

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?

Kevin
  • 1,147
  • 11
  • 21
  • It returns the width of `| long longggg |` because I think it uses all the width available to it. You can check it by applying a color background on that LabelField. But if you don't want that LabelField to take all the space then the parent manager needs to control the space it allows to that field. – Rupak Sep 10 '12 at 06:08
  • coz I need to draw a background rect behind the LabelField and I dont need the unnecessary. – Kevin Sep 10 '12 at 09:31
  • 1
    Thats hacky. Instead, try adding the label into a fixed width manager, then call ´Manager.setBackground´. – Mister Smith Sep 10 '12 at 10:30

2 Answers2

0

Check getPreferedWidth() to get length.

If you have applied any font than you need to get

<font object>.getAdvance(label.getText()) 
Shashank Agarwal
  • 512
  • 3
  • 12
  • Then it will return the length of "long longggg long text", not the actual width used by the `LabelField`. – Rupak Sep 10 '12 at 08:28
0

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.

AAverin
  • 3,014
  • 3
  • 27
  • 32