0

Hello everyone I am having some trouble loading custom fonts into Java.

public class CustomFonts extends JPanel {

public static void loadFont() throws FontFormatException, IOException {
    String fontFileName = "stocky.ttf";
    InputStream is = CustomFonts.class.getClassLoader()
            .getResourceAsStream(fontFileName);

    Font ttfBase = Font.createFont(Font.TRUETYPE_FONT, is);

    Font ttfReal = ttfBase.deriveFont(Font.PLAIN, 24);

    GraphicsEnvironment ge = GraphicsEnvironment
            .getLocalGraphicsEnvironment();
    ge.registerFont(ttfReal);

}

public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setTitle("Blach Blach Blach");
    frame.setSize(400, 400);
    frame.setLocationRelativeTo(null);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
    try {
        loadFont();
    } catch (FontFormatException | IOException e) {
        e.printStackTrace();
    }
    JLabel fontF = new JLabel("Testing 1, 2, 3");
    fontF.setFont(new Font("ttfReal", Font.PLAIN, 20));

    frame.add(fontF);
}

}

When I run the code the font just seems to be the default one. I have loaded the ttf file into the project folder of Eclipse but do I have to give a explicit route to the file? I am trying to understand fonts through this basic program because I am trying to load it into a bigger program.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Sam
  • 93
  • 10
  • 1
    Your custom font isn't being set correctly, as no font named `ttfReal` is found. `registerFont` doesn't name the font by the Font object's local variable name. You can determine your custom font's name by [listing all font names](http://docs.oracle.com/javase/7/docs/api/java/awt/GraphicsEnvironment.html#getAvailableFontFamilyNames()), but you may find it easier to simply store the custom Font in a class variable and derive from it whenever you need to set a version of it. – FThompson Oct 01 '13 at 16:43

1 Answers1

0

Perhaps set a static class variable.

public class CustomFonts extends JPanel {
    private static Font ttfBase;
}

Then, when you load the font, load it into ttfBase. Then in your main,

public static void main (String [] args) {
    ...
    Font ttfReal = ttfBase.deriveFont(Font.PLAIN, 20);
    fontF.setFont(ttfReal);
    ...
}
Clark
  • 1,357
  • 1
  • 7
  • 18