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

2024-06-26

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

// 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);

但这是行不通的。我究竟做错了什么?

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

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

添加文本而不是添加然后重新设计,但无济于事。


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

编辑:来自javadoc

JTextArea 是一个多行区域 显示plain text.

(重点已添加。)

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 JTextArea 中设置部分文本颜色? 的相关文章

随机推荐