这是一个使用单词到颜色映射的解决方案。正如你所看到的,我映射apple
为红色,字对绿色
public class Test {
HashMap<String, Color> myMap = new HashMap<String, Color>();
public static void main(String[] args) {
new Test();
}
public Test() {
myMap.put("apple", Color.RED);
myMap.put("apples", Color.RED);
myMap.put("green", Color.GREEN);
String text = "This is a green apple and I like to eat Apples";
JTextPane textPane = new JTextPane();
StyledDocument doc = textPane.getStyledDocument();
Style style = textPane.addStyle("Red Style", null);
StyleConstants.setForeground(style, Color.red);
ArrayList<Chunk> chunks = getColorsBasedOnText(text, textPane);
try {
for (Chunk chunk : chunks) {
doc.insertString(doc.getLength(), chunk.text + " ", chunk.style);
}
} catch (BadLocationException e) {
}
JFrame frame = new JFrame("Test");
frame.getContentPane().add(textPane);
frame.pack();
frame.setVisible(true);
}
private ArrayList<Chunk> getColorsBasedOnText(String text, JTextPane textPane) {
ArrayList<Chunk> chunks = new ArrayList<Chunk>();
for (String word: text.split(" ")) {
Chunk chunk = new Chunk();
chunk.text = word;
Color color = myMap.get(word.toLowerCase());
if (color != null) {
chunk.style = textPane.addStyle("Style", null);
StyleConstants.setForeground(chunk.style, color);
}
chunks.add(chunk);
}
return chunks;
}
private class Chunk {
public String text;
public Style style;
}
当我在JTextPane图形用户界面中编写单词时,有没有办法让单词的颜色发生变化?因为在我运行该程序并再次写入“绿色”一词后,它不会变为绿色。这实际上是我想要做的。对不起,如果我没有更好地解释它。 –
您应该能够在创建它之后对JTextPane进行样式设置。这一次只是为了保持这个例子简短而甜蜜。您可能需要重新包装框架... – Chewy