0

In a JEditorPane, I want to search for a string, I know that scrollToReference won't work, so I want to know how to Iterate through the Pane and find a specified string.

How do I Iterate through a JEditorPane to find a specified String in java?

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199

2 Answers2

4

The simplest way I can think of is simply to walk through the document.

Document document = editor.getDocument();
try {
    String find = //... String to find
    for (int index = 0; index + find.length() < document.getLength(); index++) {
        String match = document.getText(index, find.length());
        if (find.equals(match)) {
            // You found me
        }
    }
} catch (BadLocationException ex) {
    ex.printStackTrace();
}

You could write some routines to "find the next word" based around this concept

You may also find Highlight a word in JEditorPane and Java - Scroll to specific text inside JTextArea which both use a similar approach to achieve different things

Community
  • 1
  • 1
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • You can have a look at [this](http://stackoverflow.com/questions/13448558/highlight-a-word-in-jeditorpane/13449000#13449000) and [this](http://stackoverflow.com/questions/13437865/java-scroll-to-specific-text-inside-jtextarea/13438455#13438455) which use similar techniques – MadProgrammer Nov 22 '12 at 01:59
4

Expanding on @Mad's answer, if your Document is an HTMLDocument, you can explore it using an ElementIterator, as shown here.

Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045