How do I get my image to follow my mouse?

情到浓时终转凉″ 提交于 2019-12-04 19:55:23

Generally, you need some way to tell the UI that it should be updated.

Assuming that Main is some kind of component (and it's also responsible for painting the Player), you should be calling its repaint method in the mouseListener

But without more details, this is more of a guess

Updated

After a muck around with the code, the main problem, as I see it, is your trying to draw the image only the horizontal axis (x) using the vertical position (y)...

public void drawPlayer(Graphics g){
    //g.drawImage(p2Image, y, heightPosition, main);
    g.drawImage(p2Image, x, heightPosition, main);
}

To get it to work, you're going to have to uncomment the code in you mouseMoved method so that the x position updates.

You should also avoid painting to top level containers, the main reason (apart from the fact that you can screw up the paint process) is that top level containers are not double buffered.

Instead, you should move your entire game container over to something like a JPanel and override it's paintComponent method (and don't for get to call super.paintComponent)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!