javatextfieldchangelistener

How to print JTextField value immediately after user input?


I would like the user to enter a value into the JTextField and use a listener to listen to the textfield and print the value to the console straightaway without pressing a key.

textfield1.addChangeListener(new ChangeListener() {
    public void actionPerformed(ActionEvent e) {                
        System.out.println(textfield1);
    }
});

error:

<anonymous textfield$2> is not abstract and does not override abstract method stateChanged(ChangeEvent) in ChangeListener

Solution

  • Put this private class into your public class. Just like a method.

    private class textChangedListener implements KeyListener 
    {
        public void keyPressed(KeyEvent e){} 
        public void keyReleased(KeyEvent e){}
    
        public void keyTyped(KeyEvent e) 
        {
            System.out.print(textField1.getText());
        } 
    }
    

    And then call it to your JTextField in your main method like so:

    private JTextField textField1; // just showing the name of the JTextField
    textField1.addKeyListener(new textChangedListener());