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.

And the class is below.

You can easily change the font attributes like bold and italic of a JTree‘s tree node (parent or leaf node) by overriding the DefaultTreeCellRenderer class getTreeCellRendererComponent() method. Then you can set the JTree’s setRenderer() method to this renderer object.

The code above sets the tree node’s font attributes (in this case bold and italic) if it is selected. If you want all tree nodes to have these same font attributes, you can remove the if condition statement.

Say you want your selected JTree node to have its text in bold and italicized, once you click on the node, the text (if long) more or less gets truncated with … and you do not want to see that in your JTree right? What you need to do is override the getPreferredSize() method of the DefaultTreeCellRenderer. mimiman_ from the Sun forum gave this piece of code.

It worked wonders!

Related Posts Plugin for WordPress, Blogger...