如何在 Java 中让 Graphic2D 对象精确跟随鼠标指针?
在下面的代码中,我只是使用鼠标侦听器来获取鼠标的 XY 坐标,然后调用重绘。在绘制方法中,我使用相同的 XY 坐标作为位置绘制了一个矩形。矩形确实跟随,但与鼠标指针有一定距离。我希望矩形的左上角能够触摸鼠标指针。
我做错了什么吗?
为什么我的鼠标指针和 Rectangle 对象之间有一段距离?
public void mouseMoved(MouseEvent e){
x = e.getX();
y = e.getY();
repaint();
}
public class Canvas extends JPanel{
Canvas(){}
public void paint(Graphics g){
Graphics2D g2 = (Graphics2D)g;
g2.setPaint(Color.red);
g2.fillRect(x, y, 50, 50);
}
}
In the code below I have simply used a mouse listener to get the XY coordinates of the the mouse, and then call for a repaint. Within the paint method I've drawn a rectangle using the same XY coordinates for position. The rectangle does follow but at a distance from the mouse pointer. I'd expect the top left corner of the rectangle to touch the mouse pointer.
Am I doing something wrong?
Why is there a distance between my mouse pointer and the Rectangle object?
public void mouseMoved(MouseEvent e){
x = e.getX();
y = e.getY();
repaint();
}
public class Canvas extends JPanel{
Canvas(){}
public void paint(Graphics g){
Graphics2D g2 = (Graphics2D)g;
g2.setPaint(Color.red);
g2.fillRect(x, y, 50, 50);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不要调用您的类 Canvas,有一个使用该名称的 AWT 组件,因此会让人感到困惑。
自定义绘制是通过重写 JPanel 的paintComponent()方法而不是paint()方法来完成的。
您没有显示将 MouseListener 添加到面板的位置。您可能会将其添加到框架中。
如果您需要更多帮助,请发布您的 SSCCE 来说明问题。
Don't call your class Canvas, there is an AWT component by that name so it becomes confusing.
Custom painting is done by overriding the paintComponent() method of the JPanel, not the paint() method.
You don't show where you add the MouseListener to the panel. You are probably adding it to the frame instead.
If you need more help then post your SSCCE that demonstrates the problem.