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