1

I'm building a small conversation agent, where the text looks like follows:

enter image description here

I would like to set the System's text to always be red. The text is all placed in a JTextPane.

How can I accomplish this? I have tried doing the following:

agentTextPane.setForeground(Color.red); after the system's text is added, and then switching back to black, however that changes all the text in the JTextPane.

This is how the system's text is added:

//'output' is a stringBuilder
output.append("\nSystem: ").append(tempOutput).append("\n");
agentTextPane.setText(output.toString());
Dot NET
  • 4,891
  • 13
  • 55
  • 98

2 Answers2

2

As shown here, you can define an attribute set representing a desired style. For example,

StyledDocument doc = (StyledDocument) jtp.getDocument();
SimpleAttributeSet system = new SimpleAttributeSet();
StyleConstants.setFontFamily(system, "Serif");
StyleConstants.setForeground(system, Color.red);
doc.insertString(doc.getLength(), "...", system);

The styles can be progressive, as shown here.

image

See Text Component Features for more examples.

Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
2

You may want to use HTML tags to format your Strings in terms of colour. The following reference may be useful. setting JTextPane to content type HTML and using string builders

 output.append("<font color=\"red\">");
 output.append("\nSystem: ").append(tempOutput).append("\n");
 output.append("</font>");
Community
  • 1
  • 1
blackpanther
  • 10,998
  • 11
  • 48
  • 78