I am working on a Java project and need to have a keypress simulate a click on a JTextField. What I'm looking for is the equivalent of the JButton doClick() method.
I am trying to have the keypress "enter" perform the exact same function as a click on the JTextField.
Not sure what other info to provide. Thanks in advance.
OK, thanks for the help. I guess I wasn't being clear, but I have now discovered a way to make my code work thanks to some of your ideas.
I had already thought of just creating a private method that was called by both functions, but part of the code needs to know which JTextField the user is clicked on. I discovered .getFocusOwner(), which allows me to reference the current item with Focus (the JTextField). Something like this
public void keyPressed(KeyEvent e) {
if(e.getKeyCode()==KeyEvent.VK_ENTER) {
Object which = JFrame.getFocusOwner();
if(which.getClass() == JTextField.class)
foo(which);
}
}
public void mouseClicked(MouseEvent e) {
Object which = e.getSource();
if(which.getClass()== JTextField.class) {
foo(which);
}
}
There was probably a better way to do this, but basically I had an array of JTextFields and the program was functioning properly when users clicked on the next JTextField, but when pressing enter I didn't know how to call the JTextField that was just entered so I wanted to simulate a click on the JTextField (which calls for focus). I guess I should have just explained my whole problem.
Thank you.