Java JTextPane Change Font of Selected Text

三世轮回 提交于 2019-12-01 04:37:59

问题


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:


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 .




回答2:


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



来源:https://stackoverflow.com/questions/1905461/java-jtextpane-change-font-of-selected-text

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!