Question: I have a JPanel with two JTextFields. If the user writes some text into textfield A the same text should appear in textfield B and vice versa.

How can that be implemented without getting an infinite loop.

So far I have the following which leds to a infinite loop.

```
        JTextField textFieldA;
        JTextField textFieldB;

        textFieldA.getDocument().addDocumentListener(new DocumentListener() {
            public void insertUpdate(DocumentEvent e) {  
                Document doc = (Document)e.getDocument();
                String line = doc.getText(0, doc.getLength());  
                textFieldB.setText(line);
            }
            textFieldB.getDocument().addDocumentListener(new DocumentListener() {
                public void insertUpdate(DocumentEvent e) {  
                    Document doc = (Document)e.getDocument();
                    String line = doc.getText(0, doc.getLength());  
                    textFieldA.setText(line);
                }

```

Answer: 
You can use a boolean to mark when you are propagating changes.

```
    JTextField textFieldA;
    JTextField textFieldB;
    boolean updating = false;

    textFieldA.getDocument().addDocumentListener(new DocumentListener() {
        public void insertUpdate(DocumentEvent e) {  
            if(!updating) {
            updating = true;
            Document doc = (Document)e.getDocument();
            String line = doc.getText(0, doc.getLength());  
            textFieldB.setText(line);
            updating = false;
            }
        }
    textFieldB.getDocument().addDocumentListener(new DocumentListener() {
        public void insertUpdate(DocumentEvent e) {  
            if(!updating) {
            updating = true;
            Document doc = (Document)e.getDocument();
            String line = doc.getText(0, doc.getLength());  
            textFieldA.setText(line);
            updating = false;
            }
        }

```
Try to update `textFieldB` only if `textFieldA` [hasFocus](http://docs.oracle.com/javase/6/docs/api/java/awt/Component.html#isFocusOwner%28%29) (and vice versa)