gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 11:03:38 25 4
gpt4 key购买 nike

首先,这是相关代码:

    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

关于java - 显示 (x,y) 偏移量的 MouseMotionListener,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33140789/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com