开发者

Insert String into Document with a specified font

开发者 https://www.devze.com 2023-03-05 09:19 出处:网络
I know I can set a font family on an AttributeSet like this: SimpleAttributeSet set = new SimpleAttributeSet();

I know I can set a font family on an AttributeSet like this:

        SimpleAttributeSet set = new SimpleAttributeSet();
        StyleConstants.setFontFamily(set, "Monospace");

        doc.insertString(
            caretPosition, text, set);

But what I really want to do is set a font:

        StyleConstants.setFont(set, "Courier New");

However, there is no StyleConstants.setFont() 开发者_JAVA技巧method.

So how do I set a font on an AttributeSet? (Note that I am free to use an implementation of AttributeSet other than SimpleAttributeSet. I just happened to use that one.)

(Note that my real goal is to insert a string into a Document using a specified font.)


In my case the

SimpleAttributeSet set = new SimpleAttributeSet();
StyleConstants.setFontFamily(set, "Monospace");

does not work. I must change the "Monospace" to "Monospaced":

StyleConstants.setFontFamily(set, "Monospaced");

To find all available family you can use the following code:

GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
String[] fnt = ge.getAvailableFontFamilyNames();

for (String f : fnt){
            System.out.println(f);
}

Benedek


You can set all font attributes using StyleConstants:

SimpleAttributeSet set = new SimpleAttributeSet();
StyleConstants.setFontFamily(set, "Monospace");
StyleConstants.setFontSize(set, 22);
StyleConstants.setBold(set, true);
StyleConstants.setItalic(set, true);
0

精彩评论

暂无评论...
验证码 换一张
取 消