Programmatically trigger a key events in a JTextField?

和自甴很熟 提交于 2019-11-27 16:23:15
David Kroukamp
  • 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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!