在textarea中搜索单词

我在java中构建一个自定义find and replace 。 我浏览文本文件并在textarea中加载内容。 现在我有一个textBox,我在其中输入需要搜索的文本。

搜索文本的最佳方法是什么。 我知道使用string.indexOf() ,但我还需要突出显示。 所以请帮帮我。

首先阅读文本和新行 ,了解如何获取文本进行搜索。

然后突出显示您需要使用荧光笔的文本。 代码类似于:

 Highlighter.HighlightPainter painter = new DefaultHighlighter.DefaultHighlightPainter( Color.cyan ); int offset = text.indexOf(searchWord); int length = searchWord.length(); while ( offset != -1) { try { textPane.getHighlighter().addHighlight(offset, offset + length, painter); offset = text.indexOf(searchWord, offset+1); } catch(BadLocationException ble) { System.out.println(ble); } } 

indexOf是最简单的方法,但可能不是最快的方法。

为什么indexOf不适合你呢? 您将获得匹配的索引,并且您知道匹配的长度,因此只需突出显示匹配的文本。

我的文本编辑器遇到了同样的问题。 我没有使用荧光笔,我用过

 textArea.select(int i1, int i2); //where i1 is where your selection begins and i2 is where it ends. 

找到和替换的简单方法是:

 textArea.setText(textArea.getText().replaceAll(String string1, String string2)); 
 final String inputValue = JOptionPane.showInputDialog("Find What?"); final int l1 = jTextArea1.getText().indexOf(inputValue); final int l2 = inputValue.length(); if (l1 == -1) { JOptionPane.showMessageDialog(null, "Search Value Not Found"); } else { jTextArea1.select(l1, l2+l1); }