Eyad Salah
Eyad Salah

Reputation: 1103

How can I set partial text color in JTextArea?

I want to set color for specific lines in the text area. What I've found so far, is 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 this is not working. What am I doing wrong?

EDIT: OK, I've been trying things out and I tried using

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

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

Upvotes: 2

Views: 6592

Answers (2)

lazypal
lazypal

Reputation: 1

Create a custom swing document extending for example PlainDocument and have a custom HighlightedView which is responsible for painting tokens.

Upvotes: 0

mdma
mdma

Reputation: 57707

I'm not sure if JTextArea can be styled in so much detail, since it presumably sets up styles for the whole document from the selected font, color etc. You may have more luck using a JTextPane/JEditorPane.

EDIT: From the javadoc

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

(The emphasis is added.)

If you can move to JTextPane, then that will render the formatting.

Upvotes: 9

Related Questions