javajformattedtextfielddocumentlistener

Getting Changed Text from DocumentListener


I thought this would be easy by apparently I don't understand DocumentListeners. I created a JFormattedTextField extension to include a listener so that I can update a hash map with the changed field text.

package stokerMonitor;

import java.util.HashMap;

import javax.swing.JFormattedTextField;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;

public class TimeLineTextClass extends JFormattedTextField {

/**
 * 
 */
private static final long serialVersionUID = 1L;

private HashMap<Integer,Object> fieldList;
private int field;

public TimeLineTextClass (Object tlformat_,HashMap<Integer,Object> fieldList_,int field_) {
    super(tlformat_);
    fieldList=fieldList_;
    field=field_;
    getDocument().addDocumentListener(new DocumentListener() {

        @Override
        public void changedUpdate(DocumentEvent e) {
            // Ignore - Using plain document

        }

        @Override
        public void insertUpdate(DocumentEvent e) {
            fieldList.put(field,????);
        }

        @Override
        public void removeUpdate(DocumentEvent e) {
            fieldList.put(field,????);
        }

    });
}

}

After going through the documentation, I cannot figure out how to get the changed text in the event handler. There appears to be no getText method. What do I use for '????'? TIA.


Solution

  • As TimeLineTextClass extends JFormattedField, you'll find there actually is a getText() method.

        @Override
        public void insertUpdate(DocumentEvent e) {
            fieldList.put(field,getText());
        }
    
        @Override
        public void removeUpdate(DocumentEvent e) {
            fieldList.put(field,getText());
        }
    

    The above code should work fine.