javagraphicsawtjpanelfontmetrics

How to use FontMetrics?


Can someone explain to me how to use FontMetrics in a JPanel? I need to figure out the width and height in pixels of a String when using drawString() to paint it on a JPanel

Thanks!


Solution

  • you can define a Graphics object as your method's input variable. or, you can use getFontMetrics() method of your JFrame or JPanel.

    for example to get a character's width:

    JFrame frame = new JFrame();
    int charWidth = frame.getFontMetrics( frame.getFont() ).charWidth() ;