Search code examples
javasearchsearch-engine

Java. Searching a word in a text area


Good day. I am working on a project and I have a question. I have a text area with a .txt file imported and I want to create a search button and I want to enter a word and search it in that textarea. Similar to CTRL+F, you enter a word, you press enter and you find the word.

My code looks like this:

JScrollPane textp1 = new JScrollPane();
        textp1.setBounds(110, 222, 570, 450);
        textp1.setBackground(Color.DARK_GRAY);
        gtapage1.add(textp1);
JTextArea textpage1 = new JTextArea();
        textpage1.setBackground(Color.WHITE);
        textpage1.setEditable(false);
        textpage1.setWrapStyleWord(true);
        textpage1.setLineWrap(true);
        try{
            FileInputStream fstream = new FileInputStream("D:\\Facultate\\anul 2\\Java Workspace\\Encyclopedia\\src\\text\\gta\\gtaintro.txt");
            DataInputStream in = new DataInputStream(fstream);
            Reader reader = new InputStreamReader(in);
            textpage1.read(reader, fstream);
        }catch(Exception e){System.err.println("Error: " + e.getMessage());}
        textp1.setViewportView(textpage1);

I want to have a button/field, to enter a word, press enter and highlight the word in my textpage1.


Solution

  • You could use the built in method of the String. e.g.

    String str = "Here I am";
    int i = str.indexOf("am"); //i is 7
    

    Then you would highlight the specific area by taking the start index and the length of the string. i is 7 because there is 7 characters before the first letter of the string we are looking up.

    NOTE: indexOf is case sensitive.