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");
}
}
}
Start with methods of JTextArea:
getLineStartOffset(...)
and getLineEndOffset(...)
methods.getText(...)
method to get all the text for the line.String.indexOf(...)
to search the text for the location of "first".getHighlighter()
method of the text area to get the highlighteraddHighlight()
method to highlight the word