Obtain FontMetrics of different fonts : Font Metrics « 2D Graphics « Java Tutorial






import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JFrame;

public class Main extends JFrame {

  public Main() {
    super("Demonstrating FontMetrics");

    setSize(510, 210);
    setVisible(true);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  }

  public void paint(Graphics g) {
    g.setFont(new Font("SansSerif", Font.BOLD, 12));
    FontMetrics fm = g.getFontMetrics();
    g.drawString("Current font: " + g.getFont(), 10, 40);
    g.drawString("Ascent: " + fm.getAscent(), 10, 55);
    g.drawString("Descent: " + fm.getDescent(), 10, 70);
    g.drawString("Height: " + fm.getHeight(), 10, 85);
    g.drawString("Leading: " + fm.getLeading(), 10, 100);

    Font font = new Font("Serif", Font.ITALIC, 14);
    fm = g.getFontMetrics(font);
    g.setFont(font);
    g.drawString("Current font: " + font, 10, 130);
    g.drawString("Ascent: " + fm.getAscent(), 10, 145);
    g.drawString("Descent: " + fm.getDescent(), 10, 160);
    g.drawString("Height: " + fm.getHeight(), 10, 175);
    g.drawString("Leading: " + fm.getLeading(), 10, 190);
  }

  public static void main(String args[]) {
    Main app = new Main();
  }
}








16.24.Font Metrics
16.24.1.Font Metrics: the wealth of dimensional data about a font
16.24.2.Font base line
16.24.3.Getting Char with based on current font
16.24.4.calls stringWidth (String) to center several text messagescalls stringWidth (String) to center several text messages
16.24.5.Center text.Center text.
16.24.6.Draw text to the leftDraw text to the left
16.24.7.Draw text to the rightDraw text to the right
16.24.8.Draw text to the centerDraw text to the center
16.24.9.Text justifyText justify
16.24.10.Draw font metrics
16.24.11.Display a text in 3 dimensions
16.24.12.Obtain FontMetrics of different fonts