开发者

Why does the getX() getY() of MouseEvent seem to offset from the real coordinate?

I have a JPanel embedded inside a JFrame. JPanel is added at CENTER of BorderLayout. I am using the following code to draw on it but the MouseEvent's getX() and getY() seem to offset the real coordinate. Why?

The relevant code is:-

private Image backBuffer = createImage(getWidth(), getHeight());

public void mouseDragged(MouseEvent e) {
    //System.out.println("Canvas.mouseDragged()");
    Graphics2D g2d = (Graphics2D) backBuffer.getGraphics();
    int x = e.getX(), y = e.getY();
    if(lastCoord == null) {
        g2d.drawRect(x, y, 0, 0);
    } else {
        g2d.drawLine(lastCoord[0], lastCoord[1], x, y);
    }
    lastCoord = new Integer[]{x, y};
    repaint();
}

public void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D graphics2D = (Graphics2D) g;
    graphics2D.setColor(Color.black);
    graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
        RenderingHints.VALUE_ANTIALIAS_ON)开发者_如何学编程;
    graphics2D.drawImage(backBuffer, 0, 0, null);
}

Why does the getX() getY() of MouseEvent seem to offset from the real coordinate?


Maybe you've added your mouse listener to the JFrame (and not to the panel) so getX and getY values are relative to the JFrame. Then the offsets are the JFrame borders and upper title bar.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜