How to add a listener for jtexfield when changing it?

I have a JTextField. I want to call a function when the text in it is changed.

How to do it?

+4
source share
4 answers

The appropriate listener in Java swing to track changes to JTextField text content is the DocumentListener, which you must add to the JTextField document:

 myTextField.getDocument().addDocumentListener(new DocumentListener() { // implement the methods }); 
+19
source

Use Key Listener this way

 JTextField tf=new JTextField(); tf.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent ke) { if(!(ke.getKeyChar()==27||ke.getKeyChar()==65535))//this section will execute only when user is editing the JTextField { System.out.println("User is editing something in TextField"); } } }); 
+3
source

You can use catherine listener

  JTextField textField = new JTextField(); textField.addCaretListener(new CaretListener() { @Override public void caretUpdate(CaretEvent e) { System.out.println("text field have changed"); } }); 
0
source

You can add a KeyListener or ActionListener to the field and commit events.

-1
source

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


All Articles