开发者

Why the pointer x and y position never go below 4 and 23?

开发者 https://www.devze.com 2023-02-04 10:02 出处:网络
I have the following code import javax.swing.*; import java.awt.event.*; public class MousePos implements MouseMotionListener{

I have the following code

import javax.swing.*;


import java.awt.event.*;

public class MousePos implements MouseMotionListener{

    JLabel x = new JLabel();
    JLabel y = new JLabel();

    public static void main(String[] args) {
        MousePos mp =new MousePos();
        mp.go();
    }

    public void go() {
        JFrame frame = new JFrame("Mouse Position");

        frame.addMouseMotionListener(this);

        JPanel p =new JPanel();
        p.add(x);
        p.add(y);

        frame.getContentPane().add(p);
        frame.setSize(150,150);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }

    @Override
    public void mouseDragged(MouseEvent e) {


    }

    @Override
    public void mouseMoved(MouseEvent e) {
        x.setText("X : " + e.getX());
        y.setText("Y : " +e.getY());

    }

}

which create a frame with two labels that hold the x position and y position of the mouse pointer on the form.

what I learned is the x value and y value would be 0 and 0 on the top left corner

the problem is the value never go below 4 for x and 23 fo开发者_JAVA百科r y.

Could anyone tell me why.

Thanks in advance.


frame.addMouseMotionListener(this);

The coordinates are relative to the frame and not to the content pane. 4 is the width of the frame's border, 23 the height of border plus frame "title area".

Try this instead:

p.addMouseMotionListener(this);

If you're listening to the frames mouse events by intention, note, that the frame unfortunatly does not fire events if the button is over the border or the title area... That's why you don't observer (0,0) if you point to the frames upper left corner.

0

精彩评论

暂无评论...
验证码 换一张
取 消