6

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

How do I do that?

Sнаđошƒаӽ
  • 16,753
  • 12
  • 73
  • 90
Mahdi_Nine
  • 14,205
  • 26
  • 82
  • 117

4 Answers4

20

The appropriate listener in Java's swing to track changes in the text content of a JTextField is a DocumentListener, that you have to add to the document of the JTextField:

myTextField.getDocument().addDocumentListener(new DocumentListener() {
    // implement the methods
});
Alberto Bonsanto
  • 17,556
  • 10
  • 64
  • 93
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • 1
    It's a bit OTT when all one wants to do is detect a change, but I'll admit it's the only workable solution. – Andrew S Apr 02 '14 at 09:31
2

Use Key Listener in 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");
            }
        }
    });
Tushar Arora
  • 103
  • 1
  • 4
1

You can use Caret Listener

        JTextField textField = new JTextField();
    textField.addCaretListener(new CaretListener() {

        @Override
        public void caretUpdate(CaretEvent e) {
            System.out.println("text field have changed");

        }
    });
Adi Mor
  • 2,145
  • 5
  • 25
  • 44
-2

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

jzd
  • 23,473
  • 9
  • 54
  • 76
  • the values in field may change without user directly entering the value int the field , for example setting the value in field based on the radio button selected. – prnjn May 30 '18 at 22:39