Abhay Abhay - 10 months ago 22
Java Question

How To Select A Specific text In A TextArea In Swing

so i have written a code that searches for a word in a textArea. here is the code:

else if(str.equals("Find Next"))
if(ta.getText().length()!=0 && t1.getText().length()!=0)
int n = ta.getText().trim().indexOf(t1.getText().trim());

for reference, ta is the texarea and t1 is the TextField where the user enter word to be searched. my problem is when i write a string something like this - He is a good boy , and search for say , good , then good is not selected but when i search for "He" , he is selected. what i basically want to say is that if i enter the first word of the string in the textField, it is searched and selected but if i enter any other word it does not get Selected. where am i doing wrong?


The problem is that the second argument of select needs to be the ending index of the String -- it's not a size, it's a location. The code you provided works for the beginning of the String because n is zero, so your location and your size happen to be the same. I think you can solve your problem by changing your last line to:

ta.select(n,n + t1.getText().length());

In the working case (at the beginning of the String), n = 0 so we've changed nothing. In the case that isn't working, this extra "n + " moves us to the location we need to finish at.