Thread: Text Searching
View Single Post
Old 12-01-2004, 12:14 PM   #1 (permalink)
freesoft_2000
Code Monkey
 
Join Date: Oct 2004
Posts: 51
freesoft_2000 is on a distinguished road
Exclamation Text Searching

Hi everyone,

I have a textpane with some text inside and trying to search for a particular text in the textpane by highlighting it. Basically i the main function that does this is as follows

TextPane is an instance of my JTextPane
Code:
  public void findtext(int pos1, String str1) {
    //This function finds the specified text in the document in the JTextPane
    //according the downwards position of the caret in the JTextPane
    
    Document Document1 = null;
    String str2 = null;
    int w = 0, w1 = 0, w2 = 0;
    
    //The below command line gets the document of the JTextPane
    
    Document1 = TextPane1.getDocument();
    System.out.println("" + pos1);
    try {
      //The below command line gets the text of the document according to
      //the downwards position of the caret in the JTextPane
      
      str2 = Document1.getText(pos1, Document1.getLength() - pos1);
      //The below two command lines converts the text in the document and the
      //the text to be searched both to lower case letters
      
      //str1 = str1.toLowerCase();
      //str2 = str2.toLowerCase();
      //The below command line gets the length of the text to be searched
      
      w2 = str1.length();
    }
    
    catch(Exception e) {
      Label2.setText("A caret position error has occurred");
    }
    
    //The below command line gets the index of the searched text in the document
    
    w = str2.indexOf(str1);
    
    if(w == -1) {
      //In this if statement TextPane1 is gained focus when the searched text
      //is not found in the document and the function is returned
      
      TextPane1.grabFocus();
      Label2.setText("The text that was searched was not found");
      return;
    }
    
    else {
      Label2.setText("");
      //In this else statement if the searched text is found in the document
      //the text in the document is selected with respect to the current
      //caret position in the JTextPane
      
      w1 = (w + pos1);
      TextPane1.select(w1, w1 + w2);
      TextPane1.grabFocus();
    }
    
  }
The problem is that the first time that i search the jtextpane the above function works Ok but when i try to do it again only the last text in the jtextpane is selected

I really do not know what is wrong and hope someone can help me with this problem.

Any help is greatly appreciated

Thank You

Yours Sincerely

Richard West

Last edited by Belisarius; 12-01-2004 at 12:51 PM.
freesoft_2000 is offline   Reply With Quote