看着你的問題,好像你想在你的JTextPane中使用多種顏色。 您只需將此方法放入您的代碼中並根據需要提供參數。
public void appendToPane(String yourText, Color colour)
{
StyleContext sc = StyleContext.getDefaultStyleContext();
AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, colour);
aset = sc.addAttribute(aset, StyleConstants.FontFamily, "Lucida Console");
int len = tPane.getDocument().getLength();
tPane.setCaretPosition(len);
tPane.setCharacterAttributes(aset, false);
tPane.replaceSelection(yourText);
}
上述方法使用以下進口:
- 進口javax.swing.text.AttributeSet;
- import javax.swing.text.SimpleAttributeSet;
- import javax.swing.text.StyleConstants;
- import javax.swing.text.StyleContext;
- import javax.swing.JTextPane;
而tPane是JTextPane的對象。就像如果你想讓你的名字顯示爲藍色一樣,請將方法稱爲appendToPane(「Your Name」,Color.BLUE);現在如果你想讓其他文本顯示爲紅色,再次調用方法appendToPane(「New Text」,Color.RED);希望這可以解決你所要求的查詢。
Regards
Thanks!小錯字:STyleConstants應該是StyleConstants – adhg 2013-05-28 16:25:43