仅在第一个字符遇到JtextArea中的LineEndOffset时将“荧光笔”应用于行

时间:2013-03-23 12:44:53

标签: java swing jtextarea swing-highlighter

我的问题非常简单。

我有一个JtextArea。我的目标是从该行第一个角色的开头突出显示该textarea中的一行。 通过使用Java行开始和结束偏移,我能够突出显示整行,但它看起来很难看。

我试图从该行获取所有文本。通常它将包含空格。 我尝试了什么:

String text = textArea_1.getText(); //My TextArea
int startIndex = textArea_1.getLineStartOffset(i11); //i11 is the Line Number
int endIndex = textArea_1.getLineEndOffset(i11);
String myString = text.substring(startIndex, endIndex);
//I get all text from that line

for(int i1 = 0; i1 < myString.length(); i1++){ 
//This is trying to increment startindex until it gets a non empty space, 
//the counter should stop.
       while(Character.isWhitespace(myString.charAt(i1))){
              startIndex++;
              break;
       }
}

String myString2 = text.substring(startIndex, endIndex);
//I now pass the new startIndex
String [] javaWords = {myString2};//Function highlight takes an array.
System.out.println("String to Highlight: " + myString2);
highLight(textArea_1, javaWords);//Function to Highlight  

荧光笔方法:

public void highLight(JTextComponent textComp, String[] pattern) {

  try {
     Highlighter hilite = textComp.getHighlighter();
     javax.swing.text.Document doc = textComp.getDocument(); 
     String text = doc.getText(0, doc.getLength());
     for (int i = 0; i < pattern.length; i++) {
        int pos = 0;
         // Search for pattern
         while ((pos = text.indexOf(pattern[i], pos)) >= 0) {
            hilite.addHighlight(pos, pos + pattern[i].length(),painter);
            pos += pattern[i].length();
         }
     }
     } catch (BadLocationException e) {}
}

上面代码的结果: enter image description here

in x;
string y;
chr z; 

应突出以上内容。我错过了什么吗?

1 个答案:

答案 0 :(得分:0)

问题在于循环......它修正了:

String text = textArea_1.getText();
                        int startIndex = textArea_1.getLineStartOffset(i11);
                        int endIndex = textArea_1.getLineEndOffset(i11);
                        String myString = text.substring(startIndex, endIndex);
                        for(int i1 = 0; i1 < myString.length(); i1++){
                            if(Character.isWhitespace(myString.charAt(i1))){
                                startIndex++;

                            }
                         if(!Character.isWhitespace(myString.charAt(i1))){
                                startIndex = startIndex+0;;
                                break;
                            }


                        }

                        String myString2 = text.substring(startIndex, endIndex);
                        String [] javaWords = {myString2};
                        System.out.println("String to Highlight: " + myString2);
                        highLight(textArea_1, javaWords);    

结果:

enter image description here