Setting the font of either a JEditorPane or JTextPane is not possible by doing it directly. However, you can do that by setting it in the EditorKit class. This post uses the RTFEditorKit class as an example of the editor kit used by a JEditorPane.
I created a custom class that inherits the RTFEditorKit to make things simpler. Just call initializeDefaultFont() to set the font to the JEditorPane. However, a very important thing to note is that this method should only be called after the RTFEditorKit object is set to the JEditorPane.setEditorKit() method. If the initializeDefaultFont() is called before that, the font will not be set.
To use the class. Check the sample code below.
|
1 2 3 4 |
JEditorPane ep = new JEditorPane(); MyRTFEditorKit rtfkit = new MyRTFEditorKit(); ep.setEditorKit(rtfkit); rtfkit.initializeDefaultFont(); |
And the MyRTFEditor.java class is below.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
public class MyRTFEditorKit extends RTFEditorKit { private MutableAttributeSet attr = null; private Font font = new Font("Arial", Font.PLAIN, 12); public void initializeDefaultFont() { if (attr == null) attr = new SimpleAttributeSet(); StyleConstants.setFontFamily(attr, font.getFontName()); StyleConstants.setFontSize(attr, font.getSize()); StyleConstants.setForeground(attr, Color.black); if (Default.RTF_FONT.isBold()) StyleConstants.setBold(attr, true); else StyleConstants.setBold(attr, false); if (Default.RTF_FONT.isItalic()) StyleConstants.setItalic(attr, true); else StyleConstants.setItalic(attr, false); // set default font in rtf editor kit MutableAttributeSet iattr = getInputAttributes(); iattr.removeAttribute(attr); iattr.addAttributes(attr); } } |