Login | Register   
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Java Language
Expertise: Beginner
Apr 7, 2000

Mouse Click Coordinate

Question:
I know how to detect a mouse click with a MouseListener, but how do I obtain the coordinates associated with the click?

Answer:
If you already know how to detect a mouse click, you're just one step away from being able to retrieve the coordinates associated with the click. To detect a mouse click in a component, you register a MouseListener with the addMouseListener() method defined in java.awt.Component. This allows you to detect when the mouse is pressed, released, or clicked in a component. It also allows you to detect when the mouse enters or leaves the component. Each time one of these events occurs, the appropriate MouseListener method is invoked with a MouseEvent as an argument.

For all of these events, the MouseEvent will contain the coordinates of the mouse at the time of the event. You can get the coordinates together as a Point object with getPoint(), or separately with getX() and getY(). The coordinates will be returned relative to the component reporting the event. You can use translatePoint(int x, int y) to convert the coordinates to be relative to the entire screen or some other component.

DevX Pro
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap