datalogo
Return to Unit Menu |  JavaBitsNotebook.com | MathBits.com | Terms of Use  | JavaMathBits.com

Mouse Click Drawing

It is possible to use a mouse click to reposition a figure that can be drawn on the screen. In this example, the initial figure (a red circle) will either:
PART 1: disappear and then reappear at any mouse click location, or
PART 2: stay in its original position and then be duplicated across the screen upon mouse clicks.

dividerdash

PART 1: At each new mouse click, the previous circle will disappear.

To add a mouse interaction, we will be using the interface MouseListener.
To implement the MouseListener, use addMouseListener(this); as part of the MouseCircle(), which will "connect" our program to the mouse.
Then implement the method public void mouseClicked(MouseEvent e) from the MouseListener interface.

You will now be able to click the mouse at various locations in the JPanel to position the red circle, that you drew, at that new location.
NOTE: click slowly when using the window!
The repaint() command can get held-up in the queue waiting to be executed, which may delay the "immediate" reappearance of a circle. If this happens, just click slower.

mc1aa

mc2aa

rc1 rc2 rc3

If you prefer to start with a clear frame, instead of the red circle in the upper left corner,
choose x and y initialized values that will move the figure out of the viewing window
(such as x = -40 and y = -40).
Be sure to choose values that will move the entire figure off the viewing window.

NOTE: The MouseListener interface specifies 5 instance methods:
public void mousePressed (MouseEvent e);
(press down on one of the mouse buttons)
public void mouseReleased (MouseEvent e);
(the pressured on button is released)
public void mouseClicked (MouseEvent e);
(press mouse button and release without moving mouse)
public void mouseEntered (MouseEvent e);
(mouse entered (moved over) the component)
public void mouseExited (MouseEvent e);
(mouse exited (moved out of) the component)

In the example shown above, the panel was repainted when the user clicked and released at a location on the panel. In order for this to happen, a mouse listener must listen for mouse events on the panel, and when the listener detects a mouseClicked event, it responds by calling the repaint() method of the panel. Consequently, all possible mouse events are "listened for" in the programming.

See PART 2

divider
Return to Unit Menu |  JavaBitsNotebook.com | MathBits.com | Terms of Use  | JavaMathBits.com

Notice: These materials are free for your on-line use at this site, but are not free for the taking.
Please do not copy these materials or re-post them to the Internet, as it is copyright infringement.
If you wish hard-copies of these materials, refer to our subscription area, JavaMathBits.com.
Help us keep these resources free. Thank you.