Java - Cursor position relative to JFrame

zomy2000 :

Trying to have an object follow the cursor using:

int mx =(int) MouseInfo.getPointerInfo().getLocation().getX()-50;
Player.setX(mx);

in my tick method. However, this returns cursor position on screen, how can I make it relative to the JFrame itself? Is there maybe a way to read the position of the top-left point in the canvas so i can add an offset ?

Stefan :

Create a mouse listener, and fetch the coordinates from there:

public class SimpleFrame extends JFrame {
public static void main(String[] args) {
    SimpleFrame frame = new SimpleFrame();
    frame.setSize(new Dimension(200, 300));
    frame.setLocation(new Point(500, 600));
    frame.setVisible(true);
    frame.addMouseListener(new MouseListener() {
        @Override
        public void mouseReleased(MouseEvent e) {
            System.out.println(e.getX() + " / " + e.getY());
        }
        @Override
        public void mousePressed(MouseEvent e) {
        }
        @Override
        public void mouseExited(MouseEvent e) {
        }
        @Override
        public void mouseEntered(MouseEvent e) {
        }
        @Override
        public void mouseClicked(MouseEvent e) {
        }
    });
}
}

When you test this, you probably realize that you want to have the coordinates relative to something else, for example the main panel of your application. Then you create the mouselistener for that component:

SimpleFrame frame = new SimpleFrame();
JPanel mainPanel = new JPanel();
frame.add(mainPanel, ...);
mainPanel.addMouseListener(...

It is much better to do it this way, than to start substracting constants from the coordinates you get from the JFrame's mouseListener, since those "constants" will differ depending on OS etc.

And if you want to have event whenever the user moves the mouse, not only when he/she clicks it, use this:

    frame.addMouseMotionListener(new MouseMotionListener() {
        @Override
        public void mouseMoved(MouseEvent e) {
            System.out.println(e.getX() + " / " + e.getY());
        }
        @Override
        public void mouseDragged(MouseEvent e) {
    });

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=362083&siteId=1