获取光标坐标作为相对于JPanel的点

时间:2013-12-01 05:54:29

标签: java swing cursor location jpanel

如何获取JPanel上光标的坐标?我试过用这个:

MouseInfo.getPointerInfo().getLocation();

但是这会返回屏幕上的位置。我尝试使用mouseMoved(MouseEvent m)方法,然后从m.getX()m.getY()获取坐标,但该方法未被调用。 (我正在使用MouseListener)。

这是我的Panel类:

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);
}

}

1 个答案:

答案 0 :(得分:3)

mouseMoved事件由MouseMotionListener处理。