java documentlistener

Sergey Scopin picture Sergey Scopin · May 25, 2012 · Viewed 9.5k times · Source

I'm trying to call method after changing text of JTextField.

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

            public void changedUpdate(DocumentEvent arg0) 
            {
                System.out.println("IT WORKS");
                panel.setPrice(panel.countTotalPrice(TabPanel.this));
            }
            public void insertUpdate(DocumentEvent arg0) 
            {

            }

            public void removeUpdate(DocumentEvent arg0) 
            {

            }
        });

When I call this method at another ActionListener, it works ok. But when I change text in text field, nothing happens. Even println. Any suggestions?

Answer

Sergey Scopin picture Sergey Scopin · May 25, 2012

The problem solved. changedUpdated method called only when other atributes (font, size, but not text) changed. To call method after every change of text, I should put the call into insertUpdate and removeUpdate methods. This way:

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

            public void changedUpdate(DocumentEvent arg0) 
            {

            }
            public void insertUpdate(DocumentEvent arg0) 
            {
                System.out.println("IT WORKS");
                panel.setPrice(panel.countTotalPrice(TabPanel.this));
            }

            public void removeUpdate(DocumentEvent arg0) 
            {
                System.out.println("IT WORKS");
                panel.setPrice(panel.countTotalPrice(TabPanel.this));
            }
        });