We help IT Professionals succeed at work.

How to set text color in JTextArea

chenwei
chenwei asked
on
Medium Priority
5,698 Views
Last Modified: 2008-03-17
My code looks as follow:

...
...
   jTextArea_EventMsg.append(myText + newline);
...
I want to set the color of myMext and then append it to the JTextArea. Is it possible or should I use another component?
Comment
Watch Question

Commented:
If you want the text area to display its text using multiple fonts or other styles, you should use an editor pane or text pane

Commented:
If the displayed text has a limited length and is never edited by the user, consider using a label instead.

Commented:
Ok, if you only use one type of  style you can use jtextarea.


textArea.setFont(new Font("Serif", Font.ITALIC, 16));
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
CERTIFIED EXPERT
Top Expert 2016

Commented:
The easiest way is to use a JEditorPane instead and use html

jEditorPane_EventMsg.append("<font color=\"red\">myText</font><br>");
JTextArea area = new JTextArea();
area.setForeground(Color.blue);

This is for single color.

If you want to go for multiple colors... then you have to use editor pane.

Author

Commented:
To CEHJ,

JTextEditorPane has no member of append(), right?

Author

Commented:
By the way, I have to put out the text line after line, not just only one line.

Commented:
JTextPane is a subclass of JEditorPane that uses a StyledEditorKit and StyledDocument, and provides cover methods for interacting with those objects.

In the link that I indicated in a previous message you will be able to find examples on this topic.
CERTIFIED EXPERT
Top Expert 2016

Commented:
>>JTextEditorPane has no member of append(), right?

Yes, that's right sorry.

You can do, get/setText
Mayank SPrincipal Technologist
CERTIFIED EXPERT

Commented:
I prefer:

String sCurrentText = jepMessage.getText () ; // jepMessage is the JEditorPane
jepMessage.setText ( sCurrentText.substring ( 0, sCurrentText.lastIndexOf ( "</body>" ) ) + yourString + "</BODY></HTML>" ) ;

// yourString can contain anything like: "<font color=\"red\">myText</font><br>"
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;
import javax.swing.text.DefaultStyledDocument;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;

public class ColorJTextArea extends JFrame implements ActionListener
{
      private DefaultStyledDocument doc ;
      private StyleContext sc ;
      private JTextField field ;
      private JTextPane p;
      
      public ColorJTextArea()
      {
            super();
            
            initialize();
      }
      
      private void initialize()
      {
            JPanel panel = (JPanel)getContentPane();
            panel.setLayout(new FlowLayout());
            
            sc = new StyleContext();
            doc = new DefaultStyledDocument(sc);
            
            p = new JTextPane(doc);
            
            p.setPreferredSize(new Dimension(100,100));
            
            
            panel.add(p);
            
            JButton colorButton = new JButton("Set color");
            colorButton.addActionListener(this);
            
            field = new JTextField(10);
            
            panel.add(field);
            panel.add(colorButton);
            
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            
            setSize(300,300);
            setVisible(true);
      }
      
      public void actionPerformed(ActionEvent e)
      {
            String color = field.getText();
            Style style = sc.addStyle(null, null);
            boolean canSet = false;
            
            if ("red".equalsIgnoreCase(color))
            {
                  StyleConstants.setForeground(style, Color.red);
                  canSet = true;
            }
            else if ("blue".equalsIgnoreCase(color))
            {
                  StyleConstants.setForeground(style, Color.blue);
                  canSet = true;
            }
            else if ("green".equalsIgnoreCase(color))
            {
                  StyleConstants.setForeground(style, Color.green);
                  canSet = true;
            }
            
            if (canSet)
                  p.setCharacterAttributes(style, false);
      }
      
      public static void main(String[] args)
      {
            new ColorJTextArea();
      }
}

Author

Commented:
Thanks for the information from all sites. I feel there is some what confucious. Maybe I haven't explained my question clear? What my programm does is to watch a process liek a watch dog. If it gets a warning, it will print out a warning message onto the TextPane or something else, if it gets an error, it will print out an error message such like:

while(stop == false)
{
...
...
   result = check_process();
   if(result == warning)
     print_warning(color.yellow);
   if(result == error)
     print_error(color.red);
   if(result == ok)
     print_ok(color.green);
...
...
}

I find the append()-function is what I want sine I don't want to overwrite the output text before. But what a pity it's unter JTextArea.

I hope I've explained my question mire clearer this time.
Mayank SPrincipal Technologist
CERTIFIED EXPERT

Commented:
You can write your own append () method and use it for JEditorPane. You can either sub-class JEditorPane and make your own class with an append () method, or in your container (JPanel, JFrame, whatever), you can use this:

public void append ( String sMessage, Color col )
{
  // make an HTML string-message: sDisplayMessage = "<FONT COLOR=\"" + .... // based on the 'col'

  // Let jepMessage be the JEditorPane
  String sCurrentText = jepMessage.getText () ;
  jepMessage.setText ( sCurrentText.substring ( 0, sCurrentText.lastIndexOf ( "</body>" ) ) + sDisplayMessage + "</BODY></HTML>" ) ;

}

Author

Commented:
I've solved the problem myself. My code lokks as follow:
...
...
        javax.swing.text.StyledDocument doc = jTextPane1.getStyledDocument();
       // Makes text red
                // Create a style object and then set the style attributes
        javax.swing.text.Style style = doc.addStyle("StyleName", null);
        // Foreground color
        javax.swing.text.StyleConstants.setForeground(style, Color.blue);
        // Append to document
        try{
        doc.insertString(doc.getLength(), text + newline, style);
        }
        catch (javax.swing.text.BadLocationException e) {
        }
...
...

Please don't answer this question anymore.
Unlock this solution and get a sample of our free trial.
(No credit card required)
UNLOCK SOLUTION
Unlock the solution to this question.
Thanks for using Experts Exchange.

Please provide your email to receive a sample view!

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.