It appears that there is no API call to calculate the width (in pixels) of a text string in Java FX 2.2. There have been suggestions of workarounds on other forums, but my efforts to create or find any code that returns the width of a String, either using the default font or otherwise, have failed. Any help would be appreciated.
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
I tried this:
and it seems to be working fine.
This solution works up until java 8:
Those classes have since been removed and are not available in newer java version!
If you are just measuring the default font without CSS:
If you need to apply CSS:
This works because it forces a layout pass on the Text which calculates it's layout bounds. The scene in step 2 is required because that is just the way the CSS processor works (it needs a node to be located in a Scene to be able to do its job). Definitely read the linked javadoc for applyCss if you want to understand the processing further.
Sample Code
Sample program output (displays the width in pixels of an arbitrary piece of text):
Apply the font to a text object containing the same message you will plot to the canvas. Unlike when you are measuring text plotted to the scene graph, items plotted to a canvas do not have CSS applied to them, so you don't need to place the Text object in a scene and have CSS applied to it before measuring the text. You can measure the layout bounds of your text object and it will be the same as the bounds of the text plotted within the canvas with the same font.