Change Font and get FontMetrics - Java 2D Graphics

Java examples for 2D Graphics:Font

Description

Change Font and get FontMetrics

Demo Code

import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class Main extends JFrame {
  public Main() {
    super("Show Font");
    setSize(425, 150);/*from   w  ww. ja va 2s .c  o  m*/
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    TextFramePanel sf = new TextFramePanel();
    add(sf);
    setVisible(true);
  }
  public static void main(String[] arguments) {
    Main frame = new Main();
  }
}

class TextFramePanel extends JPanel {
  public TextFramePanel() {
    super();
  }
  public void paintComponent(Graphics comp) {
    super.paintComponent(comp);
    Graphics2D comp2D = (Graphics2D) comp;
    comp2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
        RenderingHints.VALUE_ANTIALIAS_ON);
    Font font = new Font("Dialog", Font.BOLD, 18);
    FontMetrics metrics = getFontMetrics(font);
    comp2D.setFont(font);
    String text = "test";
    int x = (getSize().width - metrics.stringWidth(text)) / 2;
    int y = getSize().height / 2;
    comp2D.drawString(text, x, y);
  }
}

Related Tutorials