Programmatically trigger a key events in a JTextField?

23,229

Solution 1

  • 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

Solution 2

You can construct Event by yourself and then call dispatchEvent on JTextField.

  KeyEvent keyEvent = new KeyEvent(...); //create
  myTextField.dispatchEvent();

For parameters of KeyEvent can refer KeyEvent constructors

Share:
23,229
ktulinho
Author by

ktulinho

Software Engineer with 12 years of experience developing, deploying and maintaining client and server applications. Ability to design and develop applications using Object Oriented concepts, Software Engineering concepts and methodologies such as Scrum and Agile. Specialties: Java EE, Java SE, Maven, Git, SQL, IntelliJ, Databases and a bit of DevOps. Continuously improving skills and knowledge through courses, articles and technical conferences. Interested by: Serverless, Cloud and Server-Side Applications; Desktop and mobile application design, development, usability and improving user experience; New technologies such as IoT, Machine Learning, VR and video games!

Updated on November 27, 2020

Comments

  • ktulinho
    ktulinho over 3 years

    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.

  • Robin
    Robin over 11 years
    -1 There is already a binding for the ENTER key. It will trigger the ActionListener attached to the text field. Overriding this might cause subtle issues
  • David Kroukamp
    David Kroukamp over 11 years
    @Robin I see your point +1 thank you for the knowlegde.. updated code
  • mKorbel
    mKorbel over 11 years
    I bet that is only about DocumentListener, dispatchEvent(); could be usefull to simulating DocumentListener from KeyListener, (now coming reason why I commenting...) or your answer going another direction, then have to add more detailed description about your idea
  • mKorbel
    mKorbel over 11 years
    How do I problematically trigger a key pressed event on a JTextField :-) I bet that is only about DocumentListener, even ActionListner returns whole Document
  • Nikolay Kuznetsov
    Nikolay Kuznetsov over 11 years
    @mKorbel, can you please let me know the logical chain how you come up to DocumentListener? Because I have never used it and here it is never mentioned. But dispatchEvent() I have used for JScrollPane and it worked fine. Do you think it is not suitable in this case?
  • mKorbel
    mKorbel over 11 years
    key event are implemented in Document, Document is model for JTextComponents, you can to listening all typed chars by add DocumentListener :-) never add KeyListener (my view) to Swing *JComponents, only if is there real reason e.i. combinations of 4-5 keys are pressed or for another ZOO came from keyboard
  • Nikolay Kuznetsov
    Nikolay Kuznetsov over 11 years
    @mKorbel, ok thanks, I would need to read about internals of JTextComponent. However, if the author still wants to use the code he provided us, I guess my answer might be useful to him.
  • mKorbel
    mKorbel over 11 years
    hehehe I see, then OP will returns with a few question or to creating mess,
  • David Kroukamp
    David Kroukamp over 11 years
    @mKorbel But Why go through all of that if we simply want to catch enter pressed and can via actionListener. I guess you are under the assumption the OP is performing validation checks... +1 this would be the way to go than
  • mKorbel
    mKorbel over 11 years
    @David Kroukamp I'm "confused" from this question, better could be waiting for OPs whatever, nobody knows
  • David Kroukamp
    David Kroukamp over 11 years
    @mKorbel true, though I'd lean with DocumentFilter and not Listener if it is the case
  • Alex Barker
    Alex Barker almost 11 years
    If anyone else is wondering why the example keeps repeating the enter key, it is because robot.keyRelease(KeyEvent.VK_ENTER) is never called.
  • Edu Costa
    Edu Costa about 5 years
    For JUnit purpose you can customize you JTextField as explained here stackoverflow.com/questions/47336703/…