Articles Projects Tips Downloads Contacts About

Using custom font (not registered) in StyledDocument of JEditorPane.

javax.swing.text.StyledDocument interface provides a getFont() method which returns font based on passed in AttributeSet attributes. There should be check in the getFont() method whether font family attribute has the same name as the custom font. If the name is the same we should create derived font with all passed attributes.

The DefaultStyledDocument extension below shows how to achieve

public class CustomFontDocument extends DefaultStyledDocument {
    String pathToFontFile="c:/test/testFontFile.ttf";
    Font customFont;
    public Font getFont(AttributeSet attrs) {

        if (customFont==null) {
            try {
                InputStream fis=new FileInputStream(pathToFontFile);
                customFont = Font.createFont(Font.TRUETYPE_FONT, fis);
            } catch (FontFormatException e) {

            } catch (IOException e) {
            if (customFont!=null && customFont.getName().equals(StyleConstants.getFontFamily(attrs))) {

                //we should specify all the font params here
                int style = Font.PLAIN;
                if (StyleConstants.isBold(attrs)) {
                    style |= Font.BOLD;
                if (StyleConstants.isItalic(attrs)) {

                    style |= Font.ITALIC;
                Font retFont=customFont.deriveFont(style, StyleConstants.getFontSize(attrs));
                return retFont;
        return super.getFont(attrs);