tags:

views:

40

answers:

2

I have a button and when I use mouse on the button I want to know the mouse x,y coords relative to the frame

How can I do that?

+1  A: 

register a MouseListener and implement the corresponding events. MouseEvent has getX and getY methods that can give you the mouse position.

Faisal Feroz
Yes but when I'm in the button the JFrame does not fire that event
xdevel2000
Try this code inside the button's event listener: PointerInfo a = MouseInfo.getPointerInfo(); Point b = a.getLocation(); int x = (int) b.getX(); int y = (int) b.getY();
Faisal Feroz
No it give me the coords relative to the button not to the frame!
xdevel2000
Checkout the SwingUtilities class. It has helper methods to convert MouseEvent co-ordinates and other utility methods for converting points relative to components and screen.http://download.oracle.com/javase/1.4.2/docs/api/javax/swing/SwingUtilities.html
Faisal Feroz
A: 

getBounds() gives you a Rectangle with the position and dimensions of the button relative to its parent. In my example the parent is the JFrame.

public class Click { 
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                final JFrame f = new JFrame("Click pos");
                f.setSize(640, 480);

                final JButton b = new JButton("Click Me!");
                b.addMouseListener(new MouseAdapter() {
                    public void mouseClicked(MouseEvent e) {
                        final JButton bb = (JButton) e.getSource();
                        final Rectangle bbox = bb.getBounds();
                        final int x = bbox.x + e.getX();
                        final int y = bbox.y + e.getY();
                        JOptionPane.showMessageDialog(f, "pos: " + x + " " + y);
                    }
                });
                f.getContentPane().add(b, BorderLayout.SOUTH);
                f.setVisible(true);
            }
        });
    }
}

Edit:
With the helper methods from SwingUtilities the mouseClicked method gets much simpler. And you get the correct coordinates independent of how many containers are between the JFrame and the JButton. I wasn't aware of them.

                    final JButton bb = (JButton) e.getSource();
                    Point p = SwingUtilities.convertPoint(bb, e.getPoint(), f);
                    JOptionPane.showMessageDialog(f, p);
Kintaro