FileDocCategorySizeDatePackage
MouseDrag.javaAPI DocExample2957Sun Feb 08 21:33:50 GMT 2004None

MouseDrag

public class MouseDrag extends Component implements MouseListener, MouseMotionListener
MouseDrag -- implement simple mouse drag in a window.

Fields Summary
Image
curImage
The Image we are to paint
static Label
status
Kludge for showStatus
boolean
inDrag
true if we are in drag
int
startX
starting location of a drag
int
startY
int
curX
current location of a drag
int
curY
Constructors Summary
public MouseDrag(Image i)

		super();
		curImage = i;
		setSize(300,200);
		addMouseListener(this);
		addMouseMotionListener(this);
	
Methods Summary
public static voidmain(java.lang.String[] av)


	// "main" method
	     
		JFrame f = new JFrame("Mouse Dragger");
		Container cp = f.getContentPane();

		if (av.length < 1) {
			System.err.println("Usage: MouseDrag imagefile");
			System.exit(1);
		}
		Image im = Toolkit.getDefaultToolkit().getImage(av[0]);

		// create a MouseDrag object
		MouseDrag j = new MouseDrag(im);

		cp.setLayout(new BorderLayout());
		cp.add(BorderLayout.NORTH,
			new Label("Hello, and welcome to the world of Java"));
		cp.add(BorderLayout.CENTER, j);
		cp.add(BorderLayout.SOUTH, status = new Label());
		status.setSize(f.getSize().width, status.getSize().height);
		f.pack();
		f.setVisible(true);
		f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	
public voidmouseClicked(java.awt.event.MouseEvent e)
Called when the mouse has been clicked on a component.

	
public voidmouseDragged(java.awt.event.MouseEvent e)

		Point p = e.getPoint();
		// System.err.println("mouse drag to " + p);
		showStatus("mouse Dragged to " + p);
		curX = p.x; curY = p.y;
		if (inDrag) {
			repaint();
		}
	
public voidmouseEntered(java.awt.event.MouseEvent e)
Called when the mouse enters a component.

	
public voidmouseExited(java.awt.event.MouseEvent e)
Called when the mouse exits a component.

	
public voidmouseMoved(java.awt.event.MouseEvent e)

		showStatus("mouse Moved to " + e.getPoint());
	
public voidmousePressed(java.awt.event.MouseEvent e)
Called when the mouse has been pressed.

		Point p = e.getPoint();
		System.err.println("mousePressed at " + p);
		startX = p.x; startY = p.y;
		inDrag = true;
	
public voidmouseReleased(java.awt.event.MouseEvent e)
Called when the mouse has been released.

		inDrag = false;
		System.err.println("SELECTION IS " + startX + "," +
			startY + " to " + curX + "," + curY);
	
public voidpaint(java.awt.Graphics g)

		int w = curX - startX, h = curY - startY;
		Dimension d = getSize();
		g.drawImage(curImage, 0, 0, d.width, d.height, this);
		if (startX < 0 || startY < 0)
			return;
		System.err.println("paint:drawRect @[" + startX +"," + startY +
			"] size " + w + "x" + h);
		g.setColor(Color.red);
		g.fillRect(startX, startY, w, h);
	
public voidshowStatus(java.lang.String s)

		status.setText(s);