[英]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.