显示 (x,y) 偏移量的 MouseMotionListener

MouseMotionListener showing (x,y) offset

首先附上相关代码:

    canvas = new CanvasPanel();
    canvas.setBackground(Color.white);
    canvas.addMouseListener(new PointListener());
    canvas.addMouseMotionListener(new PointListener());

    JSplitPane sp = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftPanel, canvas);


class CanvasPanel extends JPanel
{
    public void paintComponent(Graphics page)
    {
        super.paintComponent(page);

        if (mouseDragged == true)
        {
            page.drawRect(x1, y1, x3, y3);
            canvas.repaint();
        }
    }
}


class PointListener implements MouseListener, MouseMotionListener
{
    public void mousePressed (MouseEvent event)
    {
        mouseDragged = true;
        x1 = event.getX();
        y1 = event.getY();
    }
    public void mouseReleased (MouseEvent event)
    {
       // some code
    }

    public void mouseDragged(MouseEvent event)
    {
        x3 = event.getX();
        y3 = event.getY();
        canvas.repaint();
    }

所以这段代码的作用是,当我点击 canvas 组件时,它会绘制一个矩形的轮廓,并且当我拖动鼠标时尺寸会发生变化

但是,当我点击并开始拖动鼠标时,矩形的右下角出现了偏移。它似乎在我拖动鼠标的那一刻跳到更大的尺寸。有趣的是,我点击的canvas组件越靠近左上角,矩形的大小就越接近我用鼠标绘制的矩形。

我该如何解决这个问题?

请记住,drawRect 使用 xywidthheight 作为参数,您实际上应该使用点击之间的增量点和拖动点

也许像...

public void paintComponent(Graphics page)
{
    super.paintComponent(page);

    if (mouseDragged == true)
    {
        int x = Math.min(x1, x3);
        int y = Math.min(y1, y3);
        int width = Math.max(x1, x3) - x;
        int height = Math.max(y1, y3) - y;
        page.drawRect(x, y, width, height);
    }
}

并且,不要从 paint 方法中调用 repaint