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.
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.
If you want the same thing to happen both due to the mouse and a key press, wouldn't it make more sense to have a method called by both? That is, you have a method like fieldClicked
which gets called both by the MouseListener
and by the KeyListener
. This would be easier to debug--less mucking about with events, which can be very confusing--and probably more readable.
public void simulateKey(KeyEvent e, Component c) {
Field f = KeyEvent.class.getField("focusManagerIsDispatching");
f.setAccessible(true);
f.set(e, Boolean.TRUE);
c.dispatchEvent(e);
}
Send "Enter" to your JTextField. This was stolen from here.
What I want is when the user presses enter, it calls the same code as when they click anywhere in the frame
Still doesn't make sense to me.
When the user clicks any where on the frame a couple of things happen:
a) the text field loses focus
b) some other component gains focus
You could add an ActionListener to the text field. The ActionListener is invoked when the Enter key is pressed. But then how to you guess where on the frame to generate a mouse click? Seems like random logic to me.