如何在JTextArea中设置部分文本颜色?

Eya*_*lah 2 java swing jtextarea

我想为文本区域中的特定行设置颜色.到目前为止我发现的是以下内容

// 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);
Run Code Online (Sandbox Code Playgroud)

但这不起作用.我究竟做错了什么?

编辑:好的,我一直在尝试,我尝试使用

final int end = jTextAreaLog.getLineEndOffset(jTextAreaLog.getLineCount() - 1);
document.insertString(end, "someText", awayAttributeSet);
Run Code Online (Sandbox Code Playgroud)

添加文本而不是添加然后重新打印,但无济于事.

mdm*_*dma 9

我不确定JTextArea是否可以如此详细地设置风格,因为它可能会根据所选字体,颜色等为整个文档设置样式.使用JTextPane/JEditorPane可能会有更多的运气.

编辑:从javadoc

JTextArea是一个显示文本的多行区域.

(重点是补充.)

如果您可以移动到JTextPane,那么将呈现格式.