Font of a StyledDocument associated with a JTextPane

烂漫一生 提交于 2020-01-04 02:42:24

问题


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.


回答1:


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;
}



回答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());
}


来源:https://stackoverflow.com/questions/6949125/font-of-a-styleddocument-associated-with-a-jtextpane

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!