Setting custom font

Firstly gain an URL to the Font. Then do something like this.

‘Airacobra Condensed’ font available from Download Free Fonts.

Registered Font

import java.awt.*;
import javax.swing.*;
import java.net.URL;

class LoadFont {
    public static void main(String[] args) throws Exception {
        // This font is < 35Kb.
        URL fontUrl = new URL("http://www.webpagepublicity.com/" +
            "free-fonts/a/Airacobra%20Condensed.ttf");
        Font font = Font.createFont(Font.TRUETYPE_FONT, fontUrl.openStream());
        GraphicsEnvironment ge = 
            GraphicsEnvironment.getLocalGraphicsEnvironment();
        ge.registerFont(font);
        JList fonts = new JList( ge.getAvailableFontFamilyNames() );
        JOptionPane.showMessageDialog(null, new JScrollPane(fonts));
    }
}

OK, that was fun, but what does this font actually look like?

Display Font

import java.awt.*;
import javax.swing.*;
import java.net.URL;

class DisplayFont {
    public static void main(String[] args) throws Exception {
        URL fontUrl = new URL("http://www.webpagepublicity.com/" +
            "free-fonts/a/Airacobra%20Condensed.ttf");
        Font font = Font.createFont(Font.TRUETYPE_FONT, fontUrl.openStream());
        font = font.deriveFont(Font.PLAIN,20);
        GraphicsEnvironment ge =
            GraphicsEnvironment.getLocalGraphicsEnvironment();
        ge.registerFont(font);

        JLabel l = new JLabel(
            "The quick brown fox jumped over the lazy dog. 0123456789");
        l.setFont(font);
        JOptionPane.showMessageDialog(null, l);
    }
}

Leave a Comment