Java – Topic
30
(Drag & Drop)
LESSON NOTE
MULTIPLE
LISTENERS/INTERFACES
A class can implement more than one
interface at a time. You simply need to
list the interfaces separated by a comma.
For example:
public class
FunApplet extends Applet implements KeyListener, MouseListener
Inside such a class, you will need
both statements:
addKeyListener(this);
addMouseListener(this);
And of course, you will have to
implement all methods from both interfaces.
MOUSEMOVEMENTLISTENER
INTERFACE
You may think that you are currently
able to watch for any type of event on the mouse or keyboard right now. You’re wrong. There are some mouse events for which you need to use a different
listener.
The MouseMovementListener interface
provides the following event-related methods:
void
mouseDragged(MouseEvent e)
void mouseMoved(MouseEvent e)
The mouseDragged method is executed
when the mouse is dragged (moved while button is down). The mouseMoved method is executed when the
mouse is moved with button up.
EXAMPLE
The following applet will allow you
to click on a circle and drag it around as you wish. When you release the click, the circle will no longer be dragged
around. The technique we will use will
combine the use of the mouseClicked and mouseReleased events from the
MouseListener interface along with the mouseMoved event from the
MouseMotionListener.
Click here to see the applet. Click here to see the code.