为什么 MouseEvent 的 getX() getY() 似乎偏离了真实坐标? [英] Why does the getX() getY() of MouseEvent seem to offset from the real coordinate?

查看:43
本文介绍了为什么 MouseEvent 的 getX() getY() 似乎偏离了真实坐标?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 JFrame 中嵌入了一个 JPanel.JPanel 添加在BorderLayoutCENTER.我使用下面的代码来绘制它,但 MouseEventgetX()getY() 似乎偏移了真实坐标.为什么?

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?

相关代码为:-

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

推荐答案

也许您已将鼠标侦听器添加到 JFrame(而不是面板),因此 getX 和 getY 值是相对于 JFrame 的.然后偏移量是 JFrame 边框和上标题栏.

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.

这篇关于为什么 MouseEvent 的 getX() getY() 似乎偏离了真实坐标?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆