Java Notes

Mouse Events - Overview

The mouse listeners allow you to receive events to process:

Normally handled for you. The mouse is handled automatically by most components, so you never have to know about it. For example, if someone clicks on a button (JButton), the JButton translates that click into an ActionEvent, which is a higher level event that can be caused by a number of things. You don't need to know (and shouldn't care) whether the ActionEvent was from a mouse click on the button, or from a keyboard shortcut, or hitting enter while that button had focus, or ....

Sometimes used with graphics. If you are are drawing your own graphics (eg, on a JComponent or JPanel) and need to know where the user clicks, then you need to know about mouse events. You can easily add a mouse listener to a JComponent or JPanel.

Important Classes and Interfaces

These classes and interfaces are defined in java.awt.event. The first three are the most commonly used.

MouseEventA MouseEvent object is passed to all mouse listeners. The most useful information in a MouseEvent is the x and y coordinates of the mouse cursor.
MouseListenerInterface for mouse presses, releases, clicks, enters, and exits.
MouseMotionListenerInterface for mouse moves and drags.
MouseInputListenerInterface combination of MouseListener and MouseMotionListener.
Adapter classes - You only have to override the methods you need.
MouseAdapterClass useful for writing anonymous listener for mouse button presses, entering, ...
MouseMotionAdapterClass useful for writing anonymous listener for mouse movement.
Handling the mouse wheel.
MouseWheelEvent Object passed to mouseWheelMoved. Subclass of MouseEvent.
MouseWheelListenerInterface to handle wheel movements. Write mouseWheelMoved(MouseWheelEvent we)

Additional Mouse Notes

MouseListener - Handles presses, releases, clicks, enters, and exits.
MouseMotionListener - Handles moves and drags.
Mouse Listeners - How and where to write mouse listeners.
Mouse Buttons, Modifier Keys - How to check which mouse buttons are pressed.
Example - MouseTest - Example shows mouse coordinates.
Example - DragDemo - Example shows mouse dragging.