javastringswingjtextareaswing-highlighter

Highlight a string according to given line number in JtextArea


Is there any function I can use to actually pass a line number and the string to highlight the word in that line number. I got no clue on how to achieve this.

Am able to load my File on the JtextArea.

The File am loading "Hello.txt" contains:

Hello, This
is my first
lesson in Java
Hope You Have a nice 
Time.

I want the function to highlight string "first" in line 1.

My Codes:

import javax.swing.*;  

import java.util.*;  

import java.io.*;  

public class OpenTextFileIntoJTextArea  
{  
public static void main(String[]args)  
{  
 try  
 {  

  FileReader readTextFile=new FileReader("C:\\Hello.py");  

  Scanner fileReaderScan=new Scanner(readTextFile);  

  String storeAllString="";  

  while(fileReaderScan.hasNextLine())  
  {  
   String temp=fileReaderScan.nextLine()+"\n";  

   storeAllString=storeAllString+temp;  
  }  
  JTextArea textArea=new JTextArea(storeAllString);  
  textArea.setLineWrap(true);  
  textArea.setWrapStyleWord(true);  
  JScrollPane scrollBarForTextArea=new JScrollPane(textArea,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);  
  JFrame frame=new JFrame("Open text file into JTextArea");  
  frame.add(scrollBarForTextArea);  
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
  frame.setSize(500,500);  
  frame.setLocationRelativeTo(null);  
  frame.setVisible(true);  
 }  
 catch(Exception exception)  
 {  

  System.out.println("Error in file processing");  
 }  
}  
}  

Solution

  • Start with methods of JTextArea:

    1. see the getLineStartOffset(...) and getLineEndOffset(...) methods.
    2. then you can use the getText(...) method to get all the text for the line.
    3. then you can use String.indexOf(...) to search the text for the location of "first".
    4. now you can add the offset from the start of the line and the indexOf methods to get the location of the text you want to highlight in the document
    5. then you can use the getHighlighter() method of the text area to get the highlighter
    6. finally you can use the addHighlight() method to highlight the word