Set font when drawing strings in Java

Description

The following code shows how to set font when drawing strings.

Example


import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
/*from ww  w.  jav a 2  s .  c  om*/
import javax.swing.JComponent;
import javax.swing.JFrame;

class MyCanvas extends JComponent {
  public void paint(Graphics g) {
    Font f = new Font("SansSerif", Font.BOLD, 14);
    Font fi = new Font("SansSerif", Font.BOLD + Font.ITALIC, 14);
    FontMetrics fm = g.getFontMetrics(f);
    FontMetrics fim = g.getFontMetrics(fi);

    String s1 = "Demo ";
    String s2 = "Source and Support";
    String s3 = " at www.java2s.com";
    int width1 = fm.stringWidth(s1);
    int width2 = fim.stringWidth(s2);
    int width3 = fm.stringWidth(s3);

    Dimension d = getSize();
    int cx = (d.width - width1 - width2 - width3) / 2;
    int cy = (d.height - fm.getHeight()) / 2 + fm.getAscent();

    g.setFont(f);
    g.drawString(s1, cx, cy);
    cx += width1;
    g.setFont(fi);
    g.drawString(s2, cx, cy);
    cx += width2;
    g.setFont(f);
    g.drawString(s3, cx, cy);
  }
}

public class Main {
  public static void main(String[] a) {
    JFrame window = new JFrame();
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.setBounds(30, 30, 450, 450);
    window.getContentPane().add(new MyCanvas());
    window.setVisible(true);
  }
}

The code above generates the following result.

Set font when drawing strings in Java




















Home »
  Java Tutorial »
    Graphics »




Animation
BufferedImage
Color
Font
Gradient
Graphics Settings
Image
Mouse Draw
Print
Shape
Text
Transform