简体   繁体   English

如何在Swing中的TextArea中选择特定文本

[英]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. 所以我写了一个代码,在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());
        ta.select(n,t1.getText().length());
    }
}

for reference, ta is the texarea and t1 is the TextField where the user enter word to be searched. 作为参考,ta是texarea,t1是TextField,用户输入要搜索的单词。 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. 我基本上想说的是,如果我在textField中输入字符串的第一个单词,则会搜索并选择它,但如果我输入任何其他单词则不会被选中。 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. 问题是select的第二个参数需要是String的结束索引 - 它不是一个大小,它是一个位置。 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. 您提供的代码适用于String的开头,因为n为零,因此您的位置和大小恰好相同。 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. 在工作情况下(在String的开头),n = 0所以我们什么都没改变。 In the case that isn't working, this extra "n + " moves us to the location we need to finish at. 在不起作用的情况下,这个额外的“n +”将我们带到我们需要完成的位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM