Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

set color of just one specific word into the text area.

 
rohit rusty
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello friends,

i am trying to develop an application and i need to change the color of a particular word in the same TextArea from which it is being read. i have gotten this far :

for(int i = 0;i < inWord.length; i++){ //inWord is a Strin[] having the words that the user has written into the TextArea i.e. txtInput
if((lookup = (String) list.get(inWord[i])) == null){ //to check if the word is present or not, if not present
txtInput.setForeground(Color.red); // change the foreground color
txtInput.replaceRange(inWord[i],startPos,startPos+inWord[i].length()); //and replace the word at the correct position in the TextArea i.e. txtInput with changed color
break;
}
else
startPos = startPos + inWord[i].length()+1; // else find the position of where to replace.
}



the problem, that you all might have guessed by now, is once i use the setForeground() method.... the foreground color of entire TextArea changes to red. whereas i just want to change the color of the word that i am inserting.
Also if there are any methods to directly change the color a particular word in the TextArea without reading it and reinserting it.
please help.

rohitrusty314.
 
Rob Camick
Ranch Hand
Posts: 2610
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You should use a JTextPane.

See Text Component Features for a working example.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic