Search code examples
javaswingkeylistenerkey-bindings

KeyListener VS Key Binding for JField


I'm trying to do a dynamic search using JTextField, this is, I need to query a list of objects every time I strike a key (for example, I press an "A" and get all entries containing an "A", then I add an "l" and all the entries that don't have "Al" in it get filtered out, then come "Ali", "Alic" and finally "Alice" ). I don't really need to associate the keys with any specific actions, so my question is: is it enough to use KeyListener to cover this functionality?


Solution

  • I actually wouldn't use either of those tools. There is a tool that was custom built to do exactly what you are talking about. It is called a DocumentListener.

    Here is a demo code.

    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.text.*;
    
    public class DocumentListenerExample
    {
    
       public static void main(String[] args)
       {
       
          JFrame frame = new JFrame();
          frame.setSize(500, 500);
          frame.setLocationByPlatform(true);
          
          JTextField field = new JTextField();
          
          Document doc = field.getDocument();
          
          doc.addDocumentListener(
             new DocumentListener()
             {
             
                public void changedUpdate(DocumentEvent e) {}
                public void removeUpdate(DocumentEvent e) {}
                
                public void insertUpdate(DocumentEvent e)
                {
                   
                   try
                   {
                      System.out.println(e.getDocument().getText(e.getOffset(), e.getLength()));
                   } 
                   catch (Exception exception) 
                   {
                      System.err.println(exception);
                   }
                
                }
             
             }
             );
          
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.getContentPane().add(field);
          frame.setVisible(true);
       
       }
    
    }
    
    

    I extracted the Document out of my JTextField, then I added an anonymous DocumentListener to it, whose DocumentListener::insertUpdate method just prints out the String that was just inserted by using Document::getText, DocumentEvent::getOffset, and DocumentEvent::getLength.

    For your purposes, you may want to just grab all of the text as opposed to just the String that was just inserted. But regardless, this gives you a decent Proof of Concept on how to do it.