java 为什么 MouseEvent 的 getX() getY() 似乎偏离了真实坐标?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6040011/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why does the getX() getY() of MouseEvent seem to offset from the real coordinate?
提问by AppleGrew
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?
我有一个JPanel
嵌入在JFrame
. JPanel
在加入CENTER
的BorderLayout
。我正在使用以下代码在其上绘制,但MouseEvent
'sgetX()
和getY()
似乎偏移了真实坐标。为什么?
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);
}
回答by Andreas Dolk
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.
也许您已将鼠标侦听器添加到 JFrame(而不是面板),因此 getX 和 getY 值是相对于 JFrame 的。然后偏移量是 JFrame 边框和上标题栏。