1

I am looking for an alternative to FontLoader.computeStringWidth, since this is a Class from the com.sun package and should not be used.

This is used to dynamically set the prefWidth based on text in order to consider text font size (which may come from CSS). Having multiple GridPane I want the first column to be aligned with all the grids.

For example

From this:

| Column1Text | Column2 |

| Column1TextMore | Column2 |

| Column1TextSomeMore | Column2 |

To this (disregard the dots):

| Column1Text .................| Column2 |

| Column1TextMore .........| Column2 |

| Column1TextSomeMore | Column2 |

I did find one accepted answer here which was to create a temporary Scene, add a Text to it, then call applyCss and finally get the width. However I did not like this alternative. Must be a better way. https://stackoverflow.com/a/13020490/1835477

In my case I have multiple grids, and creating a Scene/Text for each seems like a poor solution (performance wise) and not particularly elegant.

DJViking
  • 832
  • 1
  • 12
  • 29
  • unrelated: in fx9, the method has moved somewhere else ... – kleopatra Oct 09 '17 at 08:44
  • If your aim is to set the preferred size, wouldn't using [`USE_COMPUTED_SIZE`](https://docs.oracle.com/javase/8/javafx/api/javafx/scene/layout/Region.html#USE_COMPUTED_SIZE) work just as well? – Itai Oct 09 '17 at 10:06

1 Answers1

1

No better solution has presented itself than the one described on this answer.

  1. Place the String to be measured in a Text object.
  2. Create a throwaway Scene and place the Text object in the Scene.
  3. Call applyCss on Text object.
  4. Get the width of the Text object's layout bounds.

Sample:

final Text text = new Text("XYZ");
new Scene(new Group(text));
text.applyCss(); 
final double width = text.getLayoutBounds().getWidth();
DJViking
  • 832
  • 1
  • 12
  • 29