How to display text in different colors in JEditorPane

I think you better forget about the JTextField and start thinking in JEditorPane and JTextPane. They support differents fonts. A JTextField will let you change the color but for all the text within.

http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/JEditorPane.html
http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/JTextPane.html

Once you have a JEditorPane or JTextPane (now I don't remember them to suggest wich one) get the document (getDocument) or better set your own Document, an heir of StyledDocument and try the insertString method and the setCharacterAttributes.

You wil have to read the classes:
AttributeSet http://java.sun.com/j2se/1.4.2/docs/api/javax/print/attribute/AttributeSet.html
SimpleAttributeSet http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/text/SimpleAttributeSet.html
MutableAttributeSet http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/text/MutableAttributeSet.html
StyleConstants http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/text/StyleConstants.html
StyledDocument http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/text/StyledDocument.html


You could use JEditorPane as previously mentioned. JEditorPane can interpret html. So, you could insert<font color=\"color\"> tags to format the text as you like. JEditorPane I think is the way to go as it gives you all the flexibility html has to offer.


I don't like the html idea. It would overload de JEditorPane and make it slow down. I think the idea is the StyledDocument with the insertString and setCharacterAttributes methods. You may consult also the AttributeSet, SimpleAttributeSet, MutableAttributeSet & StyleConstants classes.