views:

208

answers:

3

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.

+4  A: 

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.

mdma
The JTextArea supports StyleDocuments and attributes, I can't find a reason why it shouldn't support text style!
ComputerJy
I've not tried this, but looking at the code, BasicTextAreaUI only creates PlainView instances. JTextArea may accept a styled document, but are you sure it renders it? I know JTextPane has explicit support for StyledDocument.
mdma
A: 

What IDE are you using? I am quite sure I did that once in NetBeans but I can't give 100% "it's possibe". Did you check in the official documentation?

Cninroh
A: 

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

lazypal