5

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() 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.)

Charles
  • 50,943
  • 13
  • 104
  • 142
Paul Reiners
  • 8,576
  • 33
  • 117
  • 202
  • Works fine for me. Post your SSCCE that demonstrates the problem. – camickr May 10 '11 at 19:49
  • possible duplicate of [Resetting attributes in a Document after inserting a String](http://stackoverflow.com/questions/5955324/resetting-attributes-in-a-document-after-inserting-a-string) – trashgod May 10 '11 at 21:32

2 Answers2

3

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

betontalpfa
  • 3,454
  • 1
  • 33
  • 65
2

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);
Suma
  • 33,181
  • 16
  • 123
  • 191
KrzyH
  • 4,256
  • 1
  • 31
  • 43