Java Swing How to - Get Font Metrics








Question

We would like to know how to get Font Metrics.

Answer

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
/* ww w.j  ava 2s  . c o m*/
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Main {
  public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLayout(new BorderLayout());
    frame.add(new TestPane());
    frame.pack();
    frame.setVisible(true);
    System.out.println("Frame size = " + frame.getSize());
  }
}

class TestPane extends JPanel {
  @Override
  public Dimension getPreferredSize() {
    return new Dimension(200, 200);
  }
  @Override
  protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2d = (Graphics2D) g.create();
    String text = getWidth() + "x" + getHeight();
    FontMetrics fm = g2d.getFontMetrics();
    int x = (getWidth() - fm.stringWidth(text)) / 2;
    int y = ((getHeight() - fm.getHeight()) / 2) + fm.getAscent();
    g2d.drawString(text, x, y);
    g2d.dispose();
  }
}