如果你想有不同的文本文字有不同的顏色指定文本顏色,你必須閱讀有關How to use Editor Pane or TextPane。這將幫助你。
的樣本程序:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.text.AttributeSet;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;
public class TextPaneTest extends JFrame
{
private JPanel topPanel;
private JTextPane tPane;
public TextPaneTest()
{
topPanel = new JPanel();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
EmptyBorder eb = new EmptyBorder(new Insets(10, 10, 10, 10));
tPane = new JTextPane();
tPane.setBorder(eb);
//tPane.setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY));
tPane.setMargin(new Insets(5, 5, 5, 5));
topPanel.add(tPane);
appendToPane(tPane, "My Name is Too Good.\n", Color.RED);
appendToPane(tPane, "I wish I could be ONE of THE BEST on ", Color.BLUE);
appendToPane(tPane, "Stack", Color.DARK_GRAY);
appendToPane(tPane, "Over", Color.MAGENTA);
appendToPane(tPane, "flow", Color.ORANGE);
getContentPane().add(topPanel);
pack();
setVisible(true);
}
private void appendToPane(JTextPane tp, String msg, Color c)
{
StyleContext sc = StyleContext.getDefaultStyleContext();
AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, c);
aset = sc.addAttribute(aset, StyleConstants.FontFamily, "Lucida Console");
aset = sc.addAttribute(aset, StyleConstants.Alignment, StyleConstants.ALIGN_JUSTIFIED);
int len = tp.getDocument().getLength();
tp.setCaretPosition(len);
tp.setCharacterAttributes(aset, false);
tp.replaceSelection(msg);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new TextPaneTest();
}
});
}
}
這裏是這段代碼的輸出:
謝謝,這就是我正在尋找。我會盡力回覆。 – FirmView 2012-03-05 13:16:37
@FirmView:你的歡迎,併成爲我的客人,我可以幫助你,我會:-) – 2012-03-05 13:31:32
*「一個示例程序片段:」*很奇怪,你應該給這些單詞添加'片段'。我的意思是 - '片段'通常表達'短',但在編程環境中,它也意味着(至少對我而言)「缺少更多代碼就無法工作」。示例程序已準備就緒。 (代碼和屏幕截圖爲+1) – 2012-03-05 13:54:25