鼠标的坐标?

时间:2011-11-08 02:24:21

标签: java swing mouse

public class mouse extends JFrame {
    private int x, y;
    private JLabel label;

    public mouse() {
        JPanel panel = new JPanel();
         addMouseMotionListener(new MouseMotion());
         label = new JLabel();
         panel.add(label);
         setPreferredSize(new Dimension(400, 200));
         add(panel, BorderLayout.SOUTH);
         pack();
         setVisible(true);
    }
    private class MouseMotion extends MouseMotionAdapter {
        public void mouseMoved(MouseEvent e) {
            x = e.getX();
            y = e.getY();
            label.setText("mouse coordinate " + "(" + x + "," + y + ")");
    }}
    public static void main(String[]args) {
        mouse a = new mouse();
    }
}

当我将鼠标移动到边框时,它不是(0,0)。为什么?例如,我将鼠标移动到左上角,它显示(4,30)而不是(0,0)。

1 个答案:

答案 0 :(得分:5)

将MouseListener或MouseMotionListener添加到JFrame的contentPane,而不是JFrame本身,否则您必须担心边框,菜单,插图等。例如:

getContentPane().addMouseMotionListener(new MouseMotion());

另外,请格式化您的代码,以便我们阅读。