简体   繁体   中英

Java JTextPane Change Font of Selected Text

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)

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM