MouseMotionListener 不会将坐标传输到 Canvas
Posted
技术标签:
【中文标题】MouseMotionListener 不会将坐标传输到 Canvas【英文标题】:MouseMotionListener does not transfer coordinates to the Canvas 【发布时间】:2019-01-04 15:01:39 【问题描述】:我希望 Mouse 类中的坐标转到 Paint 方法中的 Paint 类。并且正方形随着鼠标的移动而移动。但是坐标没有传输。
g.drawRect(mouse.getX(), mouse.getY(), 10, 10);
mouse.getX(), mouse.getY() 仅从开头开始。之后不会改变。
类绘制点
public class DrawPoints
Frame f;
KeyBoard key;
Mouse mouse;
Paint c;
public void GUI()
f = new Frame("DrawPoints");
f.setSize(300, 300);
mouse = new Mouse(); // edit
c = new Paint(mouse); // edit
c.setSize(300, 300);
c.setBackground(Color.WHITE);
c.addMouseListener(mouse);
c.addMouseMotionListener(mouse);
key = new KeyBoard();
c.addKeyListener(key);
f.add(c);
f.pack();
f.setVisible(true);
f.addWindowListener(new WindowAdapter()
@Override
public void windowClosing(WindowEvent e)
System.exit(0);
);
类绘画
class Paint extends Canvas
Mouse mouse; // edit
public Paint() // added
mouse = new Mouse();
@Override
public void paint(Graphics g)
g.drawRect(mouse.getX(), mouse.getY(), 10, 10);
repaint(); // added
类鼠标
class Mouse implements MouseListener, MouseMotionListener
private int x;
private int y;
public int getX()
return this.x;
public int getY()
return this.y;
// MouseMotionListener
@Override
public void mouseMoved(MouseEvent e)
x = e.getX();
y = e.getY();
//System.out.println(e.getX() + " " + e.getY());
@Override
public void mouseDragged(MouseEvent e)
System.out.println("mouseDragged");
【问题讨论】:
【参考方案1】:我不知道其他类,但我认为问题是您创建了不同的鼠标对象。将 new Mouse() 移动到 new Paint() 之前,并将 new Paint 更改为 Paint(mouse)。 DrawPoints 类:
public class DrawPoints
Frame f;
KeyBoard key;
Mouse mouse;
Paint c;
public void GUI()
f = new Frame("DrawPoints");
f.setSize(300, 300);
mouse = new Mouse();
c = new Paint(mouse);
c.setSize(300, 300);
c.setBackground(Color.WHITE);
c.addMouseListener(mouse);
c.addMouseMotionListener(mouse);
key = new KeyBoard();
c.addKeyListener(key);
f.add(c);
f.pack();
f.setVisible(true);
f.addWindowListener(new WindowAdapter()
@Override
public void windowClosing(WindowEvent e)
System.exit(0);
);
Paint 类:将 Paint() 更改为 Paint(Mouse mouse) 并将 new Mouses() 行更改为 this.mouse = mouse;
class Paint extends Canvas
Mouse mouse;
public Paint(Mouse mouse)
this.mouse = mouse;
@Override
public void paint(Graphics g)
g.drawRect(mouse.getX(), mouse.getY(), 10, 10);
【讨论】:
您的代码有帮助。但是添加 c.addMouseMotionListener (mouse);和 c.addMouseListener(mouse);在 Paint 类之后需要。在我正确回答的答案中。【参考方案2】:忘记您不应该使用 AWT 库进行编码这一事实,因为该 GUI 库已经过时 20 多年,这不是您进行事件驱动编程的方式,因为您需要通知程序更改鼠标状态,你的代码没有做的事情。您的鼠标侦听器方法需要更改绘图 Paint 对象中的 x 和 y 属性,然后在同一对象上调用 repaint()
。
【讨论】:
感谢提醒我repaint()方法;并指出错误。以上是关于MouseMotionListener 不会将坐标传输到 Canvas的主要内容,如果未能解决你的问题,请参考以下文章
如何将自定义的 MouseMotionListener 添加到 JPanel?