Java TextField getText () returns the previous value of the string

I have a problem with the Java text field, when I cover all the text in JTextField and immediately enter new text (do not pass back) to JTextField, then I use getText () function I get the previous line not the current line, Please help in solving some problems . Thanks in advance.

+4
source share
3 answers

I just tested the problem you described by adding keyListener to the JTextField and printing the return value of the getText () method on the console.

What I learned is that it is always one character behind if you want to use the GetText () method directly in the keyTyped or Keypressed event (I don’t know, because I usually just use the button to confirm, I m entered the text and bound KeyEvent to the Return key to launch the button if the user wants to confirm by pressing enter)

I think this is because textField updates its text value AFTER the event was shot.

I assume that this is what you have done since you did not present the sample code, so I will remove this answer if it is not.

Work on this is to implement what you want to do in the keyReleased method.

public void keyReleased(Event e) { System.out.println(myTextField.getText()); } 
+11
source

Do not use KeyListener. The character is NOT added to the document when the keyPressed () event is fired.

Add ActionListener to JButton. Thus, the user presses the button when entering text.

Also, publish a SSCCE with a question in the future so that we can better understand what you are trying to do.

+7
source

eg:

 import java.awt.GridLayout; import javax.swing.*; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; public class TextLabelMirror { private JPanel mainPanel = new JPanel(); private JTextField field = new JTextField(20); private JTextField field1 = new JTextField(20); public TextLabelMirror() { field.getDocument().addDocumentListener(new DocumentListener() { @Override public void changedUpdate(DocumentEvent e) { updateLabel(e); } @Override public void insertUpdate(DocumentEvent e) { updateLabel(e); } @Override public void removeUpdate(DocumentEvent e) { updateLabel(e); } private void updateLabel(DocumentEvent e) { java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { field1.setText(field.getText()); } }); } }); mainPanel.setLayout(new GridLayout(1, 0, 10, 0)); mainPanel.add(field); mainPanel.add(field1); } public JComponent getComponent() { return mainPanel; } private static void createAndShowUI() { JFrame frame = new JFrame("TextLabelMirror"); frame.getContentPane().add(new TextLabelMirror().getComponent()); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } public static void main(String[] args) { java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { createAndShowUI(); } }); } } 
+1
source

All Articles