我想编写一个程序,我会重新着色特定的单词。
像这样:
嘿,我喜欢带骨头的胡萝卜。
我想让胡萝卜在输入时自动显示,将其设为蓝色。 哇,我在代码中这样做吗?
我已经试过了:
public void getWord(String whatword){
if(jtextarea.contains(whatword){
//Stuck on here
}
例如: 如果我输入:
我喜欢胡萝卜和金枪鱼。
我想将胡萝卜和金枪鱼的颜色更改为蓝色。 其他词需要保持黑色。
现在我不知道如何给这个词重新着色,也不知道这个 if 语句是否有效。 那么,我该如何解决这个问题?
对不起,我是荷兰人,所以我想你需要用这种语言来做
最佳答案
JTextArea
仅用于包含纯文本,不能为某些单词着色。如果你想给不同的词涂上颜色,你需要使用 JTextPane或 JEditorPane .
有关详细信息,请参阅此 question .这question也可能有帮助
这是一个例子:
JTextPane textPane = new JTextPane();
StyledDocument doc = textPane.getStyledDocument();
Style style = textPane.addStyle("I'm a Style", null);
StyleConstants.setForeground(style, Color.red);
String word = "Hello";
if (word.equals("Hello") {
try {
doc.insertString(doc.getLength(), word, style);
} catch (BadLocationException ex) {
ex.printStackTrace();
}
} else {
StyleConstants.setForeground(style, Color.blue);
try {
doc.insertString(doc.getLength(), word, style);
} catch (BadLocationException e) {
e.printStackTrace();
}
}
这构成了一个字符串 word
。如果单词是"Hello"
,它将显示为红色,否则将显示为蓝色。
关于java - 键入时重新着色单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24851974/