Friday, February 20, 2015

Simple Drag and Drop


We are going to implement a simple drag and drop function. The program will display a red block on the screen and you may drag and drop it to anywhere inside the window.

Mouse Event

For a simple implementation, we just need to implement two functions. One is known as mousePressed and the other is known as mouseDragged. These two functions are defined in two different interfaces. Hence we need to implement both interfaces. Though we are only interested in two functions, we still need to provide empty implementation for every function defined in MouseListener and MouseMotionListener

Basic Flow of Drag and Drop

  1. Remember the mouse position when the mouse is pressed. This is the starting point.
  2. When the mouseDragged event is received, calculate a displacement vector from the starting point to the current mouse position.
  3. Add the displacement vector to the position of the object.

The following is the implementation of step 1. All we have to do is just remembering the starting position when mouse is pressed.

The following is the implementation of step 2 and 3.


For a full demonstration, compile and run the following source code.

No comments:

Post a Comment