Box Mover

<< SimpleGameTutorial | FinalProjectsTrailIndex | MoveImage >>

This demonstrates how to move a box by dragging with a mouse

Box.java

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Rectangle;

public class Box extends Rectangle
{
	private Color color;
	public Box(Color c){
		super(10,10,24, 24);	
		color=c;
	}	
	public void draw(Graphics g){
		g.setColor(color);
		int size=(int)this.getHeight();
		g.fillRect((int)this.getX()-size/2, (int)this.getY()-size/2, size, size);
	}
}

BoxMover.java

import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.*;

public class BoxMover extends Applet implements  MouseMotionListener
{
	Box box1;
	public void init(){
		box1=new Box(Color.RED);
		box1.setLocation(20, 20);
		addMouseMotionListener(this);
	}
	public void paint(Graphics g){
		box1.draw(g);
	}
	@Override
	public void mouseDragged(MouseEvent e) {
		box1.setLocation(e.getPoint());
		repaint();
	}

	@Override
	public void mouseMoved(MouseEvent e) {
	}


}