开发者

How do I move the image in JPanel

开发者 https://www.devze.com 2023-02-08 10:34 出处:网络
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 fin开发者_如何学JAVAd very simple version. I spent lot of time and I found t

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 fin开发者_如何学JAVAd 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消