Java: How to I change the color of a specific line or row of string in a Text area?

Kevin picture Kevin · Jan 11, 2011 · Viewed 32.2k times · Source

the one way I could change the color is by setForground(). However when there are multiple lines of code it makes everything green or black. Is there another method or any way of solving this problem? Thanks!

int key = evt.getKeyCode();
    if (key == KeyEvent.VK_ENTER)
    {
       String tb1EnterdValue = tb1.getText().toString();
       if((tb1EnterdValue.equals("yes")) )
        {
            TextArea1.setForeground(Color.green);
    else
        {
              TextArea1.setForeground(Color.lightGray);
        }
       this.TextArea1.append(">"+tb1EnterdValue+newline);
       this.tb1.setText("");

Answer

camickr picture camickr · Jan 11, 2011

I would use a JTextPane with "attributes" (not HTML) for changing the text color. The section from the Swing tutorial on Text Component Features has a working examples to get you started.

I've tried JTextPanes before but they won't let me use append() method

The append() method is just a convenience method that allows you to add text to the end of the Document. You can implement you own append() method for a JTextPane as well. Just look at the source code for JTextArea and copy the code from its append() method.