zhangyiying
zhangyiying

Reputation: 424

The coordinate of 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();
    }
}

When I move mouse to border, it is not (0,0). Why? For example, I move mouse to top left corner, it shows (4,30) rather than (0,0).

Upvotes: 2

Views: 177

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285403

Add the MouseListener or MouseMotionListener to the JFrame's contentPane, not the JFrame itself, else you have to worry about borders, menus, insets, and the like. For example:

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

Also, please format your code so we can read it.

Upvotes: 5

Related Questions