Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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("");
like image 382
Kevin Avatar asked Jan 11 '11 03:01

Kevin


People also ask

How to set textArea in Java?

java . The following code creates and initializes the text area: textArea = new JTextArea(5, 20); JScrollPane scrollPane = new JScrollPane(textArea); textArea. setEditable(false);

What is JTextArea in Java?

A JTextArea is a multi-line area that displays plain text. It is intended to be a lightweight component that provides source compatibility with the java. awt. TextArea class where it can reasonably do so.


1 Answers

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.

like image 160
camickr Avatar answered Nov 15 '22 00:11

camickr