4

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.

ktulinho
  • 3,870
  • 9
  • 28
  • 35
  • Why don't you call directly `doStuff()`? – Guillaume Polet Nov 26 '12 at 10:50
  • don´t get your problem, it is working. do you get any error? – SomeJavaGuy Nov 26 '12 at 10:50
  • 1
    Use an Actionlistener instead of and KeyAdapter and it should work – SomeJavaGuy Nov 26 '12 at 10:51
  • 3
    There is normally no need to add a `KeyListener` to a `JTextField`. You have `DocumentListener`s, `DocumentFilter`s and `ActionListener`s at your disposal. In this case you would need the `ActionListener` which is automatically triggered when pressing ENTER – Robin Nov 26 '12 at 11:02
  • -1 until you explain _what_ you want to achieve – kleopatra Nov 26 '12 at 11:41
  • @kleopatra Ok, so what I want to achieve is to call whatever code is assigned to the ENTER key. Only thing I know is that the textfield will be listening for ENTER key events. The code I wrote above is just to show how my textfield has its key listener declared. It is not the part I'm actually trying to achieve. – ktulinho Nov 26 '12 at 13:30

2 Answers2

17
  • 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

Community
  • 1
  • 1
David Kroukamp
  • 36,155
  • 13
  • 81
  • 138
  • 2
    -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 – Robin Nov 26 '12 at 11:01
  • @Robin I see your point +1 thank you for the knowlegde.. updated code – David Kroukamp Nov 26 '12 at 11:16
  • 2
    `How do I problematically trigger a key pressed event on a JTextField` :-) I bet that is only about DocumentListener, even ActionListner returns whole Document – mKorbel Nov 26 '12 at 11:28
  • @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 – David Kroukamp Nov 26 '12 at 12:00
  • @David Kroukamp I'm "confused" from this question, better could be waiting for OPs whatever, nobody knows – mKorbel Nov 26 '12 at 12:01
  • @mKorbel true, though I'd lean with `DocumentFilter` and not `Listener` if it is the case – David Kroukamp Nov 26 '12 at 12:09
  • If anyone else is wondering why the example keeps repeating the enter key, it is because robot.keyRelease(KeyEvent.VK_ENTER) is never called. – Alex Barker Jul 07 '13 at 19:27
4

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

Nikolay Kuznetsov
  • 9,467
  • 12
  • 55
  • 101
  • 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 Nov 26 '12 at 11:26
  • @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? – Nikolay Kuznetsov Nov 26 '12 at 11:30
  • 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 – mKorbel Nov 26 '12 at 11:36
  • @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. – Nikolay Kuznetsov Nov 26 '12 at 11:40
  • hehehe I see, then OP will returns with a few question or to creating mess, – mKorbel Nov 26 '12 at 11:58
  • For JUnit purpose you can customize you JTextField as explained here https://stackoverflow.com/questions/47336703/simulate-key-press-in-junit-tests/54950578#54950578 – Edu Costa Mar 01 '19 at 19:12