Java Swing Tutorial - Java FontMetrics.charWidth(char ch)








Syntax

FontMetrics.charWidth(char ch) has the following syntax.

public int charWidth(char ch)

Example

In the following code shows how to use FontMetrics.charWidth(char ch) method.

/*ww w .  j av  a  2 s  .c o  m*/

import java.awt.FontMetrics;

import javax.swing.JFrame;

public class Main {
  public static void main(String args[]) {
    JFrame f = new JFrame("JColorChooser Sample");
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    

    f.setSize(300, 200);
    f.setVisible(true);
    
    FontMetrics metrics = f.getFontMetrics(f.getFont());

    int widthX = metrics.charWidth('X');

    System.out.println(widthX);
    
  }
}