gpt4 book ai didi

java - 每当我在 JTextPane 中写入特定单词时指定文本颜色

转载 作者:行者123 更新时间:2023-12-02 03:33:20 25 4
gpt4 key购买 nike

有没有办法指定我编写文本时希望文本具有的颜色?假设我将“Apple”设置为红色。如果我在 JTextPane 中写下“this Apple is good Apple”,则单词“apple”应该变成红色。

这是我到目前为止所拥有的,但它只是显示全黑。我想写Apple显示为红色

public static void main(String[] args) {
JTextPane textPane = new JTextPane();
//Would like to make the words Apple Red in foreground color
textPane.setText("this Apple is good Apple");


JFrame frame = new JFrame("Test");
frame.getContentPane().add(textPane);
frame.pack();
frame.setVisible(true);
}

最佳答案

这是使用单词到颜色的映射的解决方案。如您所见,我将 apple 映射为红色,将单词 green 映射为绿色

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;
}

关于java - 每当我在 JTextPane 中写入特定单词时指定文本颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37768088/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com