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.
            Asked
            
        
        
            Active
            
        
            Viewed 2,441 times
        
    2 Answers
3
            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;
}
        StanislavL
        
- 56,971
 - 9
 - 68
 - 98
 
2
            
            
        The relevant UIManager key is TextPane.font. UIManager.get() may be used to determine the value for a chosen L&F. For example, on Mac OS X, this code produces the following console output:
System.out.println(UIManager.get("TextPane.font"));
Console:
com.apple.laf.AquaFonts$DerivedUIResourceFont[
    family=Lucida Grande,name=Lucida Grande,style=plain,size=13]
Addendum: As shown in this example, the default is a StyleContext.NamedStyle that matches the UI default:
NamedStyle:default {
    name=default,font-style=,
    FONT_ATTRIBUTE_KEY=com.apple.laf.AquaFonts$DerivedUIResourceFont[
        family=Lucida Grande,name=Lucida Grande,style=plain,size=13],
    font-weight=normal,
    font-family=Lucida Grande,
    font-size=4,
}
Addendum: Here's the code to iterate through the pane's styles:
JTextPane jtp = new JTextPane();
...
HTMLDocument doc = (HTMLDocument) jtp.getDocument();
StyleSheet styles = doc.getStyleSheet();
Enumeration rules = styles.getStyleNames();
while (rules.hasMoreElements()) {
    String name = (String) rules.nextElement();
    Style rule = styles.getStyle(name);
    System.out.println(rule.toString());
}
- 
                    Empirically, this default prevails until it's changed, but I've never chased it down. – trashgod Aug 05 '11 at 00:18