0

if I have a class with a private Label = new Label(""); in it and in some method i write:

private void setText(String text)
{
    this.label.setText(text);
    System.out.println("label size = " + this.label.getSize(0,0));
}

it will always print "label size = Dimension(0,0)". why is this? how can I obtain the size occupied by the label after setting its text? I also tried other solutions (here and method getTextBounds() as suggested in here ) but i either obtain again Dimension(0,0) or a NullPointerException, respectively.

do you have any suggestion? thanx :)

FSp
  • 1,545
  • 17
  • 37

1 Answers1

1

this.label.getPreferredSize() is what you're looking for. It returns the space your label would like to occupy. But at this point the label doesn't know yet what font to use, hence the NullPointerException. Once your figure tree has been set e.g. as the content of a FigureCanvas the font should be available. Alternatively, you could explicitly set a font before calling getPreferredSize().

To add a rounded rectangle around your label, like you requested in your comment, you could do the following:

RoundedRectangle rr = new RoundedRectangle();
rr.setBorder(new MarginBorder(4));
rr.setLayoutManager(new StackLayout());
rr.add(new Label("label text"));
Frettman
  • 2,251
  • 1
  • 13
  • 9
  • thankx a lot. actually i need the label size because around the label i want to draw a RoundedRectangle and i want to set the rectangle size as a function of the label size. i thought the setText would be the right place to adapt the rectangle size in case the content of the label is updated. any other suggestions?!? – FSp Dec 02 '11 at 05:27
  • @FSp: For a rounded border around you label, see my updated answer. – Frettman Dec 02 '11 at 08:30