Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)?

like image 687
ZimZim Avatar asked Dec 05 '11 10:12

ZimZim


2 Answers

From an answer by @JRL


Use the underlying document:

myTextField.getDocument().addDocumentListener();
like image 177
COD3BOY Avatar answered Nov 08 '22 18:11

COD3BOY


Yeah, but what is a document listener and how do you use it? You're not really answering the question.

I have a JTextField in my app's user interface. When the user makes any change to it, I want a nearby JCheckBox to be checked. The purpose is to tell the app to USE the value that was entered. Users often enter a value there but if they don't explicitly tell the app to use it then the app continues to ignore it. Instead of "training" users I'm supposed to follow the principle of least astonishment and automatically check the "Use this value" box.

But how do I listen for a change? Can't you guys just tell me the easy way, instead of "educating me" about document listeners?

like image 36
Ed Poor Avatar answered Nov 08 '22 18:11

Ed Poor