好吧,我不得不对你的变量名做一些假设,我希望我做对了。基本上你的代码对我有用,但我不明白第一行:
int index = text.indexOf(myWord);
我认为应该是:
int index = text.indexOf(pattern);
无论如何,我写了这段代码,它对我有用:
String pattern = "<aa>";
String text = textArea.getText();
int index = text.indexOf(pattern);
while(index >= 0){
try {
hl.addHighlight(index, index + pattern.length(), DefaultHighlighter.DefaultPainter);
index = text.indexOf(pattern, index + pattern.length());
} catch (BadLocationException ex) {
ex.printStackTrace();
}
}
更新
查看当您单击标记文本的末尾并开始输入文本时,该文本也将被标记 - 这是我的错误。
抱歉,我之前没看到。我不认为你可以停止荧光笔,但你可以使用 aCaretListener
并在那里做这些事情。这样,如果您输入一个与您的模式匹配的新字符串,它也会被突出显示:
textArea.addCaretListener(new CaretListener() {
@Override
public void caretUpdate(CaretEvent e) {
if(e.getMark() == e.getDot()){
Highlighter hl = textArea.getHighlighter();
hl.removeAllHighlights();
String pattern = "<aa>";
String text = textArea.getText();
int index = text.indexOf(pattern);
while(index >= 0){
try {
Object o = hl.addHighlight(index, index + pattern.length(), DefaultHighlighter.DefaultPainter);
index = text.indexOf(pattern, index + pattern.length());
} catch (BadLocationException ex) {
ex.printStackTrace();
}
}
}
}
});
注意e.getMark() == e.getDot()
表示“没有文本选择”基于CaretEvent.getDot()和CaretEvent.getMark() javadoc。否则,您不应突出显示所选文本以外的任何内容。
截屏
更新的 SSCCE
这是一个完整的SSCCE来测试它:
import java.awt.Dimension;
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultHighlighter;
import javax.swing.text.Highlighter;
public class Demo {
private void initGUI(){
final JTextArea textArea = new JTextArea();
textArea.addCaretListener(new CaretListener() {
@Override
public void caretUpdate(CaretEvent e) {
if(e.getMark() == e.getDot()){
Highlighter hl = textArea.getHighlighter();
hl.removeAllHighlights();
String pattern = "<aa>";
String text = textArea.getText();
int index = text.indexOf(pattern);
while(index >= 0){
try {
Object o = hl.addHighlight(index, index + pattern.length(), DefaultHighlighter.DefaultPainter);
index = text.indexOf(pattern, index + pattern.length());
} catch (BadLocationException ex) {
ex.printStackTrace();
}
}
}
}
});
JScrollPane scrollPane = new JScrollPane(textArea);
scrollPane.setPreferredSize(new Dimension(300,200));
JPanel content = new JPanel(new FlowLayout());
content.add(scrollPane);
JFrame frame = new JFrame("Demo");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setContentPane(content);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new Demo().initGUI();
}
});
}
}