Search code examples
javaswingjtextfielddocumentlistener

extend functionality of addDocumentListener


I've a text field which extends javax.swing.JTextField and also have document listener like this

public class MyTetField extends javax.swing.JTextFiled{
     public MyTextField(){
          super();
          // Document listener to check mandatory functionality
          getDocument().addDocumentListener(new javax.swing.event.DocumentListener() {
            /**
             * If the text is changed then this event will be fired.
             */
            public void changedUpdate(javax.swing.event.DocumentEvent e) {
            }
            /**
             * If some value is removed then this event is fired.
             */
            public void removeUpdate(javax.swing.event.DocumentEvent e) {
            }
            /**
             * If some value is auto set, this event will be called
             * @param e The value change event
             */
            public void insertUpdate(javax.swing.event.DocumentEvent e) {
                if (getText().trim().equals("")){
                    setBorder(javax.swing.BorderFactory.createLineBorder(java.awt.Color.RED));
                }else{
                    setBorder(javax.swing.BorderFactory.createLineBorder(java.awt.Color.GRAY));
                }
            }
        });
     }
}

Now I want another text field say MyTextField1extending MyTextField which should have this mandatory check and also to get some information from DB after checking mandatory field and if some value is given. I do not want to write the same document listener code in that. Is it possible to extend document listener which we added in MyTextField OR should I go for focus listener?


Solution

    1. There is no need to extend JTextField for what you are doing. Most of the times, there is no need to extend the Swing components.
    2. What your listener does in your MyTextField class looks remarkably similar to what a JFormattedTextField does. You might want to consider using that class instead
    3. To actually answer your question, you can extend your MyTextField class and just add another DocumentListener which does some extra checks. You will keep your original functionality since the super class will add its own DocumentListener