2014-08-29 61 views
-3

我正在为代码编辑器编写脚本,我想要动态命令。如何动态更改JTextArea中的字体颜色?

所以,如果用户键入“class”,它将改变“class”的颜色。

我该怎么做?

// This is the main focus part of the code. 

textarea.addKeyListener(new KeyAdapter() { 
     public void keyPressed(KeyEvent evt) { 
      word += evt.getKeyChar(); 

      if(evt.getKeyCode() == KeyEvent.VK_ENTER) { 
       word = ""; 
       line = ""; 
       lineInMemory = line; 
      } 

      if(evt.getKeyCode() == KeyEvent.VK_SPACE) { 
       word = word.replaceAll("null",""); 
       line += word; 
       word = ""; 
       String text = textarea.getText(); 
       String[] words = line.split(" "); 

       if(word.toLowerCase().equals("class")) { 

        // What the heck do I put here?! 

       }  
      } 
     } 
    }); 

我已经拥有了读键的关键听众,将它们放入单词中,然后将单词放入句子中。我希望它能够输入关键字,并且它在键入时会自动更改关键字的颜色,有点像Sublime Text的功能。

+0

欢迎来到StackOverflow,我们不是您可能会看到的代码工厂。您应该发布您的代码或至少一个[最小示例](http://stackoverflow.com/help/mcve),以便我们可以复制粘贴并帮助您。如果你没有表现出任何努力来解决它,那么我认为任何人都不会试图用这个来帮助你。 – Frakcool 2014-08-29 17:16:36

+0

是的,我正在编辑文章,因为你发布它。谢谢! – mgthomas99 2014-08-29 17:21:35

回答

1

A JTextArea仅用于包含纯文本,并且不能颜色某些单词。如果您想要为不同的单词着色,则需要使用JTextPaneJEditorPane

欲了解更多信息,请参阅此question。这question可能也有帮助(尤其是第二个答案)。

下面是一个例子:

JTextPane textPane = new JTextPane(); 
StyledDocument doc = textPane.getStyledDocument(); 

Style style = textPane.addStyle("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",它将显示为红色,否则将显示为蓝色。

+0

谢谢你,但它似乎是抛出一个错误。错误出现在你提交的代码的第5行,它表示“StyleConstants.setForeground(style,Color.red);”我不知道为什么。我可能错过了一些显而易见的东西,但我对GUI编程相对较新。有什么建议么? – mgthomas99 2014-08-29 18:08:41

+0

究竟是抛出的错误是什么? – Zach 2014-08-29 19:17:45

+0

异常在线程“主要” java.lang.Error的:未解决的编译问题: \t令牌(S)语法错误,错位构建体 \t令牌语法错误“(”删除此令牌 \t语法错误上令牌“)”,无效VariableDeclarator – mgthomas99 2014-08-29 19:23:46