Search code examples
javafontsmonospace

Java "MONOSPACED" font width


I'm creating a game and I'd like to use Java's Font.MONOSPACED font, because it is easy to use (even though it looks disgusting). The problem is that I have no idea about the fonts width-height-ratio, which is very important. I couldn't find a answer online after searching for a while.

If someone knows it or how to find it out, I'd be very grateful.


Solution

  • java.awt.FontMetrics is going to be your friend here.

    You get access to it through a Graphics2d object:

    Graphics2D gfx = ...;
    gfx.setFont(...); // select your preferred font, monospaced or otherwise
    FontMetrics metrics = gfx.getFontMetrics();
    

    having done so you can get: (all from the above link to docs)

    The width of any single char:

    charWidth(char ch) Returns the advance width of the specified character in this Font.

    The width of a string:

    stringWidth(String str) Returns the total advance width for showing the specified String in this Font.

    The height of a line

    getHeight() Gets the standard height of a line of text in this font.

    I assume you can figure out how to get a width-height ratio from the above, and you can get lots of other information from different FontMetrics methods - check it out.