FileDocCategorySizeDatePackage
IncrementalSearch.javaAPI DocExample2416Mon Jan 09 11:02:00 GMT 2006None

IncrementalSearch

public class IncrementalSearch extends Object implements DocumentListener, ActionListener

Fields Summary
protected JTextComponent
content
protected Matcher
matcher
Constructors Summary
public IncrementalSearch(JTextComponent comp)

        this.content = comp;
    
Methods Summary
public voidactionPerformed(java.awt.event.ActionEvent evt)

        continueSearch();
    
public voidchangedUpdate(javax.swing.event.DocumentEvent evt)

        runNewSearch(evt.getDocument());
    
private voidcontinueSearch()

        if(matcher != null) {
            if(matcher.find()) {
                content.getCaret().setDot(matcher.start());
                content.getCaret().moveDot(matcher.end());
                content.getCaret().setSelectionVisible(true);
            }
        }
    
public voidinsertUpdate(javax.swing.event.DocumentEvent evt)

        runNewSearch(evt.getDocument());
    
public static voidmain(java.lang.String[] args)

        JTextArea text_area = new JTextArea(10,20);
        JScrollPane scroll = new JScrollPane(text_area);
        IncrementalSearch isearch = new IncrementalSearch(text_area);

        JTextField search_field = new JTextField();
        search_field.getDocument().addDocumentListener(isearch);
        search_field.addActionListener(isearch);
        
        JFrame frame = new JFrame("Incremental Search Hack");
        frame.getContentPane().add("North",search_field);
        frame.getContentPane().add("Center",scroll);
        frame.pack();
        frame.show();
    
public static voidp(java.lang.String str)

        System.out.println(str);
    
public voidremoveUpdate(javax.swing.event.DocumentEvent evt)

        runNewSearch(evt.getDocument());
    
private voidrunNewSearch(javax.swing.text.Document query_doc)

        try {
            String query = query_doc.getText(0,query_doc.getLength());
            Pattern pattern = Pattern.compile(query);
            Document content_doc = content.getDocument();
            String body = content_doc.getText(0,content_doc.getLength());
            matcher = pattern.matcher(body);
            continueSearch();
        } catch (Exception ex) {
            p("exception: " + ex);
            ex.printStackTrace();
        }