为什么MouseEvent的getX() getY()看起来与真实坐标有偏移?

发布于 2024-11-08 02:56:11 字数 1098 浏览 0 评论 0原文

我有一个嵌入在 JFrame 中的 JPanelJPanel 添加在 BorderLayoutCENTER 处。我使用以下代码在其上绘图,但 MouseEventgetX()getY() 似乎偏移了真实坐标。为什么?

相关代码是:-

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

我所说的偏移量

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

What I mean by offset

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

风铃鹿 2024-11-15 02:56:11

也许您已将鼠标侦听器添加到 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文