Search code examples
javaextendsjformattedtextfield

Extend JFormattedTextField


I am extending a JFormattedTextField to add a listener. I have this working although it is probably not the best way to do it. Is there not a way to use a single generic constructor?

public class TimeLineTextClass extends JFormattedTextField {

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

private TimelineRecord timeLine;

public TimeLineTextClass (NumberFormat tlformat_,HashMap<Integer,JComponent> fieldList_,int field_,TimelineRecord timeLine_) {
    super(tlformat_);
    timeLine=timeLine_;
    getDocument().addDocumentListener(new DocumentListener() {

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

        }

        @Override
        public void insertUpdate(DocumentEvent e) {
            timeLine.setObject((String) getClientProperty("type"),getText());
        }

        @Override
        public void removeUpdate(DocumentEvent e) {
            timeLine.setObject((String) getClientProperty("type"),getText());
        }

    });
}

public TimeLineTextClass (SimpleDateFormat tlformat_,HashMap<Integer,JComponent> fieldList_,int field_,TimelineRecord timeLine_) {
    super(tlformat_);
    timeLine=timeLine_;
    getDocument().addDocumentListener(new DocumentListener() {

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

        }

        @Override
        public void insertUpdate(DocumentEvent e) {
            timeLine.setObject((String) getClientProperty("type"),(String) getText());
        }

        @Override
        public void removeUpdate(DocumentEvent e) {
            timeLine.setObject((String) getClientProperty("type"),(String) getText());
        }

    });
}

}

It seems like there should be a way to use just one constructor with a generic format type as the first argument and for 'super'. TIA.


Solution

  • Just like the JFormattedTextField constructors, you can use the type Format to catch the NumberFormat type and the SimpleDateFormat type.