Updating the text area at the same time as you type text in the text box

I want to update the text area with the input of the text field, but I get a delay of 1 keystroke when I type ie when I press the key that displays the previous key. Here is my fragment

private void jTextField1KeyTyped(java.awt.event.KeyEvent evt) { String a = jTextField1.getText(); jTextArea1.setText(a); } 
+4
source share
4 answers

I would not recommend using KeyListeners

Just add a DocumentListener to your JTextField with:

 textField.getDocument().addDocumentListener(new DocumentListener() { @Override public void insertUpdate(DocumentEvent de) { } @Override public void removeUpdate(DocumentEvent de) { } @Override public void changedUpdate(DocumentEvent de) { } }); 

Inside each of the methods ( insertUpdate , removeUpdate and changedUpdate ), simply enter a call to set the text of your JTextArea via setText() :

 textArea.setText(textField.getText()); 

Here is an example I made:

 import java.awt.BorderLayout; import javax.swing.*; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; public class Test { public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { new Test().createAndShowUI(); } }); } private void createAndShowUI() { final JFrame frame = new JFrame("Test"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); initComponents(frame); frame.setResizable(false); frame.pack(); frame.setVisible(true); } private void initComponents(JFrame frame) { final JTextField jtf = new JTextField(20); final JTextArea ta = new JTextArea(20,20); ta.setEditable(false); jtf.getDocument().addDocumentListener(new DocumentListener() { @Override public void insertUpdate(DocumentEvent de) { ta.setText(jtf.getText()); } @Override public void removeUpdate(DocumentEvent de) { ta.setText(jtf.getText()); } @Override public void changedUpdate(DocumentEvent de) { //Plain text components don't fire these events. } }); frame.getContentPane().add(jtf, BorderLayout.WEST); frame.getContentPane().add(ta, BorderLayout.EAST); } } 
+9
source

You must do this in keyReleased instead of keyTyped , and it will work as needed.

+6
source

You need to wait until the event on your TextField is processed before updating TextArea. Your code updates TextArea before the TextField completes processing the new typed character. Therefore, the text set to TextArea is a single keystroke.

0
source

You can try using recursion by specifying a method inside the method (at least avoid loops).

0
source

Source: https://habr.com/ru/post/1437245/


All Articles