Why does getX () getY () from MouseEvent seem to be offset from the actual coordinate?

I have a JPanel embedded inside a JFrame . JPanel added to CENTER BorderLayout . I use the following code to draw, but MouseEvent getX() and getY() seem to compensate for the actual coordinate. Why?

Corresponding code: -

 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

+6
source share
1 answer

You may have added a mouse listener to the JFrame (not the panel), so the getX and getY values ​​are relative to the JFrame. Then the offsets are the borders of the JFrame and the top line of the header.

+12
source

Source: https://habr.com/ru/post/888378/


All Articles