Solved

How to set text color in JTextArea

Posted on 2004-04-06
17
3,006 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Salesforce Has Never Been Easier

Improve and reinforce salesforce training & adoption using WalkMe's digital adoption platform. Start saving on costly employee training by creating fast intuitive Walk-Thrus for Salesforce. Claim your Free Account Now

 

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
 

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

Salesforce Has Never Been Easier

Improve and reinforce salesforce training & adoption using WalkMe's digital adoption platform. Start saving on costly employee training by creating fast intuitive Walk-Thrus for Salesforce. Claim your Free Account Now

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
map related example 6 59
tomcat startup error 5 136
type mismatch (Object[] to double[] 4 41
Problem to Alipay 10 72
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
In this post we will learn different types of Android Layout and some basics of an Android App.
The viewer will learn how to implement Singleton Design Pattern in Java.
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

730 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