Let ActionListener listen for change in JTextField instead of only enter?

ZimZim picture ZimZim · Dec 5, 2011 · Viewed 29.8k times · Source

So as you may know, if you have a text field and you add an ActionListener to it, it will only listen to the keypress of the enter button. However, I want to let my ActionListener listen to changes in text of the . So basically I've got this:

    public static JPanel mainPanel() { 
    JPanel mainp = new JPanel(); 
    JTextArea areap = new JTextArea("Some text in the textarea"); 
    JTextField fieldp = new JTextField("Edit this"); 
    areap.setEditable(false); 
    fieldp.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            // TODO Auto-generated method stub
             if(//change in textfield, for instance a letterpress or space bar)
                   { 
                        //Do this
                   } 
        }
    });
    mainp.add(areap);
    mainp.add(fieldp); 
    return mainp;
}

Any way I can listen to changes in text (like documented in the actionPerformed event)?

Answer

COD3BOY picture COD3BOY · Dec 5, 2011

From an answer by @JRL


Use the underlying document:

myTextField.getDocument().addDocumentListener();