How to distinguish textfield Settext() and manually add text to textfield in Java?

I have a textfield in my application. When the user clicks in an item in JList, it will start programmatically (textfield. Settext())

How to check whether textfield is filled in manually or through textfield Settext() fill in the?

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

>Delete the documentlistener before settext ("..."), and add the documentlistener if it is completed

code

public void attachDocumentListener(JComponent compo){
      compo.addDocumentListener(someDocumentListener);
}

//similair void for remove....

>Use a Boolean value to disable "if needed", but you must change the record of the 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
    }
});
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>