Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Highlight sentence in textarea

Tags:

java

highlight

I have to write a program in which i have to highlight the sentence in JTextarea. I have one file called original file and summary file. Original file will be displayed in textarea box and i have to highlight all the sentences of a summary file in textarea box.

For example. If original file contains "Tendulkar was born in Bombay (now Mumbai). His mother Rajni worked in the insurance industry,and his father Ramesh Tendulkar, a Marathi novelist, named Tendulkar after his favourite music director, Sachin Dev Burman. Tendulkar's elder brother Ajit encouraged him to play cricket. Tendulkar has two other siblings: a brother Nitin, and sister Savita."

Above text is displayed in textarea.

In summary file i have "Tendulkar was born in Bombay (now Mumbai). Tendulkar has two other siblings: a brother Nitin, and sister Savita."

I want these sentences to be highlighted in textarea. Please can anyone tell me how can i do this? Thank you in advance :)

like image 742
Srikanth Avatar asked Dec 27 '22 20:12

Srikanth


2 Answers

You can use a Highlighter:

Highlighter h = textArea.getHighlighter();
h.removeAllHighlights();
int pos = originalText.indexOf(summaryText, 0);
h.addHighlight(pos ,
               pos  + summaryText.Length,
               DefaultHighlighter.DefaultPainter);
like image 159
manji Avatar answered Dec 30 '22 10:12

manji


According to The Java Tutorial:

JTextArea can display multiple lines of editable text. Although a text area can display text in any font, all of the text is in the same font. Use a text area to allow the user to enter unformatted text of any length or to display unformatted help information.

You may want to use JEditorPane and its subclass JTextPane to use rich text areas in Swing instead of plain JTextArea.

like image 41
acalypso Avatar answered Dec 30 '22 10:12

acalypso