Java Swing Tutorial - Java Font TRUETYPE_FONT








Syntax

Font.TRUETYPE_FONT has the following syntax.

public static final int TRUETYPE_FONT

Example

In the following code shows how to use Font.TRUETYPE_FONT field.

import java.awt.Font;
import java.io.InputStream;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/*ww w. j  a v a 2 s  .  c  o  m*/
public class Main {
  private static String[] names = { "A.ttf" };

  private static Map<String, Font> cache = new ConcurrentHashMap<String, Font>(names.length);
  static {
    for (String name : names) {
      cache.put(name, getFont(name));
    }
  }

  public static Font getFont(String name) {
    Font font = null;
    if (cache != null) {
      if ((font = cache.get(name)) != null) {
        return font;
      }
    }
    String fName = "/fonts/" + name;
    try {
      InputStream is = Main.class.getResourceAsStream(fName);
      font = Font.createFont(Font.TRUETYPE_FONT, is);
    } catch (Exception ex) {
      ex.printStackTrace();
      System.err.println(fName + " not loaded.  Using serif font.");
      font = new Font("serif", Font.PLAIN, 24);
    }
    return font;
  }
}