Search code examples
javaswingjtextpanestyleddocument

Font of a StyledDocument associated with a JTextPane


What font does the StyledDocument associated with a JTextPane use? By default, does it use the same font as the JTextPane? In particular, I'm wondering about the font size.


Solution

  • StyledDocument is just interface. Interface doesn't have any font.

    If you take a look at the DefaultStyledDocument class (implementing the interface).

    public Font getFont(AttributeSet attr) {
        StyleContext styles = (StyleContext) getAttributeContext();
        return styles.getFont(attr);
    }
    

    Then in the StyleContext's sources

    public Font getFont(AttributeSet attr) {
        // PENDING(prinz) add cache behavior
        int style = Font.PLAIN;
        if (StyleConstants.isBold(attr)) {
            style |= Font.BOLD;
        }
        if (StyleConstants.isItalic(attr)) {
            style |= Font.ITALIC;
        }
        String family = StyleConstants.getFontFamily(attr);
        int size = StyleConstants.getFontSize(attr);
    
        /**
         * if either superscript or subscript is
         * is set, we need to reduce the font size
         * by 2.
         */
        if (StyleConstants.isSuperscript(attr) ||
            StyleConstants.isSubscript(attr)) {
            size -= 2;
        }
    
        return getFont(family, style, size);
    }
    

    Then in the StyleConstants.

    public static int getFontSize(AttributeSet a) {
        Integer size = (Integer) a.getAttribute(FontSize);
        if (size != null) {
            return size.intValue();
        }
        return 12;
    }