Let's say you created a JPanel like so:
JPanel myJPanel = new JPanel;
you can use:
myJPanel.getMousePosition().x and myJPanel.getMousePosition().y to get the x and y coordinates of the mouse respectively. These will be relative to the top right corner of your JPanel.
Be careful, if your mouse isn't inside the panel, or the panel isn't visible, this will return a null value, so, if you ever want to call these functions, wrap the code that uses them inside a try like so:
try{ [insert code that uses myJPanel.getMousePosition().x/y here, if your mouse isn't inside the JPanel or the JPanel isn't visible, the code here will not be executed] }catch(NullPointerException e) {[if your mouse isn't inside the JPanel or the JPanel isn't visible, code placed here will be executed]}
This will stop your code throwing errors in cases where your mouse is outside the bounds of the JPanel or your JPanel isn't visible.
This can work well if you only ever intend to execute the code when your mouse is inside a visible JPanel, but otherwise, I would stick to other methods to get the mouse coordinates.
It's useful for doing things such as clicking on objects inside your JPanel, but it does have limitations.
MouseListener?MouseMotionListener?