Solved

How to set text color in JTextArea

Posted on 2004-04-06
17
2,967 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
How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

 

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:mayankeagle
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:mayankeagle
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

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
pairstar challenge 2 42
endX challenge 2 50
java set up 1 46
Java and GPO 11 47
By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
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 will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…

758 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

21 Experts available now in Live!

Get 1:1 Help Now