4

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)

Sev
  • 15,401
  • 9
  • 56
  • 75

2 Answers2

5

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
  • 66,391
  • 18
  • 125
  • 167
  • 2
    +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 Dec 15 '09 at 07:51
  • 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 Dec 15 '09 at 08:03
  • (to be fair, 95% of the tutorial is GREAT!) – Carl Smotricz Dec 15 '09 at 08:03
  • javax.swing.text.StyleConstants.setFontFamily only accepts a "String" as input to the "font-family". is there anyway we can use custom fonts ? – Pacerier Feb 28 '12 at 14:01
1

You can do this by using JTextPane. It is impossible to do this using JTextArea. . Here is a best example on how to use JTextPane.

Sample: http://download.oracle.com/javase/tutorial/uiswing/components/editorpane.html

Code: http://download.oracle.com/javase/tutorial/uiswing/examples/components/TextSamplerDemoProject/src/components/TextSamplerDemo.java

  • Welcome to Stack Overflow! Whilst this may theoretically answer the question, [it would be preferable](http://meta.stackexchange.com/q/8259) to include the essential parts of the answer here, and provide the link for reference. – Kev Aug 21 '11 at 23:48