How can I get the current mouse coordinates while handling a KeyEvent in a keyPressed(KeyEvent) method?
Created May 4, 2012
Finlay McWalter The KeyEvent doesn't contain that information, but you
can do the following:
- Add both a KeyListener and a MouseMotionListener to the component you're interested in.
- In the mouseMoved() callback, store the MouseEvent in an instance variable.
- In the keyPressed() callback, get the last reported location of the mousepointer by calling getPoint() on that MouseEvent you stored.
This will work fine unless you need accurate performance in applications where the mouse is likely to be moving when the key is pressed (e.g. video games) - in which case you'll probably find that the reported mouse position appears to 'lag' the actual mouse pointer.