简体   繁体   中英

How do I move the image in JPanel

I am very new to the Java Swing, I want to move the image in JPanel by using MouseInputAdaptor. I google it but I couldn't find very simple version. I spent lot of time and I found that I should use mouseDragged, mousePressed methods but how can I applied to the specific image, suppose If attempt to drag how do I make that image move??

Please explain me?

You can use mouseDragged() method to do this.

Take two global variable X and Y . now in paint method of JPanel draw you image like this:

 public void paintComponent(Graphics g) {
....
g.drawImage(image,X,Y,this);
....
}

and in your mouseDragged method do this:

 public void mouseDragged(MouseEvent e) {
          X = e.getX();
          Y = e.getY();
         repaint();
 }

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM