鼠标的坐标?

zha*_*ing 2 java mouse swing

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

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

Hov*_*els 5

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

getContentPane().addMouseMotionListener(new MouseMotion());
Run Code Online (Sandbox Code Playgroud)

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