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

2

6

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("");
Galicia answered 11/1, 2011 at 3:46 Comment(0)
P
3

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.

Pozzuoli answered 11/1, 2011 at 4:9 Comment(3)
Thanks, but how exactly do I get the source code from JTextArea?Galicia
The source code comes with the JDK. Its in a file called src.zip.Pozzuoli
Where ever you want to use it.Pozzuoli
S
0

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.

Series answered 11/1, 2011 at 3:51 Comment(3)
yes it is a swing and JTextArea. I've tried JTextPanes before but they won't let me use append() method and I need to make each 'command' onto a new line.Galicia
Lack of append shouldn't prevent you from using the other text components as you could add text to the component's Document.Series
How do I do that? Because I need the cursor to make a new line after each entry into the text-whatever. Like is there any methods that's similar to append?Galicia

© 2022 - 2024 — McMap. All rights reserved.