Robin92
Robin92

Reputation: 561

Component coordinates

I'm trying to get components coordinate's in relation to its parent. For example, when I have a JFrame of size 500x500, which has a child - JPanel - at [50, 10] I should get [50, 10] as a result. However easy may it seem, I'm keep getting wrong coords ([0, 0] or [3, 24]).

Here's my JPanel's code:

class MyPanel extends JPanel implements MouseListener { 
    private Component parent;   
    private String strName;

    public MyPanel(Component pr, String name, int w, int h) {
        super();

        parent = pr;
        strName = new String(name);

        this.setLayout(null);
        this.setSize(w, h);
        this.setBackground(Color.WHITE);
        this.addMouseListener(this);

        this.setVisible(true);
    }

    /* MouseListener implementation */
    public void mouseClicked(MouseEvent event) {
            int x = event.getX(); int y = event.getY();
            Point pnt = new Point(SwingUtilities.convertPoint(this, new Point(0, 0), parent));
            System.out.println(strName + ":" + pnt);    
    }

    public void mouseEntered(MouseEvent event) { }

    public void mouseExited(MouseEvent event) { }

    public void mousePressed(MouseEvent event) { }

    public void mouseReleased(MouseEvent event) { }
}

Any ideas?

Java binary & source code (*.tar.xz)

Upvotes: 4

Views: 1037

Answers (1)

David Kroukamp
David Kroukamp

Reputation: 36423

Try this:

Point pnt = new Point(SwingUtilities.convertPoint(this, event.getPoint(), parent));

isnatead of using (Which is never used BTW atleast in provided snippet):

    int x = event.getX();
    int y = event.getY();

and you shouldnt do this:

Point pnt = new Point(SwingUtilities.convertPoint(this, new Point(0,0), parent));

or else the co-ordinates returned will always be in respect of (0,0).

You could also do (which I think you were going to but forgot x and y :P):

    int x = event.getX();
    int y = event.getY();
    Point pnt = new Point(SwingUtilities.convertPoint(this,
                                               new Point(x,y), parent));

EDIT:

If i understand what you want then why bother with all that code? In each JPanels MouseListener's mouseClicked() do this:

public void mouseClicked(MouseEvent event) {
    System.out.println(this.getX()+" "+this.getY());//print x and why co-ords for MyJpanel
}

Upvotes: 5

Related Questions