Search code examples
javastringswingfontsfontmetrics

Measuring string and font width


I want to measure a "smallest unit" of a string (which is displayed in JTextArea with some font).

It's the width of a single character + the spacing after it (which depends on the next character).

Eg. I want to measure the pixel distance from beginning of char A to beginning of char Z in the string "AZ".

How can I do that? I tried using the FontMetrics and measuring the string width of both characters together and then decrementing it for the width of the second one but it didn't work...


Solution

  • java.awt.Font has

    public GlyphVector layoutGlyphVector(FontRenderContext frc,
                                         char[] text,
                                         int start,
                                         int limit,
                                         int flags) {
    

    Then use public Point2D getGlyphPosition(int glyphIndex) method of GlyphVector and compare difference of X coordinates for any desired pair of chars.