Ski
Ski

Reputation: 111

Getting the coordinates of the panel

Using mouseevents, I am able to get the x and y coordinates of the frame, yet I am unable to get the x and y coordinates of the panel. The below codes are me getting the x and y coordinates of the frame.

public void mouseMoved(MouseEvent e) {
    x = e.getX();
    y = e.getY();
    text = Integer.toString(x) +","+Integer.toString(y);

    Frame.frame.repaint();

}

The below codes are me trying to get the x and y coordinates of the panel, but it's painting out 0's instead. Paint.paint is the name of my jpanel. I don't know what I'm doing wrong. Please help if you can.

public void mouseMoved(MouseEvent e) {
    x = Paint.paint.getX();
    y = Paint.paint.getY();
    text = Integer.toString(x) +","+Integer.toString(y);

    Frame.frame.repaint();

}

Upvotes: 0

Views: 1117

Answers (1)

copeg
copeg

Reputation: 8348

If I understand right, your MouseListener is registered with the JFrame, and you wish to get the x/y relative to a JPanel contained within the JFrame. The x and y within the MouseEvent refer to the Component in which the MouseListener was registered. If you have a MouseListener registered on a Parent container, and which to get the coordinates of the MouseEvent relative to a child Component, you can using SwingUtilities to convert the coordinates

public void mousePressed(MouseEvent e){
    Point childCoordinate = SwingUtilities.convertPoint(parent, e.getPoint(), child);
}

Upvotes: 2

Related Questions