Question

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.

Was it helpful?

Solution 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());

OTHER TIPS

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:

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top