In this example you will see how to move image smoothly on mouse motion using Java.
To move an image, we have used the Listener interface that provides the mouse motion events in Java. So in this example you will learn where the MouseMotionListener interface is called to move an image on mouse motion. In this example we have used the JFrame class of javax.swing.* package that allows to create frame.
The methods mouseMoved() and mouseDragged() of Listener interface are defined in the code. The method mouseDragged() is invoked when a mouse button is pressed on the image. Then the image will dragged. The method mouseMoved() is invoked when the mouse cursor has been moved on to a image without pushing the image. The method checkImage() will create the Off-screen image if it has not been created. This method should always be called before using the off-screen image. To draw into the offscreen image, paintOffscreen(image.getGraphics()) is called. The g.drawImage(image, 0, 0, null) put the offscreen image on the screen.
Here is the code of SmoothMoveExample.java
Output will be displayed as:
Posted on: December 15, 2008 If you enjoyed this post then why not add us on Google+? Add us to your Circles