Compare derived fonts in Java

Description

The following code shows how to compare derived fonts.

Example


import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.font.TextAttribute;
import java.awt.geom.AffineTransform;
import java.util.Hashtable;
/*from  ww  w . j av  a  2 s .c om*/
import javax.swing.JComponent;
import javax.swing.JFrame;

class MyCanvas extends JComponent {
  public void paint(Graphics g) {
    Graphics2D g2 = (Graphics2D) g;

    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
        RenderingHints.VALUE_ANTIALIAS_ON);

    // Create a 1-point font.
    Font font = new Font("Serif", Font.PLAIN, 1);
    float x = 20, y = 20;

    Font font24 = font.deriveFont(40.0f);
    g2.setFont(font24);
    g2.drawString("font.deriveFont(24.0f)", x, y += 30);

    Font font24italic = font24.deriveFont(Font.ITALIC);
    g2.setFont(font24italic);
    g2.drawString("font24.deriveFont(Font.ITALIC)", x, y += 30);

    AffineTransform at = new AffineTransform();
    at.shear(.2, 0);
    Font font24shear = font24.deriveFont(at);
    g2.setFont(font24shear);
    g2.drawString("font24.deriveFont(at)", x, y += 30);

    Hashtable attributes = new Hashtable();
    attributes.put(TextAttribute.WEIGHT, TextAttribute.WEIGHT_BOLD);
    Font font24bold = font24.deriveFont(attributes);
    g2.setFont(font24bold);
    g2.drawString("font24.deriveFont(attributes)", x, y += 30);
  }
}

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.

Compare derived fonts in Java




















Home »
  Java Tutorial »
    Graphics »




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