Reputation: 2246
I am using JavaFX to produce bitmap previews of my music documents.
At certain points, within the paint process, I need to know the dimensions of a given string.
Upto now, I have used the following :
bounds = TextBuilder.create().text(string).font(m_Font).build().getLayoutBounds();
However, eclipse informs me that this is depreciated. It is so depreciated that the bounds object is empty (all set to zero).
How do I go about getting the bounds - width and height - of a single line string now ?
Please note that there are no on screen controls being used to display this stuff. Everything is generated in memory and "dumped" out to a png bitmap.
I have scavenged around on the net and have not found the answer (or I missed it entirely).
Any expert help available ?
Upvotes: 0
Views: 880
Reputation: 44130
As I mentioned in my comment, getLayoutBounds()
is not deprecated and is perfectly valid to use. It's just the builder which is deprecated.
That said, I have created the following test application which produced seemingly correct output, using builders and creating objects directly:
import javafx.geometry.Bounds;
import javafx.scene.text.Text;
import javafx.scene.text.TextBuilder;
import javafx.stage.Stage;
import javafx.scene.text.Font;
public class stack extends javafx.application.Application {
public static void main(String[] args)
{
// Builder
Bounds b = TextBuilder.create().text("hello").build().getLayoutBounds();
System.out.println(b.getHeight() + ", " + b.getWidth());
b = TextBuilder.create().text("heeeeello").build().getLayoutBounds();
System.out.println(b.getHeight() + ", " + b.getWidth());
// No builder
b = new Text("hello").getLayoutBounds();
System.out.println(b.getHeight() + ", " + b.getWidth());
b = new Text("heeeeello").getLayoutBounds();
System.out.println(b.getHeight() + ", " + b.getWidth());
// With bad font, zero sized
Font my_font = new Font("i am not a font", 0);
Text text = new Text("heeeeello");
text.setFont(my_font);
b = text.getLayoutBounds();
System.out.println(b.getHeight() + ", " + b.getWidth());
// With bad font, arbitrary size
my_font = new Font("i am not a font", 20);
text = new Text("heeeeello");
text.setFont(my_font);
b = text.getLayoutBounds();
System.out.println(b.getHeight() + ", " + b.getWidth());
}
@Override
public void start(Stage primaryStage) throws Exception { }
}
Output:
15.9609375, 25.91015625
15.9609375, 51.01171875
15.9609375, 25.91015625
15.9609375, 51.01171875
0.0, 0.0
26.6015625, 85.01953125
I would hypothesise that your font is screwing things up, possibly the size is set to zero or some other error.
Upvotes: 3