다음은 색상에 대한 단어 맵을 사용하는 솔루션입니다. 당신이 볼 수 있듯이, 나는 빨간색과 감사
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 GUI에서 단어를 쓸 때 단어 색상을 변경하는 방법이 있습니까? 프로그램을 실행하고 "녹색"이라는 단어를 다시 쓰면 녹색으로 변하지 않기 때문입니다. 그것은 실제로 내가하려고하는 것입니다. 미안하지만 내가 더 잘 설명하지 못한다면. –
JTextPane을 만든 후에 스타일을 지정할 수 있어야합니다. 예제를 짧고 다정하게 유지하기 위해 한 번에 모든 것이 있습니다. 프레임을 다시 포장해야 할 수도 있습니다 ... – Chewy