這是一個使用單詞到顏色映射的解決方案。正如你所看到的,我映射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