Through the years I have created tons of small examples, which illustrate a very specific task or use case. I decided to publish them as a series of small posts. Some topics may be rather old stuff, hopefully interesting nonetheless.

How about using a custom font in a JTextArea? Take a look at the screenshot first:

Screenshot of C64FontDemo

This is the class that produces the output:

package com.thomaskuenneth.swing.fontdemo;

import java.awt.*;
import java.io.*;
import java.util.logging.*;
import javax.swing.*;

/**
 * 1) Get the font here: https://style64.org/c64-truetype
 * 2) Unzip and update variable 
 * 
 * @author Thomas Künneth
 */
public class C64FontDemo {

    private static final String FONTPATH  = "/Users/thomas/Downloads/C64_TrueType_v1.2.1-STYLE/fonts/C64_Pro_Mono-STYLE.ttf";
    private static final String CODE = "10 PRINT \"HELLO, WORLD \";\n20 GOTO 10";

    private static void createAndShowUI() {
        JFrame frame = new JFrame(C64FontDemo.class.getName());
        JTextArea ta = new JTextArea(CODE);
        ta.setBackground(new Color(0x525ce6));
        ta.setForeground(new Color(0xb0b3ff));
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(new JScrollPane(ta));
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            try {
                InputStream is = new FileInputStream(new File(FONTPATH));
                Font f = Font.createFont(Font.TRUETYPE_FONT, is);
                f = f.deriveFont(22f);
                UIManager.put("TextArea.font", f);
            } catch (FontFormatException | IOException ex) {
                Logger.getLogger(C64FontDemo.class.getName()).log(Level.SEVERE, "main()", ex);
            }
            createAndShowUI();
        });
    }
}

I am using C64 TrueType v1.2. You need to download and unzip the fonts and update FONTPATH accordingly.

Making a font avavilable to a JTextArea involves:

  1. InputStream is = new FileInputStream(new File( ... ));
  2. Font f = Font.createFont(Font.TRUETYPE_FONT, is);
  3. UIManager.put("TextArea.font", f);

Quite nice, isn’t it?