20-CS-694 Advanced Programming Techniques Spring 2012
Mouse Actions

Interfaces, Exceptions, Graphics, Animation, Threads, Reflection, Networking, RMI, JDBC, JNI

       Previous     Next        Applet Source     All lectures

Acting When The Mouse Is Dragged

Instructions for all applets: Move the mouse cursor to some point in the gray area." Press the mouse button and drag the mouse. The string 'Hello World' follows.

All applets contain two widgets - a JTextField which appears at the top of the applet and presents a short description of the applet, and a JPanel on which a 'Hello World' string is drawn. All applets implement the MouseMotionListener interface which requires coding methods mouseDragged and mouseMoved. The mouseDragged method in these examples records the new (moved) mouse cursor position and, depending on the applet, may also erase the string in its old position and draw it in its new position.

    0.   DragAnObject0.java

    Both widgets are declared in a single JFrame class that implements the MouseListener interface. Hence, the string 'Hello World' draws in the entire JFrame although it is desired to have it draw in the JPanel only. Drawing is done in the paint method so that events other than a mouse movement will redraw the string. The mouse position prior to a mouse motion event is stored as x_old and y_old so that the string may be erased in its old position before drawing it in its new position.
    1.   DragAnObject1.java

    The JPanel is declared in a class that is separate from the JFrame. This allows the MouseListener to operate only on the JPanel and not the JTextField. Hence, the string 'Hello World' draws only in the JPanelx. Drawing is still done in the paint method so that events other than a mouse movement will redraw the string. However, such redraws are handled better that in DragAnObject0. The mouse position prior to a mouse motion event is stored as x_old and y_old so that the string may be erased in its old position before drawing it in its new position.
    2.   DragAnObject2.java

    The JPanel is declared in a class that is separate from the JFrame. Drawing is still done in the paint method. The old mouse position is still stored.
 
    3.   DragAnObject3.java

    The JPanel is declared in a class that is separate from the JFrame. Drawing is done in mouseDragged only; paint is not implemented. Hence, the string disappears completely on a window resize. The old mouse position is stored as above to support erase. Since mouse position is obtained in the same method that does the drawing, there are no phantom splotches while dragging.
    4.   DragAnObject4.java

    Drawing is done in paint AND in mouseDragged. Method repaint is not overridden. This stops the phantom splotches that occurred in DragAnObject1.