A DocumentListener is used for detecting changes to a text document. You want to use it when you want something to happen every time the text changes.
You said that you want something to happen every time the user pushes the enter key. Because of this, as @camickr rightfully pointed out, you should consider using a Key Binding instead. Read up on the doc page, as that is the most correct way to handle hot keys in a JComponent.
The quick-and-dirty way to do it would be to use a KeyListener instead, which listens for key presses at a low level. Note that this is not the most correct way to do it, and that it may make your code difficult to maintain.
If you do wish to use a KeyListener, then do the following: change your MyDocListen class to some other class that implements KeyListener, and implement KeyListener.keyTyped() to check if it was the enter key that was pushed, and if it was, call getText():
class MyKeyListener implements KeyListener {
public void getText()
{
StringBuffer sb = new StringBuffer();
String str = JtextareaTest.jtextArea1.getText();
sb.append(str);
JtextareaTest.jtextArea2.setText(sb.toString());
}
@Override
public void keyPressed(KeyEvent e) {}
@Override
public void keyReleased(KeyEvent e) {}
@Override
public void keyTyped(KeyEvent e) {
if (e.getKeyChar() == KeyEvent.VK_ENTER) {
getText();
}
}
}
Then just change the line
MyDocListen listener= new MyDocListen();
to
MyKeyListener listener = new MyKeyListener();
and be sure to add the KeyListener to the JTextArea itself, not its document. To do this, replace this line:
jtextArea1.getDocument().addDocumentListener(listener);
with this:
jtextArea1.addKeyListener(listener);
and that should fix your problem.