javaswingawtfontmetrics

How to get text advance (stringWidth) without a Graphics in Java?


How to get text advance (stringWidth) without a Graphics instance in Java?

In the doc examples, stringWidth() is taken from FontMetrics, while FontMetrics is taken from Graphics.

Is it possible to obtain the same without a Graphics?

In the notes below it is said, that Graphics is required because it holds FontRenderContext. But I have FontRenderContext, just have no Graphics.

So, suppose I have FontRenderContext without a Graphics. How do I get stringWidth() then?


Solution

  • While "A FontRenderContext which is directly constructed will most likely not represent any actual graphics device, and may lead to unexpected or incorrect results," you can obtain useful metrics from an instance of TextLayout, as shown here and here.

    FontRenderContext frc = new FontRenderContext(null, false, false);
    TextLayout layout = new TextLayout(text, font, frc);
    System.out.println(layout.getBounds());
    

    image