I have a JTextField field on it that hangs the KeyTyped handler and I need to read the text from this field, but I have such a problem that when I call getText() I get a string without the last character entered, that is, I entered the first letter getText returned an empty line I entered the second letter I got the string with the letter you entered for the first time and so on. Why is this happening?

    1 answer 1

    Option that is supposed to use .getDocument().addDocumentListener()

     JLabel lbl = new JLabel(); lbl.setPreferredSize(new Dimension(150, 22)); JTextField tf = new JTextField(); tf.setPreferredSize(new Dimension(150, 22)); tf.getDocument().addDocumentListener(new DocumentListener() { @Override public void changedUpdate(DocumentEvent e) { lbl.setText(tf.getText()); } @Override public void insertUpdate(DocumentEvent e) { lbl.setText(tf.getText()); } @Override public void removeUpdate(DocumentEvent e) { lbl.setText(tf.getText()); } }); JFrame f = new JFrame(); f.setSize(new Dimension(200,100)); f.setLayout(new FlowLayout()); f.add(lbl); f.add(tf); f.setLocationRelativeTo(null); f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); f.setVisible(true); 

    Just the same way, your approach will also work if you listen not to keyTyped but to keyReleased , and the behavior will be a little not standard, check for yourself:

     JLabel lbl = new JLabel(); lbl.setPreferredSize(new Dimension(150, 22)); JTextField tf = new JTextField(); tf.setPreferredSize(new Dimension(150, 22)); tf.addKeyListener(new KeyAdapter() { @Override public void keyReleased(KeyEvent e) { lbl.setText(tf.getText()); } }); JFrame f = new JFrame(); f.setSize(new Dimension(200,100)); f.setLayout(new FlowLayout()); f.add(lbl); f.add(tf); f.setLocationRelativeTo(null); f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); f.setVisible(true); 
    • Thank. The first option really helped - Badma Bardaev