I have the following code that is designed to update JTextArea every time a key is pressed, and the focus is inside the JTextField and adds the contents of the JTextField to a new line in JTextArea.
My problem is that every time I press a key, updating JTextArea is always one of the key elements where I want.
Example: I type βcatβ in a JTextField, and only βcaβ appears in JTextArea, and not in the full String βcatβ that I want.
Any advice is appreciated, thanks for your time reading.
import java.awt.BorderLayout;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.File;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.WindowConstants;
public class Testing extends JFrame {
JTextField text;
JTextArea textArea;
public static void main(String[] args) {
Testing gui = new Testing();
gui.go();
}
public void go() {
this.setLayout(new BorderLayout());
text = new JTextField();
text.addKeyListener(new TestKeyListener());
textArea = new JTextArea();
this.add(text, BorderLayout.NORTH);
this.add(textArea, BorderLayout.CENTER);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
this.setSize(300,300);
this.setVisible(true);
}
private class TestKeyListener extends KeyAdapter {
@Override
public void keyPressed(KeyEvent evt) {
textArea.append(text.getText() + "\n");
}
}
}
James source
share