Java Reference
In-Depth Information
9.10 Mouse Events
If you write programs that show drawings, and you want users to manipulate the
drawings with a mouse, then you need to process mouse events. Mouse events are
more complex than button clicks or timer ticks.
You use a mouse listener to capture mouse events.
A mouse listener must implement the
MouseListener
interface, which contains
the following five methods:
public interface MouseListener
{
void mousePressed(MouseEvent event);
// Called when a mouse button has been pressed on a component
void mouseReleased(MouseEvent event);
// Called when a mouse button has been released on a component
void mouseClicked(MouseEvent event);
// Called when the mouse has been clicked on a component
void mouseEntered(MouseEvent event);
// Called when the mouse enters a component
void mouseExited(MouseEvent event);
// Called when the mouse exits a component
}
421
422
The
mousePressed
and
mouseReleased
methods are called whenever a mouse
button is pressed or released. If a button is pressed and released in quick succession,
and the mouse has not moved, then the
mouseClicked
method is called as well.
The
mouseEntered
and
mouseExited
methods can be used to paint a
user-interface component in a special way whenever the mouse is pointing inside it.
The most commonly used method is
mousePressed
. Users generally expect that
their actions are processed as soon as the mouse button is pressed.
You add a mouse listener to a component by calling the
addMouseListener
method:
public class MyMouseListener implements MouseListener
{