Solved

How to set text color in JTextArea

Posted on 2004-04-06
17
2,978 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?
0
Comment
Question by:chenwei
  • 5
  • 4
  • 2
  • +3
17 Comments
 

Expert Comment

by:RobCSP
ID: 10764139
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
0
 

Expert Comment

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

Expert Comment

by:RobCSP
ID: 10764158
0
 

Expert Comment

by:RobCSP
ID: 10764166
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);
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 10764172
The easiest way is to use a JEditorPane instead and use html

jEditorPane_EventMsg.append("<font color=\"red\">myText</font><br>");
0
 
LVL 9

Expert Comment

by:mmuruganandam
ID: 10764173
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.
0
 

Author Comment

by:chenwei
ID: 10764254
To CEHJ,

JTextEditorPane has no member of append(), right?
0
 

Author Comment

by:chenwei
ID: 10764267
By the way, I have to put out the text line after line, not just only one line.
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 

Expert Comment

by:RobCSP
ID: 10764311
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.
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 10764346
>>JTextEditorPane has no member of append(), right?

Yes, that's right sorry.

You can do, get/setText
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 10764393
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>"
0
 
LVL 9

Expert Comment

by:mmuruganandam
ID: 10764461
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();
      }
}

0
 

Author Comment

by:chenwei
ID: 10764522
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.
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 10764561
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>" ) ;

}
0
 

Author Comment

by:chenwei
ID: 10765202
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.
0
 

Accepted Solution

by:
ee_ai_construct earned 0 total points
ID: 10988420
PAQed, with points refunded (30)

ee_ai_construct - (re-order part number #xm34)
Community Support Moderator
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
splitOdd10 challenge 5 74
HashMap Vs TreeMap 12 55
starter POM and spring-boot-starter,  spring-boot-web 2 40
javap bin 2 24
For customizing the look of your lightweight component and making it look opaque like it was made of plastic.  This tip assumes your component to be of rectangular shape and completely opaque.   (CODE)
Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…

932 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now