javaswingnetbeansdocumentlistener

Unable to update TextArea while typing in Text Field at same time


Hello guyz i am new to java swing and working on a project, I am unable to update the text which i was typed in text field to text area in java swing , I am using this Example as a reference , but i am making my GUI using Drag and Drop in Netbeans by using JFrame Form

Here is my code

private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {                                            
        // TODO add your handling code here:

      String s = this.jTextField1.getText();
      jTextArea1.setEditable(false);

        jTextField1.getDocument().addDocumentListener(new DocumentListener() {

            public void insertUpdate(DocumentEvent de) {
                jTextArea1.setText(s);
            }

            @Override
            public void removeUpdate(DocumentEvent de) {
                jTextArea1.setText(s);
            }

            @Override
            public void changedUpdate(DocumentEvent de) {
            //Plain text components don't fire these events.
            }
        });

    }     

I am unable to do this by using Drag and drop method , whereas its working fine for me as like example which i have posted above.

Any help would be highly appreciate


Solution

  • Normally, we don't put a Listener inside another Listener, which makes the inner Listener to be called multiple times. Clear out the following code.

    jTextArea1.setEditable(false);
    
    jTextField1.getDocument().addDocumentListener(new DocumentListener() {
    
        public void insertUpdate(DocumentEvent de) {
            jTextArea1.setText(s);
        }
    
        @Override
        public void removeUpdate(DocumentEvent de) {
            jTextArea1.setText(s);
        }
    
        @Override
        public void changedUpdate(DocumentEvent de) {
            //Plain text components don't fire these events.
        }
    });
    

    Then use your Netbeans GUI Builder to make the jTextArea1 non-editable ( in the Properties ) and also add a DocumentListener to the jTextField1 like what you did with its ActionListener.

    Then update the text in the newly added methods created by the GUI Builder, which I believed to be:

    public void jTextField1RemoveUpdate(DocumentEvent de)
    public void jTextField1InsertUpdate(DocumentEvent de)
    

    in each method, you make a call to jTextArea1.setText(jTextField1.getText());