当某些单词输入到 JTextPane 中时,如何更改它们的颜色?

How do I change the colour of certain words when they are entered into a JTextPane?

我看过几篇关于此的帖子,但 none 似乎有效。

我在 Java 编程论坛上有一个关于这个的帖子,请帮忙!:http://www.javaprogrammingforums.com/whats-wrong-my-code/47440-trying-make-simple-java-editor-having-trouble-changing-colour-words.html

DefaultStyledDocument document = new DefaultStyledDocument();
JTextPane textpane = new JTextPane(document);
StyleContext context = new StyleContext();
// build a style
Style style = context.addStyle("test", null);
// set some style color
StyleConstants.setForeground(style, Color.RED);
// add some data to the document
document.insertString(0, "", style);


OR




JTextPane pane = new JTextPane();
SimpleAttributeSet set = new SimpleAttributeSet();
StyleConstants.setForeground(set, Color.red);
Document doc = pane.getStyledDocument();
doc.insertString(doc.getLength(), "Kleine ", set);