得到鼠标X,Y坐标相对于一个框架

时间:2010-09-17 10:13:17

标签: java events

我有一个按钮,当我在按钮上使用鼠标时,我想知道鼠标x,y相对于框架的坐标

我该怎么做?

2 个答案:

答案 0 :(得分:1)

getBounds()为您提供Rectangle,其中包含按钮相对于其父级的位置和尺寸。在我的示例中,父级是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);
            }
        });
    }
}

编辑:
使用SwingUtilities的辅助方法,mouseClicked方法变得更加简单。并且您可以获得正确的坐标,而不管JFrameJButton之间的容器数量。我不知道他们。

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

答案 1 :(得分:0)

注册MouseListener并实施相应的事件。 MouseEvent具有getX和getY方法,可以为您提供鼠标位置。

相关问题