Search code examples
javaswingactionlistenerjtextfielddocumentlistener

How to get values of jTextField real time?


I am having trouble with setting up actionlistener to jtextfield. I want to update string based on users input in jtextfield in real time. As of now I have added actionlistener to jtextfield that allows me to update my after I press enter in jtextfield.

I was just wondering is there anyway that I can do it in real time ?

Thanks too suggestions from Hovercraft Full Of Eels, I dot this thing working. Following is the code that I used if somebody stumble upon this questions again

jtextfieldName.getDocument().addDocumentListener(new DocumentListener() {

        @Override
        public void removeUpdate(DocumentEvent arg0) {
            // TODO put what you would like to do when text is deleted

        }

        @Override
        public void insertUpdate(DocumentEvent arg0) {
            // TODO put what you would like to do when text is added
        }

        @Override
        public void changedUpdate(DocumentEvent arg0) {
            // TODO Auto-generated method stub

        }
    });

Solution

  • One possibility is to add a DocumentListener to the JTextField's PlainDocument. If you want to filter the information such that you want to prevent some type of text from being entered, then consider using a DocumentFilter instead.