Java Graphics How to - Calculate the font's width?








Question

We would like to know how to calculate the font's width?.

Answer

import java.awt.FontMetrics;
import java.awt.GridLayout;
//w  w  w .  j a va  2  s. c  o  m
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class Main {
  public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setSize(300, 300);

    JPanel panel = new JPanel(new GridLayout(3, 1));
    JLabel label = new JLabel();
    JTextField tf = new JTextField();
    JButton b = new JButton("calc sting width");
    b.addActionListener(e -> {
      FontMetrics fm = label.getFontMetrics(label.getFont());
      String text = tf.getText();
      int textWidth = fm.stringWidth(text);
      label.setText("text width for \"" + text + "\": " + textWidth);
    });
    panel.add(label);
    panel.add(tf);
    panel.add(b);
    frame.setContentPane(panel);
    frame.setVisible(true);
  }

}