I think, as far as I guess, you need something other than JTextArea, so you can show different things in different colors. Well, this can be done using JTextPane or JEditorPane.
Here I provide you with a simple example of how to provide JTextPane with the specified print message and the color of this message.
You can change colors for any input text so that it can display different colors for each word.
// This is in javax.swing.JTextPane; JTextPane tPane = new JTextPane(); /* Method to put text in this textPane with colour of your choice * For this you need these classes. * import javax.swing.text.AttributeSet; * import javax.swing.text.SimpleAttributeSet; * import javax.swing.text.StyleConstants; * import javax.swing.text.StyleContext; */ protected static void appendToPane(String msg, Color c,String f) { StyleContext sc = StyleContext.getDefaultStyleContext(); AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, c); aset = sc.addAttribute(aset, StyleConstants.FontFamily, f); int len = tPane.getDocument().getLength(); tPane.setCaretPosition(len); tPane.setCharacterAttributes(aset, false); tPane.replaceSelection(msg); }
So, if you call it appendToPane("HI", Color.RED, "Lucida Console") it will display the HI in red with the specified font. and if you call the word appendToPane(" THERE", Color.BLACK, "TIMES NEW ROMAN") then it will be printed in black in the same place next to Hi.
Gagandeep bali
source share