How can I set partial text color in JTextArea

Posted by ComputerJy on Stack Overflow See other posts from Stack Overflow or by ComputerJy
Published on 2010-05-14T21:50:06Z Indexed on 2010/05/14 21:54 UTC
Read the original article Hit count: 458

Filed under:
|
|

I want to set color for specific lines in the text area. What I've found so far, was 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?

© Stack Overflow or respective owner

Related posts about java

Related posts about swing