Question

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("");
Was it helpful?

Solution

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.

OTHER TIPS

Is this Swing and are you using JTextAreas? If so, please be specific in your question, and then don't use a JTextArea since it isn't the ideal text component to use if you want to have multiple formats within one text component. Instead consider use of a JTextPane or JEditorPane. The tutorials will show you how to use these and when they should be used.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top