我在 JFrame
中嵌入了一个 JPanel
。 JPanel
被添加到BorderLayout
的CENTER
。我正在使用以下代码对其进行绘制,但 MouseEvent
的 getX()
和 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);
}
最佳答案
也许您已将鼠标监听器添加到 JFrame(而不是面板),因此 getX 和 getY 值是相对于 JFrame 的。然后偏移量是 JFrame 边框和上标题栏。
关于java - 为什么MouseEvent的getX() getY() 好像和真实坐标有偏移?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6040011/