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?
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?
register a MouseListener and implement the corresponding events. MouseEvent has getX and getY methods that can give you the mouse position.
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);