Matt Searle Matt Searle - 10 months ago 60
Java Question

Origin of Java.awt.component for MouseEvent.getX()

I am trying to calculate the distance I move a mouse within a box, I am using the MouseEvent.getX() and MouseEvent.getY() to calculate the start position of the mouse and then I have another method saving the position and calculating the distance the mouse has moved. Here is some code I wrote to demonstrate this.

BlankArea.addMouseMotionListener(new MouseMotionListener(){
@Override
public void mouseMoved(MouseEvent mm){
System.out.println("Position (" + mm.getX() + ", "
+ mm.getY() + ")");
savePosition(mm.getX(), mm.getY());
}

@Override
public void mouseDragged(MouseEvent md) {
System.out.println("Position (" + mm.getX() + ", "
+ mm.getY() + ")");
savePosition(mm.getX(), mm.getY());
}
});


My Question is: The Java API states that getX() & getY() returns the horizontal & vertical coordinate relative to the source component respectively. What is the source component? What unit is the output coordinate measured in?

Answer Source

To answer your questions:

1) What is the source component?

Like Mr.777 said, it is the component that you added the listener to, so in your example it is BlankArea.

2) What unit are the output coordinates measured in?

Like Mr.777 said, they are measured in pixels with the origin (0, 0) being at the top-left of the component.

I would recommend reading some of the Java tutorials online. Here is a good page to look at the Java coordinate system Coordinates (Java Tutorial).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download