Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how add a listener for jtexfield when it changing? [duplicate]

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

How do I do that?

like image 815
Mahdi_Nine Avatar asked Mar 26 '11 16:03

Mahdi_Nine


People also ask

How do you use listener change?

In short, to use a simple ChangeListener one should follow these steps: Create a new ChangeListener instance. Override the stateChanged method to customize the handling of specific events. Use specific functions of components to get better undemanding of the event that occurred.

What is the difference between JTextField and JTextArea?

The main difference between JTextField and JTextArea in Java is that a JTextField allows entering a single line of text in a GUI application while the JTextArea allows entering multiple lines of text in a GUI application.

Can you enter more than one line in a JTextField?

Only one line of user response will be accepted. If multiple lines are desired, JTextArea will be needed. As with all action events, when an event listener registers an event, the event is processed and the data in the text field can be utilized in the program.


3 Answers

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
});
like image 181
JB Nizet Avatar answered Oct 21 '22 04:10

JB Nizet


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");
            }
        }
    });
like image 43
Tushar Arora Avatar answered Oct 21 '22 04:10

Tushar Arora


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");

        }
    });
like image 32
Adi Mor Avatar answered Oct 21 '22 05:10

Adi Mor