How to set partial text color in JTextArea?

I want to set the color for certain lines in the text area. So far I have found the following

// Declarations
private final DefaultStyledDocument document;
private final MutableAttributeSet homeAttributeSet;
private final MutableAttributeSet awayAttributeSet;

// Usage in the form constructor
jTextAreaLog.setDocument(document);
homeAttributeSet = new SimpleAttributeSet();
StyleConstants.setForeground(homeAttributeSet, Color.blue);
StyleConstants.setItalic(homeAttributeSet, true);
awayAttributeSet = new SimpleAttributeSet();
StyleConstants.setForeground(awayAttributeSet, Color.red);

// Setting the style of the last line
final int start = jTextAreaLog.getLineStartOffset(jTextAreaLog.getLineCount() - 2);
final int length = jTextAreaLog.getLineEndOffset(jTextAreaLog.getLineCount() - 1) -     start;
document.setCharacterAttributes(start, length, awayAttributeSet, true);

But that does not work. What am I doing wrong?

EDIT: Ok, I tried everything and I tried using

final int end = jTextAreaLog.getLineEndOffset(jTextAreaLog.getLineCount() - 1);
document.insertString(end, "someText", awayAttributeSet);

add text instead of adding restyling, but to no avail.

+2
source share
2 answers

I'm not sure that JTextArea can be styled in such detail, as it presumably sets styles for the entire document from the selected font, color, etc. You might be lucky with JTextPane / JEditorPane.

EDIT: from javadoc

A JTextArea is a multi-line region that displays plain text .

(Added accent.)

JTextPane, .

+9

swing, , , PlainDocument, HighlightedView, .

0

All Articles