Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 11 of 11

Thread: Seraching for String highlight all matches

  1. #1
    Member
    Join Date
    Oct 2010
    Posts
    61
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Seraching for String highlight all matches

    Hi Guys,

    This is my first post so hopefully nothing goes wrong.

    Right my java language knowledge is not the best in the world and im trying to make a program which reads in a file to JTextArea1 and ouputs everything in the text file to JTextArea1 . I have a little shearch bar and button at the bottom and for instance you put in "cat" and press search it searches for the first exact match for cat and highlights it thats it. What I want the program to do is go through all the text in JTextArea1 and highlight all the exatc matches of "cat".

    Heres my code. When the search button is pressed it matches the first exact match and highlights it.

       private void SearchForString(java.awt.event.MouseEvent evt) {                                      
            hilit.removeAllHighlights();
            String s = jTextField1.getText();
     
            if (s.length() <= 0) {
                message.setText("Nothing to search");
                return;
            }
            String content = jTextArea1.getText();
            int index = content.indexOf(s, 0);
            int end;
     
     
            if (index >= 0) {   // match found
                try {
                    end = index + s.length();
                    hilit.addHighlight(index, end, painter);
                    message.setText("'" + s + "' found.");
                } catch (BadLocationException e) {
                    message.setText("Error: " + e.getMessage());
                }
            }
            else {
                message.setText("'" + s + "' not found.");
            }
     
        }

    Any ideas how I can modify my existing code above to highlight all the strings in the JTextArea1 that match the string im searching for.

    Thankyou all for your help and if you require additional infomation please let me know.
    Last edited by fortune2k; October 2nd, 2010 at 05:51 AM.


  2. #2
    Member
    Join Date
    Oct 2010
    Posts
    61
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Seraching for String highlight all matches

    Right I have managed to get it to work however it does'nt work the best . The main bit im concerned with is the for loop. Any iodeas how I can optimize this ? The for loop overruns the ammount of searching it needed to do and i get the error message

     
        private void SearchForString(java.awt.event.MouseEvent evt) {                                      
            hilit.removeAllHighlights();
            String s = jTextField1.getText();
     
            if (s.length() <= 0) {
                message.setText("Nothing to search");
                return;
            }
            String content = jTextArea1.getText();
            int index, end;
     
     
    [B]for(int i=0; i < content.length(); i ++)[/B]
    {
            index = content.indexOf(s, i);
            if (index >= 0) {   // match found
                try {
                    end = index + s.length();
                    hilit.addHighlight(index, end, painter);
                  //  jTextArea1.setCaretPosition(end);
                    message.setText("'" + s + "' found.");
                } catch (BadLocationException e) {
                    message.setText("Error: " + e.getMessage());
                }
            }
            else {
                message.setText("'" + s + "' not found.");
            }
        }
     
        }

  3. #3
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,322
    Thanks
    49
    Thanked 2,194 Times in 2,167 Posts

    Default Re: Seraching for String highlight all matches

    i get the error message
    What is the error message? Does it explain what the problem was?

    Print out the values of the variables that can be causing the problem to see where they are wrong.

  4. #4
    Member
    Join Date
    Oct 2010
    Posts
    61
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Seraching for String highlight all matches

    Quote Originally Posted by Norm View Post
    What is the error message? Does it explain what the problem was?

    Print out the values of the variables that can be causing the problem to see where they are wrong.
    sorry there is no error message but the for loop loops round tooo many times and not effiecient. It uses .Lenght()

    java.​lang.​String
    public int length()
    Returns the length of this string. The length is equal to the number of Unicode code units in the string.
    Returns:
    the length of the sequence of characters represented by this object.

    so it loops round for every character in theJTextArea1 so after it has found all the matches it will continue to loop and i will get the else bit of code being displayed
    Last edited by fortune2k; October 2nd, 2010 at 08:32 AM.

  5. #5
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,322
    Thanks
    49
    Thanked 2,194 Times in 2,167 Posts

    Default Re: Seraching for String highlight all matches

    after it has found all the matches it will continue to loop
    Why loop based on length? Step along the string using the indexOf to find the next match. When indexOf returns NOT found, exit the loop with a break. Read API doc for indexOf to see how to use it to start at past where the last match was found.

  6. #6
    Member
    Join Date
    Oct 2010
    Posts
    61
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Seraching for String highlight all matches

    I dont know how to step along the string without using a for loop any ideas?

  7. #7
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,322
    Thanks
    49
    Thanked 2,194 Times in 2,167 Posts

    Default Re: Seraching for String highlight all matches

    The loop should continue until the indexOf method returns not found. Then exit the loop by using a break.
    The loop needs to go around enough times for that to happen. A while(true) loop would work.

    The next start point for indexOf should be past the last find.

  8. #8
    Member
    Join Date
    Oct 2010
    Posts
    61
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Seraching for String highlight all matches

    im sorry im really getting confussed here I have been trying various different aproaches but still nothing heres what i have

    boolean i = true;
        while(i == true)
        {
     
            index = content.indexOf(s, counter);
            if (index >= 0) {   // match found
                try {
                    end = index + s.length();
                    hilit.addHighlight(index, end, painter);
     
     
                }
                catch (BadLocationException e) {
                    StatusMessage.setText("Error: " + e.getMessage());
                }
            } 
            else {
               i = false;
               StatusMessage.setText("'" + s + "' not found.");
            }
     
        ++counter;
        }
        StatusMessage.setText( counter+ "matches found for '" + s + "'");
     
        }

  9. #9
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,322
    Thanks
    49
    Thanked 2,194 Times in 2,167 Posts

    Default Re: Seraching for String highlight all matches

    Please explain what the problem is.
    I see that the code should exit the loop when indexOf fails to find the string. Does it do that ok?

    Let me repeat what I suggested several times:
    The next start point for indexOf should be past the last find.
    You are using counter which is NOT related to a position in the string.
    Would the value of end be where you want to start the next search from?

  10. #10
    Member
    Join Date
    Oct 2010
    Posts
    61
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Seraching for String highlight all matches

    Right sorry for all the confusion I have managed to get it working now apart from 1 minor detail i cant get the counter for the ammount of matches

       private void SearchForString(java.awt.event.MouseEvent evt) {                                 
             hilit.removeAllHighlights();
            String s = StringSearchTextArea.getText();
     
            if (s.length() <= 0) {
                StatusMessage.setText("Nothing to search");
                return;
            }
            String content = MainTextArea.getText();
            int index, end, counter=0, matchesfound ;
     
        boolean i = true;
        while(i == true)
        {
     
            index = content.indexOf(s, counter);
            if (index >= 0) {   // match found
                ++counter;
                try {
                    end = index + s.length();
                    hilit.addHighlight(index, end, painter);
     
                }
                catch (BadLocationException e) {
                    StatusMessage.setText("Error: " + e.getMessage());
                }
             i = true;
             matchesfound = counter;
     
              StatusMessage.setText( matchesfound+ " Matches found for '" + s + "'");
            } 
     
            else if (index < 0){
               i = false;
               if(counter == 0)
               {
                   StatusMessage.setText("'" + s + "' not found.");
                }
     
            }
        }

    The program goes through determines if its not there displays the message correctly if it not there. If it can find matches it highlights them however i cant find a way to count all the exact number of matches. I get random numbers all the time

  11. #11
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,322
    Thanks
    49
    Thanked 2,194 Times in 2,167 Posts

    Default Re: Seraching for String highlight all matches

    Try debugging your code by adding print outs of the value of count every time it is changed and every location where indexOf found a match.

Similar Threads

  1. Setting Icons and checking for matches
    By Norflok669 in forum What's Wrong With My Code?
    Replies: 1
    Last Post: March 22nd, 2010, 08:52 PM
  2. Replies: 2
    Last Post: November 3rd, 2009, 05:28 AM
  3. Replies: 2
    Last Post: March 4th, 2009, 05:32 AM
  4. How to highlight search keyword in text?
    By Mohd in forum JavaServer Pages: JSP & JSTL
    Replies: 4
    Last Post: February 1st, 2009, 05:35 AM
  5. Replies: 1
    Last Post: December 30th, 2008, 06:30 AM