Search code examples
javaswingjtextfieldkeyevent

Programmatically trigger a key events in a JTextField?


How do I programmatically trigger a key pressed event on a JTextField that is listening for events on the ENTER?

The listener for key events on my JTextField is declared as follows:

myTextField.addKeyListener(new KeyAdapter() {

    @Override
    public void keyTyped(KeyEvent e) {
        if (e.getKeyChar() == KeyEvent.VK_ENTER) {
            // Do stuff
        }
    }
});

Thanks.


Solution

    • Do not use KeyListener on JTextField simply add ActionListener which will be triggered when ENTER is pressed (thank you @robin +1 for advice)

      JTextField textField = new JTextField();
      
      textField.addActionListener(new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent ae) {
               //do stuff here when enter pressed
          }
      });
      
    • To trigger KeyEvent use requestFocusInWindow() on component and use Robot class to simulate key press

    Like so:

    textField.requestFocusInWindow();
    
    try { 
        Robot robot = new Robot(); 
    
        robot.keyPress(KeyEvent.VK_ENTER); 
    } catch (AWTException e) { 
    e.printStackTrace(); 
    } 
    

    Example:

    import java.awt.AWTException;
    import java.awt.Robot;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.KeyEvent;
    import javax.swing.JFrame;
    import javax.swing.JTextField;
    import javax.swing.SwingUtilities;
    
    public class Test {
    
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    JFrame frame = new JFrame();
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    JTextField textField = new JTextField();
    
                    textField.addActionListener(new ActionListener() {
                        @Override
                        public void actionPerformed(ActionEvent ae) {
                            System.out.println("Here..");
                        }
                    });
                    frame.add(textField);
    
                    frame.pack();
                    frame.setVisible(true);
    
                    textField.requestFocusInWindow();
    
                    try {
                        Robot robot = new Robot();
    
                        robot.keyPress(KeyEvent.VK_ENTER);
                    } catch (AWTException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }
    

    UPDATE:

    As others like @Robin and @mKorbel have suggested you might want a DocumentListener/DocumentFiler (Filter allows validation before JTextField is updated).

    You will need this in the event of data validation IMO.

    see this similar question here

    it shows how to add a DocumentFilter to a JTextField for data validation. The reason for document filter is as I said allows validation before chnage is shown which is more useful IMO