tags:

views:

618

answers:

1

I have a JTextPane (or JEditorPane, I can use either no problem). How can I change the font of a selected area to a specific font?

textpane.getSelectedText().setFont() won't work. (Even with font-family)

+1  A: 

You can change JTextPane's font only as a whole, it doesn't do rich text.

There's a Document underneath JEditorPane (and apparently JTextPane too), which you get a hold of with getDocument(). You want to cast that to a StyledDocument if you can, and then you can do things like setCharacterAttributes to a given run of characters.

There are some (hopefully) helpful examples in the Java tutorial at http://java.sun.com/docs/books/tutorial/uiswing/components/editorpane.html .

Carl Smotricz
+1, for referring to the tutorial. I wish more people would do this as it answers the immediate question and provides a resource for future questions.
camickr
And put us out of business? (laugh) But I agree, the Tutorial is underrated, it taught me much of what I know. Alas, some sections seem to be put together a bit hastily: The RMI tutorial still has me confused today. Thanks for the vote!
Carl Smotricz
(to be fair, 95% of the tutorial is GREAT!)
Carl Smotricz