简体   繁体   English

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

[英]How can I set partial text color in JTextArea?

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. 添加文本而不是添加然后重新打印,但无济于事。

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

EDIT: From the javadoc 编辑:从javadoc

A JTextArea is a multi-line area that displays plain text. JTextArea是一个显示文本的多行区域。

(The emphasis is added.) (重点是补充。)

If you can move to JTextPane, then that will render the formatting. 如果您可以移动到JTextPane,那么将呈现格式。

创建一个自定义的swing文档,例如PlainDocument,并有一个自定义的HighlightedView,它负责绘制标记。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM