如何在JTextArea中设置部分文本颜色? [英] How can I set partial text color in JTextArea?

查看:434
本文介绍了如何在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?

好的,我一直在尝试尝试,并且尝试使用

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.

推荐答案

我不确定JTextArea的样式是否可以这么详细,因为它大概是根据所选字体,颜色等为整个文档设置样式的.使用JTextPane/JEditorPane可能会带来更多运气.

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.

来自javadoc

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

A JTextArea is a multi-line area that displays plain text.

(重点已添加.)

如果您可以移至JTextPane,则将呈现格式.

If you can move to JTextPane, then that will render the formatting.

这篇关于如何在JTextArea中设置部分文本颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆