有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在键入时重新存储单词

我想编写一个程序,我会记住一些特定的单词

像这样:

嘿,我喜欢带骨头的胡萝卜

我想让胡萝卜在打字时自动变蓝。 哇,我是用代码做的吗

我已经试过了:

public void getWord(String whatword){
   if(jtextarea.contains(whatword){
      //Stuck on here
     }  

例如: 如果我键入以下内容:

我喜欢胡萝卜和金枪鱼

我想把胡萝卜和金枪鱼的颜色改成蓝色。 其他的词需要保持黑色

现在我不知道如何回忆这个词,这个if语句是否有效。 那么,我该如何解决这个问题呢

对不起,我是荷兰人,所以我想你需要用这种语言


共 (1) 个答案

  1. # 1 楼答案

    一个JTextArea只能包含纯文本,不能给某些单词上色。如果希望能够为不同的单词着色,则需要使用JTextPaneJEditorPane

    有关更多信息,请参阅此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。如果word为"Hello",它将以红色显示,否则将以蓝色显示