How can I get the current mouse coordinates while handling a KeyEvent in a keyPressed(KeyEvent) method?

Finlay McWalter

The KeyEvent doesn't contain that information, but you can do the following:

  1. Add both a KeyListener and a MouseMotionListener to the component you're interested in.
  2. In the mouseMoved() callback, store the MouseEvent in an instance variable.
  3. 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.