Home Tutorial Java Swing Move Image in Java Swing


Share on Google+Share on Google+
Move Image in Java Swing
Posted on: October 31, 2009 at 12:00 AM
In this section, you will learn how to move an image using mouse.

How to Move Image in Java Swing

In this section, you will learn how to move an image using mouse. For this purpose, we have specified an image and using the MediaTracker class, the image is tracked by the method addImage(). The Graphics class then rendered this image on frame through the method drawImage(). Now to move this image, we have used public void mouseMoved() and public void mouseDragged() methods.

Here is the code:

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import javax.swing.border.TitledBorder;

public class MoveImage extends JFrame {
	ShowCanvas canvas;

	public MoveImage() {
		Container container = getContentPane();
		canvas = new ShowCanvas();
		setSize(300, 200);

	public static void main(String arg[]) {
		new MoveImage();

class ShowCanvas extends JPanel {
	int x, y;
	BufferedImage image;

	ShowCanvas() {
		setSize(450, 400);
		addMouseMotionListener(new MouseMotionHandler());

		Image img = getToolkit().getImage("node.jpg");

		MediaTracker mt = new MediaTracker(this);
		mt.addImage(img, 1);
		try {
		} catch (Exception e) {
			System.out.println("Image not found.");
		image = new BufferedImage(img.getWidth(this), img.getHeight(this),
		Graphics2D g2 = image.createGraphics();
		g2.drawImage(img, 0, 0, this);

	public void paintComponent(Graphics g) {
		Graphics2D g2D = (Graphics2D) g;
		g2D.drawImage(image, x, y, this);

	class MouseMotionHandler extends MouseMotionAdapter {
		public void mouseDragged(MouseEvent e) {
			x = e.getX();
			y = e.getY();

		public void mouseMoved(MouseEvent e) {


Related Tags for Move Image in Java Swing:

Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: October 31, 2009

Recommend the tutorial

Advertisements Advertisements