我的方法可以突出显示文本区域中所有单词的出现次数。有没有办法使用开始和结束偏移来突出显示该行中的单词。
我目前的代码。
public static 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());
int pos = 0;
// Search for pattern
while ((pos = text.indexOf(pattern, pos)) >= 0) {
// Create highlighter using private painter and apply around pattern
hilite.addHighlight(pos, pos + pattern.length(), painter2);
pos += pattern.length();
}
} catch (BadLocationException e) {
}
}
这是在执行的JButton操作上调用的:
highlight(textArea_1, "in");
结果:
我尝试使用开始和结束偏移方法,但没有运气。我试图仅在第6行突出显示“in”。对此非常感谢。
static int iline =6;
public static void highlight(JTextComponent textComp, String pattern) {
try {
Highlighter hilite = textComp.getHighlighter();
javax.swing.text.Document doc = textComp.getDocument();
int start =((JTextArea) textComp).getLineStartOffset(iline);
int end = ((JTextArea) textComp).getLineEndOffset(iline);
String text = doc.getText(start,end);
int pos = start;
// Search for pattern
while ((pos = text.indexOf(pattern, pos)) >= start) {
// Create highlighter using private painter and apply around pattern
hilite.addHighlight(pos, pos + pattern.length(), painter2);
pos += pattern.length();
}
} catch (BadLocationException e) {
}
}
答案 0 :(得分:3)
int start =((JTextArea) textComp).getLineStartOffset(iline);
int end = ((JTextArea) textComp).getLineEndOffset(iline);
String text = doc.getText(start,end);
int pos = start;
假设我们每行都有10个字符。因此,如果您想要第6行的文本,则start变量将等于51,结束变量为60。
当您获得第6行的文本时,它将只包含10个字符。
因此,当你在51开始搜索时,你已经在搜索字符串的末尾,所以你不会得到任何匹配。
您需要在偏移0处开始搜索,然后在添加突出显示时,需要将开始值添加到高光偏移。
答案 1 :(得分:0)
得到它的工作谢谢@camickr
代码:
public static void highlight(JTextComponent textComp, String pattern) {
try {
Highlighter hilite = textComp.getHighlighter();
String text = textComp.getText();
String line =null;
int start = 0;
int end;
int totalLines = ((JTextArea) textComp).getLineCount();
for (int i=0; i < totalLines; i++) {
if(i==5){ //Line Numbers Decrement by 1
start = ((JTextArea) textComp).getLineStartOffset(i);
end = ((JTextArea) textComp).getLineEndOffset(i);
line = text.substring(start, end);
System.out.println("My Line: " + line);
System.out.println("Start Position of Line: " + start);
System.out.println("End Position of Line: " + end);
}
}
int pos = start;
// Search for pattern
if ((pos =text.indexOf(pattern, pos)) >= start) {
// Create highlighter using private painter and apply around pattern
hilite.addHighlight(pos, pos + pattern.length(), painter2);
pos += pattern.length();
}
} catch (BadLocationException e) {
}
}