Solved

Change textArea color

Posted on 2001-08-19
32
428 Views
Last Modified: 2007-12-19
I am writing simple chatting program to put in my web server, in my chat client program, i have problem to make the different text color for incomming and outgoing message.i try to use setforegroup method, but this is not working,because it will change the whole message instead of differential the 2 message.Please kindly help.
0
Comment
Question by:belim
  • 10
  • 8
  • 7
  • +5
32 Comments
 
LVL 9

Expert Comment

by:yongsing
ID: 6403735
Use JEditorPane class instead. It allows you to use HTML as its contents. Example:

JEditorPane editorPane = new JEditorPane();
editorPane.setContentType("text/html");
editorPane.setText("<font color=\"ff0000\"><b>Red</b></font>");
0
 
LVL 92

Expert Comment

by:objects
ID: 6404573
None of the AWT support what you want to do.
If using Swing is an option to you, then Swing provides some support.
0
 
LVL 3

Expert Comment

by:Sendoh
ID: 6404816
hi !! objects are right...
please check out this sites for more detail on swing...:P
(example included...)

http://java.sun.com/docs/books/tutorial/uiswing/components/simpletext.html

hope it helps...;)
0
 
LVL 9

Expert Comment

by:Ovi
ID: 6405051
I believe is easy to create your own "text area" AWT component by extending Canvas for example. You will use then the paint() method and draw directly on the graphics object the messages.

............
public class SmartTextArea extends Canvas {
final int INCOMING_TYPE = 1;
final int OUTGOING_TYPE = 2;
final int OTHER_TYPE = 3;
public Vector messages = new Vector();

public void append(String message, int type) {
  type = (type != INCOMING_TYPE || type != OUTGoING_TYPE )?OTHER_TYPE:type;
  Message m = new Message(message, type);
  messages.addElement(m);
  repaint();
}

public void paint(Graphics g) {
  int lastY = 20;
  for(int i = 0; i<messages.size(); i++) {
    Message m = (Message) messages.elementAt(i);
    g.setColor(m.color);
    g.drawString(m.message, 5, lastY);
    lastY += 20;
  }
}

class Message {
  String message;
  int type;
  Color color;

  public Message(String m, int t) {
    message = m;
    type = t;
    switch(type) {
      case INCOMING_TYPE :
        color = Color.red;
        break;
      case OUTGOING_TYPE :
        color = Color.blue;
        break;
      case OTHER_TYPE :
        color = Color.gray;
        break;
    }
  }
}
}

This code is not optimized but I think is a good start if you are interested in it.

Good luck.
0
 

Author Comment

by:belim
ID: 6405168
I have tried the JEditorPane, it works fine,but my question now is do it support appendText method, which exist in the AWT component? the setText method will overwrite the text.Please Advice......
0
 
LVL 9

Expert Comment

by:yongsing
ID: 6405230
>> the setText method will overwrite the text.

I guess you can append your text to a StringBuffer, and then call setText() with the content of StringBuffer.
0
 
LVL 7

Expert Comment

by:tomboshell
ID: 6405302
If your class is extending the JEditorPane then just write your own setText(String text) method.  I did it by including a boolean value as a parameter.

setText(String text, boolean append){
  String temp=new String();
  if(append){
    temp=this.getText();
    temp+=text;
    this.super().setText(temp);
  }
  else this.super().setText(text); //the boolean must be false..
}

You can do it with a StringBuffer too, the idea is to get all the text and then set all the text.  

Tom
0
 
LVL 92

Expert Comment

by:objects
ID: 6405312
It sounds like you'd be better off using a JList with a custom renderer, rather than JEditorPane.

Is the text edittable?
0
 
LVL 9

Expert Comment

by:Ovi
ID: 6405336
JEditorPane has associated an Document object. In that document Object you have a method called insertString(...).

Now if you are displaying html in the JEditorPane, the associated document is HTMLDocument, where you have a couple of insert methods.

All you have to do is to set the caret position to the end of the document for correct scrolling :

int pos = editorPane.getDocument().getLength();
editorPane.setCaretPosition(pos - 1);

and call the appropiate insert method :

editorPane.getDocument().insert...(pos, ...);


And that's all.
0
 

Author Comment

by:belim
ID: 6406105
My main purpose is to differential the incomming and outgoing message color, if i stored the message in the strinbuffer and setText again, then the whole message in the JEditorPane will in the same color.This does not carry any point.
   Ovi, your method should able to work, but in the insertString method, it required AttributeSet as a parameter, i cannot understand what is attributeset, what should i put for this parameter? please kindly give some full code example.

Thanks
0
 
LVL 92

Expert Comment

by:objects
ID: 6407998
Definitely sounds like a job for a JList and not a JEditorPane.
0
 

Author Comment

by:belim
ID: 6408339
object, any example for JList, so i can make a comparison in between them and learn up in the faster pace,So sorry for always ask an example here, as i am a beginner in Java and have limited source to learn.
0
 

Author Comment

by:belim
ID: 6412180
OVI,
 i am waiting for your feedback,thanks!
0
 
LVL 9

Expert Comment

by:yongsing
ID: 6412396
I think using JList is better, as suggested by object. If you want to delete away earlier messages, then it's easier done with a JList than JEditorPane. The default cell renderer for a JList is a JLabel. That is, each row of a JList is a JLabel. Since you can have HTML in JLabel, it means that you can set different font and color for each message.
0
 
LVL 92

Expert Comment

by:objects
ID: 6412517
Have a look at Sun's tutorial:
http://java.sun.com/docs/books/tutorial/uiswing/components/list.html

Basically what you do is keep your messages in a list which is then displayed by the JList.
You'll need to develop a custom list renderer for displaying your messages. Basically the list renderer is used to display each individual list entry.
Here's a starting point for you that simply changes the background colour according to the list entry.

public class MyListCellRenderer
   extends DefaultListCellRenderer
{
   public Component getListCellRendererComponent(
      JList list, Object value,
      int index, boolean isSelected, boolean hasFocus)
   {
       Component result =
          super.getListCellRendererComponent(
            list, value, index, isSelected, hasFocus);
       result.setBackground(getColorFor(value));
       return result;
   }
   private Color getColorfFor(Object value)
   {
     // Return the background color for this entry
   }

}

0
 

Author Comment

by:belim
ID: 6420636
YongSing,
 any example in Jlist while i am trying the code from Ovis?
0
Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

 
LVL 92

Expert Comment

by:objects
ID: 6420641
There are good examples in the Sun tutorial link I gave above.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;

public class ListDemo extends JFrame
                      implements ListSelectionListener {
    private JList list;
    private DefaultListModel listModel;

    private static final String hireString = "Hire";
    private static final String fireString = "Fire";
    private JButton fireButton;
    private JTextField employeeName;

    public ListDemo() {
        super("ListDemo");

        listModel = new DefaultListModel();
        listModel.addElement("Alison Huml");
        listModel.addElement("Kathy Walrath");
        listModel.addElement("Lisa Friendly");
        listModel.addElement("Mary Campione");

        //Create the list and put it in a scroll pane
        list = new JList(listModel);
        list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        list.setSelectedIndex(0);
        list.addListSelectionListener(this);
        JScrollPane listScrollPane = new JScrollPane(list);

        JButton hireButton = new JButton(hireString);
        hireButton.setActionCommand(hireString);
        hireButton.addActionListener(new HireListener());

        fireButton = new JButton(fireString);
        fireButton.setActionCommand(fireString);
        fireButton.addActionListener(new FireListener());

        employeeName = new JTextField(10);
        employeeName.addActionListener(new HireListener());
        String name = listModel.getElementAt(
                              list.getSelectedIndex()).toString();
        employeeName.setText(name);

        //Create a panel that uses FlowLayout (the default).
        JPanel buttonPane = new JPanel();
        buttonPane.add(employeeName);
        buttonPane.add(hireButton);
        buttonPane.add(fireButton);

        Container contentPane = getContentPane();
        contentPane.add(listScrollPane, BorderLayout.CENTER);
        contentPane.add(buttonPane, BorderLayout.SOUTH);
    }

    class FireListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            //This method can be called only if
            //there's a valid selection
            //so go ahead and remove whatever's selected.
            int index = list.getSelectedIndex();
            listModel.remove(index);

            int size = listModel.getSize();

            if (size == 0) {
            //Nobody's left, disable firing.
                fireButton.setEnabled(false);

            } else {
            //Adjust the selection.
                if (index == listModel.getSize())//removed item in last position
                    index--;
                list.setSelectedIndex(index);   //otherwise select same index
            }
        }
    }

    //This listener is shared by the text field and the hire button
    class HireListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {

            //User didn't type in a name...
            if (employeeName.getText().equals("")) {
                Toolkit.getDefaultToolkit().beep();
                return;
            }

            int index = list.getSelectedIndex();
            int size = listModel.getSize();

            //If no selection or if item in last position is selected,
            //add the new hire to end of list, and select new hire.
            if (index == -1 || (index+1 == size)) {
                listModel.addElement(employeeName.getText());
                list.setSelectedIndex(size);

            //Otherwise insert the new hire after the current selection,
            //and select new hire.
            } else {
                listModel.insertElementAt(employeeName.getText(), index+1);
                list.setSelectedIndex(index+1);
            }
        }
    }

    public void valueChanged(ListSelectionEvent e) {
        if (e.getValueIsAdjusting() == false) {

            if (list.getSelectedIndex() == -1) {
            //No selection, disable fire button.
                fireButton.setEnabled(false);
                employeeName.setText("");

            } else {
            //Selection, update text field.
                fireButton.setEnabled(true);
                String name = list.getSelectedValue().toString();
                employeeName.setText(name);
            }
        }
    }

    public static void main(String s[]) {
        JFrame frame = new ListDemo();

        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });

        frame.pack();
        frame.setVisible(true);
    }
}

0
 

Author Comment

by:belim
ID: 6474747
It doesn't work at all, anyone still wan to comment???
else i can say nobody know how to answer this question, and i will delete it,as it pending here for quite some time
0
 
LVL 92

Expert Comment

by:objects
ID: 6475445
How can we comment if u don't tell us you're having problems.
The list demo I posted works fine here, what problem are u having with it?
0
 

Author Comment

by:belim
ID: 6475511
Objects,
  My question is very simple,as i need to use JEditorPane
to change the text color with append mode,Jlist seems not fit my requirement at all.Please advice with example how to change text color in JEditorPane by using append mode which enable me to insert a new text into the editor.
0
 
LVL 92

Expert Comment

by:objects
ID: 6475541
Why doesn't JList meet your needs?
I've used it in the past to do similar things that u need.
0
 
LVL 9

Expert Comment

by:Ovi
ID: 6475790
Sorry. our mail server was down, here is a good start app for using AttributeSet. I didn't read all the comments, I will participate soon.

import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.text.*;

public class CodeEditor extends JFrame {
  protected String[] defaults =  {
    "import blue true false false this_is_import_tooltip",
    "class red false true false this_is_class_tooltip",
    "Button green true true true this_is_button_tooltip"
    };
  protected Vector tokens;
  protected JTextPane editor;
  protected DefaultStyledDocument doc;
  protected StyledEditorKit kit;
  protected Vector content;

  public CodeEditor() {
    init();
  }

  private void init() {
    setSize(500, 500);
    setLocation(350, 100);
    createEditor();
    createTokens();
    getContentPane().add(new JScrollPane(editor), BorderLayout.CENTER);
  }

  private void createEditor() {
    editor = new JTextPane();
    doc = new DefaultStyledDocument();
    kit = new StyledEditorKit();
    editor.setEditorKit(kit);
    editor.setDocument(doc);
    editor.addKeyListener(new EditorKeyAdapter());
    editor.setToolTipText("Dummy");
  }

  private void createTokens() {
    tokens = new Vector();
    for(int i=0; i<defaults.length; i++) {
      StringTokenizer st = new StringTokenizer(defaults[i]);
      String name = st.nextToken();
      String color = st.nextToken();
      String bold = st.nextToken();
      String italic = st.nextToken();
      String underline = st.nextToken();
      String tip = st.nextToken();
      Token t = new Token();
      t.name = name;
      t.color = getColor(color);
      t.bold = (bold.equalsIgnoreCase("true"))?true:false;
      t.italic = (italic.equalsIgnoreCase("true"))?true:false;
      t.underline = (underline.equalsIgnoreCase("true"))?true:false;
      t.tip = tip;
      tokens.addElement(t);
    }
  }

  private Color getColor(String color) {
    if(color.equalsIgnoreCase("red"))
      return(Color.red);
    else if(color.equalsIgnoreCase("blue")) {
      return(Color.blue);
    } else if(color.equalsIgnoreCase("green")) {
      return(Color.green);
    }
    return(Color.black);
  }

  public void setContent(String c) {
    content = new Vector();
    boolean matched = false;
    StringTokenizer st = new StringTokenizer(c);
    while(st.hasMoreTokens()) {
      matched = false;
      String tmp = st.nextToken();
      for(int i=0; i<tokens.size(); i++) {
        if(tmp.equalsIgnoreCase(((Token) tokens.elementAt(i)).name)) {
          content.addElement(tokens.elementAt(i));
          matched = true;
          break;
        }
      }
      if(!matched) {
        Token t = new Token();
        t.name = " " + tmp + " ";
        t.color = Color.black;
        t.bold = false;
        t.italic = false;
        t.underline = false;
        content.addElement(t);
      }
    }
    for(int i=0; i<content.size(); i++) {
      insertText((Token) content.elementAt(i));
    }
  }

  private void insertText(Token token) {
    MutableAttributeSet attr = new SimpleAttributeSet();
    StyleConstants.setBold(attr, token.bold);
    StyleConstants.setItalic(attr, token.italic);
    StyleConstants.setUnderline(attr, token.underline);
    StyleConstants.setForeground(attr, token.color);
//    System.out.println("length" + doc.getLength());
    try {
      if(token.name.equalsIgnoreCase(" \\n "))
        doc.insertString(doc.getLength(), "\n", attr);
      else
        doc.insertString(doc.getLength(), token.name, attr);
    } catch(BadLocationException ble) {}
  }

  class EditorKeyAdapter extends KeyAdapter {
    public void keyReleased(KeyEvent ke) {
      try {
        int curentPos = editor.getCaretPosition();
        String text = editor.getText(0, curentPos);
        int space = text.lastIndexOf(" ");
        space++;
        String token = text.substring(space);
        for(int i=0; i<tokens.size(); i++) {
          Token tmp = (Token) tokens.elementAt(i);
          if(tmp.name.equalsIgnoreCase(token)) {
            MutableAttributeSet attr = new SimpleAttributeSet();
            StyleConstants.setBold(attr, tmp.bold);
            StyleConstants.setItalic(attr, tmp.italic);
            StyleConstants.setUnderline(attr, tmp.underline);
            StyleConstants.setForeground(attr, tmp.color);
            editor.select(space, curentPos);
            editor.setCharacterAttributes(attr, false);
            editor.select(curentPos, curentPos);
            break;
          }
        }
      } catch(BadLocationException ble) {}
    }
  }

  class Token {
    public String name;
    public Color color;
    public boolean bold;
    public boolean italic;
    public boolean underline;
    public String tip;

    public Token() {
    }
  }

  public static void main(String args[]) {
    CodeEditor t = new CodeEditor();
    t.setVisible(true);
    String file =
    "import java.awt.*; \\n " +
    "import java.awt.color.*; \\n " +
    "\\n " +
    "public class Test extends JFrame { \\n " +
    " public Button justAnButton; \\n " +
    "\\n " +
    "      public Test() { \\n " +
    "        System.out.println(123); \\n " +
    "      } \\n " +
    "} \\n ";
    t.setContent(file);
  }
}
0
 
LVL 9

Expert Comment

by:Ovi
ID: 6475797
Ok, I'm "updated". The above code I have write it as a short example of implementing a sort of Java code editor, with specific colors and styles for specific tockens (keywords). You have there methods for insertion of  styled formated text using AttributeSet  - take a look to the method 'insertText'. If you have any question, feel free to ask.
0
 

Author Comment

by:belim
ID: 6476065
OVI,
  Thanks!for your response, i wil try it out and get back to you.....you deserve for the point.


Thanks!
0
 
LVL 9

Expert Comment

by:Ovi
ID: 6476074
oki :)
0
 
LVL 9

Expert Comment

by:Ovi
ID: 6478570
working ?
0
 

Author Comment

by:belim
ID: 6484966
Ovi,
  Soli for later reply.....
i am still figure out the problem.....please give me some time.....thanks!
0
 

Author Comment

by:belim
ID: 6487184
OVI,
  U got the point
0
 
LVL 9

Expert Comment

by:Ovi
ID: 6489452
the point or the points:) ?
0
 
LVL 9

Expert Comment

by:Ovi
ID: 6604776
You have forgot to graduate this question !!!!!!!!!! ... to someone ...
0
 
LVL 1

Expert Comment

by:Moondancer
ID: 6727991
This question is LOCKED with a Proposed Answer.  If it helps you, great, accept it and grade it to close.  If not, reject it and comment as to why or what else is needed.

Few additional experts will join this collaboration effort, once a question has been locked.  Just want to confirm this to you.  If more than one expert helps you, you can always split points or award additional help in a new question, within the same topic area.  If you need help from us, post a zero point question here, and include the link:

http://www.experts-exchange.com/jsp/qList.jsp?ta=commspt

Moondancer
Community Support Moderator @ Experts Exchange

P.S.  Double click your Member Profile, expand VIEW HISTORY to navigate and update all your open questions please.
0
 

Accepted Solution

by:
SpideyMod earned 0 total points
ID: 8289657
All,
I am unlocking this question in preparation for cleanup.  I will return in 7 days to finalize this question.  Please leave any recommendations for the final state of this question, I will take all recommendations into consideration.  Failing any feedback, I may decide in 7 days to delete or PAQ this question with no refund.  Thanks.

SpideyMod
Community Support Moderator @Experts Exchange
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
array220 challenge 8 46
groupSum6 challenge 6 35
word0 challenge 4 53
Free Alternative to JIRA 4 55
INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
Viewers learn about the “while” loop and how to utilize it correctly in Java. Additionally, viewers begin exploring how to include conditional statements within a while loop and avoid an endless loop. Define While Loop: Basic Example: Explanatio…
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:

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

20 Experts available now in Live!

Get 1:1 Help Now