[英]How can I set partial text color in 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);
但这不起作用。 我究竟做错了什么?
编辑:好的,我一直在尝试,我尝试使用
final int end = jTextAreaLog.getLineEndOffset(jTextAreaLog.getLineCount() - 1);
document.insertString(end, "someText", awayAttributeSet);
添加文本而不是添加然后重新打印,但无济于事。
我不确定JTextArea是否可以如此详细地设置样式,因为它可能会根据所选字体,颜色等为整个文档设置样式。使用JTextPane / JEditorPane可能会有更多的运气。
编辑:从javadoc
JTextArea是一个显示纯文本的多行区域。
(重点是补充。)
如果您可以移动到JTextPane,那么将呈现格式。
创建一个自定义的swing文档,例如PlainDocument,并有一个自定义的HighlightedView,它负责绘制标记。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.