Search code examples
javaswingjtextfielddocumentlistener

How to make difference between textField.setText() and adding text to textField manually in java?


I have a textField in my application which will be initiated programmatically (textField.setText() ) when user clicked in an item in JList. later user will change this value manually. I get stuck with using document-listener to detect changes in this text field. When changes happens programmatically it must do nothing but if manually happens, it should change the background to red.

How to detect whether textField has been filled out manually or by textField.setText()?

txtMode.getDocument().addDocumentListener(new DocumentListener() {
        public void insertUpdate(DocumentEvent e) {
            if (!mode.equals(e.getDocument()))
            txtMode.setBackground(Color.red);
        }

        public void removeUpdate(DocumentEvent e) {
            if (mode.equals(e.getDocument()))
            txtMode.setBackground(Color.white);              
        }

        public void changedUpdate(DocumentEvent e) {
            //To change body of implemented methods
        }
    });

Solution

  • there are two ways

    • remove DocumentListener before setText("...") add DocumentListener back if done

    code

    public void attachDocumentListener(JComponent compo){
          compo.addDocumentListener(someDocumentListener);
    }
    
    //similair void for remove....
    
    • use boolean value for disabling "if needed", but you have to change contens of your DocumentListener

    for example

     txtMode.getDocument().addDocumentListener(new DocumentListener() {
        public void insertUpdate(DocumentEvent e) {
            if (!mode.equals(e.getDocument()))
    
            if (!updateFromModel){
               txtMode.setBackground(Color.red);
            }  
        }
    
        public void removeUpdate(DocumentEvent e) {
            if (mode.equals(e.getDocument()))
    
            if (!updateFromModel){
               txtMode.setBackground(Color.white);
            }  
        }
    
        public void changedUpdate(DocumentEvent e) {
            //To change body of implemented methods
        }
    });