2

Possible Duplicate:
Highlighting few of the words of a text file opened in a frame

I am finding a string in JTextArea and once that string is found, I want to highlight that string with some color. I have been searching internet for finding a solution but couldn't find an answer.

How can I highlight a string in JTextArea?

Community
  • 1
  • 1
Alfred
  • 1,543
  • 7
  • 33
  • 45
  • 3
    Have a look at [this](http://stackoverflow.com/questions/13437865/java-scroll-to-specific-text-inside-jtextarea/13438455#13438455) and [this](http://stackoverflow.com/questions/13448558/highlight-a-word-in-jeditorpane/13449000#13449000) then – MadProgrammer Dec 10 '12 at 05:49
  • 1
    `JTextArea` is for plain text (all one font, style & color). for styled text use a `JEditorPane` or `JTextPane` instead. – Andrew Thompson Dec 10 '12 at 07:45
  • 1
    See [here](http://stackoverflow.com/a/12482171/1133011) and [here](http://stackoverflow.com/questions/13478892/highlighting-the-word-in-java/13480123#13480123) for some examples. +1 @MadProgrammer for his examples too :) – David Kroukamp Dec 10 '12 at 08:47
  • 1
    @AndrewThompson Or you could cheat and use text selection :P – MadProgrammer Dec 10 '12 at 09:19
  • @MadProgrammer Yes, I checked out your clever example a while ago. +1 – Andrew Thompson Dec 10 '12 at 09:36
  • @MadProgrammer Awesome Man. Very clever solutions. Hats off :P – Alfred Dec 10 '12 at 11:02

1 Answers1

2

You would need to use a Highlighter for that. This Oracle tutorial should put you on the right track.

EDIT:

entry.getDocument().addDocumentListener(this);: This attaches the current class as an event handler for the particular object. It is highly likely that you can do without this line of code.

hilit.addHighlight(index, end, painter);: This should highlight the text.

entry.setBackground(entryBg);: Sets the background to the given item.

I would recommend you copy the code written in the tutorial and start from there.

npinti
  • 51,780
  • 5
  • 72
  • 96
  • Thanks. Can you please tell me what does the following lines of code doing: entry.getDocument().addDocumentListener(this); hilit.addHighlight(index, end, painter); textArea.setCaretPosition(end); entry.setBackground(entryBg); – Alfred Dec 10 '12 at 10:51
  • @Alfred: I have modified my answer. I am afraid that not much can be done other than you having to gets your hands dirty :) – npinti Dec 10 '12 at 13:56