Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

How to set text color in JTextArea

Posted on 2004-04-06
17
Medium Priority
?
3,053 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
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 

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

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

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

Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.
Suggested Courses

604 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