Java Reference
In-Depth Information
addMouseMotionListener(handler); // Listen for motion events
}
We call the
addMouseListener()
and
addMotionListener()
methods and pass the same listener
object because our listener class deals with both. Both these methods are inherited from the
Component
class that also defines an
addMouseWheelListener()
method for when you want to
handle mouse wheel events.
Let's go for the detail of the
MouseHandler
class now, starting with the
mousePressed()
method.
Handling Mouse Button Press Events
The first thing we will need to do is find out which button is pressed. It is generally a good idea to make
mouse button operations specific to a particular button. That way you avoid potential confusion when
you extend the code to support more functionality. This is very easy to do. The
getButton()
method
for the
MouseEvent
object that is passed to a handler method returns a value of type
int
that
indicates which of the three supported buttons changed state. It can return one of four constant values
that are defined in the
MouseEvent
class,
BUTTON1
,
BUTTON2
,
BUTTON3
, or
NOBUTTON
, the last
constant being the return value when no button has changed state in the current mouse event. On a two-
button mouse or a wheel mouse, button 1 for a right-handed user is the left button and button 2 is the
right button. Of course, these are reversed if you have a left-handed mouse setup. Button 3 is the middle
button when there is one. We can detect when button1 is pressed by using the following code in the
mousePressed()
method:
public void mousePressed(MouseEvent e) {
if(e.getButton() == MouseEvent.BUTTON1)
// Code to handle button 1 press...
}
A
MouseEvent
object records the current cursor position, and you can get a
Point
reference to it by
calling the
getPoint()
method. For example:
public void mousePressed(MouseEvent e) {
start = e.getPoint(); // Save the cursor position in start
if(e.getButton() == MouseEvent.BUTTON1) {
// Rest of the code to handle button 1 press...
}
}
This saves the current cursor position in the
start
field of our
MouseHandler
object. We save it before the
if
statement as we are likely to want the current cursor position available whichever button was pressed.
As well as saving the cursor position, our implementation of
mousePressed()
must set things up to
enable the
mouseDragged()
method to create an element and display it. One thing the
mouseDragged()
method needs to know is whether button 1 is down or not. The
getButton()
method won't do this in this case since it records which button changed state in the event, not which
button is down, and the button state won't change as a consequence of a mouse dragged event. We can
store the state of button one when the
mousePressed()
method is called, though. Then it will be
available to the
mouseDragged()
method. First, we need to add a suitable field to the
MouseHandler
class: