So, I have a JTextArea in my program, and I'm appending some text into in. I'm trying to make just one of the appended Strings bold, without making all of the text in the JTextArea bold. There doesn't seem to be a way, at least not one that I can find, to edit the font of a String without adding it to something like a JLabel (which I'd rather not do).

Anyone know a work around for this?

Thanks for your time.

有帮助吗?

解决方案 2

Use a JTextPane instead of JTextArea. By embedding text as html in this component you have more freedom to style the text. See this example:

JTextPane myTextPane = new JTextPane();
myTextPane.setContentType("text/html"); 
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("<html>");
stringBuilder.append("<b>bold text </b>");
stringBuilder.append("normal text");
stringBuilder.append("</html>");


myTextPane.setText(stringBuilder.toString());

其他提示

The best work around: don't use a JTextArea, a component that is made to display simple single fonted text easily. Instead use one of the more robust text components such as JEditorPane or JTextPane. Please have a look at the tutorials:

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top