Search code examples
javaswingcursorlocationjpanel

Get Cursor Coordinates as Point Relative to JPanel


How can I obtain the coordinates of the cursor on a JPanel? I've tried using this:

MouseInfo.getPointerInfo().getLocation();

But this returns the location on the screen. I tried using the mouseMoved(MouseEvent m) method and then get the coordinates from m.getX() and m.getY(), but that method isn't being called. (I am using MouseListener).

Here's my Panel class:

public class Panel extends JPanel implements Runnable, KeyListener, MouseListener {

// serial
private static final long serialVersionUID = -2066956445832373537L;

// dimensions
public static final int WIDTH = 800;
public static final int HEIGHT = 600;

// game loop
private Thread thread;
private boolean running;
private final int FPS = 30;
private final int TARGET_TIME = 1000 / FPS;

// drawing
private BufferedImage image;
private Graphics2D g;

// status handler
private StatusHandler statusHandler;

// constructor
public Panel() {
    setPreferredSize(new Dimension(WIDTH, HEIGHT));
    setFocusable(true);
    requestFocus();
}

public void addNotify() {
    super.addNotify();
    if(thread == null) {
        addKeyListener(this);
        addMouseListener(this);
        thread = new Thread(this);
        thread.start();
    }
}

public void run() {

    init();

    long start;
    long elapsed;
    long wait;

    // game loop
    while(running) {

        start = System.nanoTime();

        update();
        render();
        renderToScreen();

        elapsed = System.nanoTime() - start;

        wait = TARGET_TIME - elapsed / 1000000;
        if(wait < 0) wait = TARGET_TIME;

        try {
            Thread.sleep(wait);
        }
        catch(Exception e) {
            e.printStackTrace();
        }

    }

}

private void init() {
    running = true;
    image = new BufferedImage(WIDTH, HEIGHT, 1);
    g = (Graphics2D) image.getGraphics();
    statusHandler = new StatusHandler();
}

private void update() {
    statusHandler.update();
}

private void render() {
    statusHandler.render(g);
}

private void renderToScreen() {
    Graphics g2 = getGraphics();
    g2.drawImage(image, 0, 0, WIDTH, HEIGHT, null);
}

public void keyTyped(KeyEvent key) {}
public void keyPressed(KeyEvent key) {
    KeyInput.setKey(key.getKeyCode(), true);
}
public void keyReleased(KeyEvent key) {
    KeyInput.setKey(key.getKeyCode(), false);
}

public void mouseClicked(MouseEvent m) {}
public void mouseReleased(MouseEvent m) {
    MouseInput.setButton(m.getButton(), false);
    MouseInput.setMouseEvent(m);
}
public void mouseEntered(MouseEvent m) {}
public void mouseExited(MouseEvent m) {}
public void mousePressed(MouseEvent m) {
    MouseInput.setButton(m.getButton(), true);
    MouseInput.setMouseEvent(m);
}

}


Solution

  • The mouseMoved event is handled by a MouseMotionListener.