Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Obtaining position of cursor on JPanel

 
colin shuker
Ranch Hand
Posts: 750
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, I know how to use MouseListener and MouseMotionListener,
to react to MouseEvents such as pressing the mouse etc.

Then from within mousePressed(MouseEvent e), I can easily grab the
coordinates of the mouse using e.getX(), and e.getY(),

But can I just grab the coordinates of the mouse from where it is?
Without having to press/click/drag/release etc.

Thanks
 
colin shuker
Ranch Hand
Posts: 750
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok, I found this..



Not sure exactly how it works, does it give the location of the
mouse in whichever JPanel or Component its in?
 
colin shuker
Ranch Hand
Posts: 750
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, is there a better way to get the cursor position of mouse pointer inside a JPanel.

I'm thinking of using...


Then the difference in X and Y values should be the cursor position inside of the Component (assuming mouse is actually inside the component)

But will this still work for an applet which lies inside a browser?
It would take me quite a while to set the applet up, so I thought I would just ask first before I try experimenting.

Thanks
 
Craig Wood
Ranch Hand
Pie
Posts: 1535
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try overriding mouseMoved in your MouseMotionListener.
e.getPoint gives the mouse location in the source component coordinate system.
 
colin shuker
Ranch Hand
Posts: 750
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thats what I normally do, but that method only gets triggered when the mouse is moved, I want to get the coordinate after the completion of a certain process.

I seem to have it working fine, but I'm not sure if it will work in an applet or not, I guess it will
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic