Java Reference
In-Depth Information
Adding the mouse
6
In this chapter we learn how the mouse is integrated into an application. We shall
see how the mouse motion and the use of buttons can be monitored and used by
an application.
In this chapter we describe how to use the mouse 1 in a Swing component. In
previous chapters we used the mouse indirectly as a means of pressing buttons.
As buttons can be pressed in other ways (by a finger on a touch screen), these
applications reacted to buttons but they did not react to the mouse itself.
In order to directly integrate the mouse into an application we have to add a
mouse listener to some component. The listener then keeps an eye on the mouse
and starts user-defined actions if certain events occur. Such events can be clicking
a mouse button, the mouse leaving or entering the component, a change of the
!
mouse position while inside the component, etc. Note that the listener is assigned
to a component not to the mouse itself. It tracks the mouse only while it is inside
the component.
Often one is interested in the mouse buttons or in the mouse motion but not
both. Therefore there are two listeners defined by the interfaces MouseListener
and MouseMotionListener in the AWT library java.awt.event . The first is for
handling the mouse buttons while the latter monitors the motion. To add a mouse
listener to a Swing component comp use
comp.addMouseListener(MouseListener mouseListener);
comp.addMouseMotionListener(MouseMotionListener motionListener);
In Chapters 3 and 4 we introduced the ActionListener and the corresponding
ActionEvent . The implementation of an ActionListener requires the imple-
mentation of only a single method, actionPerformed . Mouse listeners have more
methods which correspond to different mouse actions. There is also a special
event, the MouseEvent . This is discussed in the following sections.
1
We use the term 'mouse' also to denote the reference point (hot spot) of the mouse pointer
icon.
Search WWH ::




Custom Search