我的问题很简单。
我有一个 JtextArea。我的目标是从该行中第一个字符的开头突出显示该文本区域中的一行。通过使用 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) {}
}
上面代码的结果:
in x;
string y;
chr z;
上面应该突出显示。我错过了什么吗?