Java Reference
In-Depth Information
A listener is added to each component that will generate the events to handle.
n
The methods are added, each with an
EventObject
class as the only argument to
the method.
n
Methods of that
EventObject
class, such as
getSource()
, are used to learn which
component generated the event and what kind of event it was.
n
When you know these steps, you can work with each of the different listener interfaces
and event classes. You also can learn about new listeners as they are added to Swing with
new components.
Q Can a program's event-handling behavior be put into its own class instead of
including it with the code that creates the interface?
A
It can, and many programmers will tell you that this is a good way to design your
programs. Separating interface design from your event-handling code enables the
two to be developed separately. This makes it easier to maintain the project; related
behavior is grouped and isolated from unrelated behavior.
Q Is there a way of differentiating between the buttons on a
mouseClicked()
event?
A
You can, using a feature of mouse events that wasn't covered today because right
and middle mouse buttons are platform-specific features that aren't available on all
systems where Java programs run.
All mouse events send a
MouseEvent
object to their event-handling methods. Call
the
getModifiers()
method of the object to receive an integer value that indicates
which mouse button generated the event.
Check the value against three class variables. It equals
MouseEvent.BUTTON1_MASK
if the left button was clicked,
MouseEvent.BUTTON2_MASK
if the middle button was
clicked, and
MouseEvent.BUTTON3_MASK
if the right button was clicked. See
MouseTest.java
and
MouseTest.class
on the Day 12 page of the topic's website
at
http://www.java21days.com
for an example that implements this technique.
For more information, see the Java class library documentation for the
MouseEvent
class: Visit the web page
http://java.sun.com/javase/6/docs/api
and click the
java.awt.event
hyperlink to view the classes in that package.