How to Write a Mouse Listener

 < Day Day Up > 

Mouse events tell you when the user uses the mouse (or similar input device) to interact with a component. Mouse events occur when the cursor enters or exits a component's onscreen area and when the user presses or releases one of the mouse buttons .

Tracking the cursor's motion involves significantly more system overhead than tracking other mouse events, so mouse-motion events are separated into a separate listener type. For details, see How to Write a Mouse-Motion Listener (page 695).

To track mouse wheel events, you can register a mouse wheel listener. See How to Write a Mouse Wheel Listener (page 699) for more information.

If your program needs to detect both mouse events and mouse-motion events, you can use Swing's convenient MouseInputAdapter [22] class, which implements both MouseListener [23] and MouseMotionListener . [24] It does not implement the MouseWheelListener [25] interface. [26]

[22] MouseInputAdapter API documentation: http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/event/MouseInputAdapter.html.

[23] MouseListener API documentation: http://java.sun.com/j2se/1.4.2/docs/api/java/awt/event/MouseListener.html.

[24] MouseMotionListener API documentation: http://java.sun.com/j2se/1.4.2/docs/api/java/awt/event/MouseMotionListener.html.

[25] MouseWheelListener API documentation: http://java.sun.com/j2se/1.4.2/docs/api/java/awt/event/MouseWheelListener.html.

[26] MouseInputAdapter doesn't directly implement MouseListener and MouseMotionListener . Instead, it implements MouseInputListener , a convenience interface that implements MouseListener and MouseMotionListener .

Figure 10 shows a mouse listener. At the top of the window is a blank area (implemented by a class named BlankArea ). The mouse listener listens for events both on the BlankArea and on its container, an instance of MouseEventDemo . Each time a mouse event occurs, a descriptive message is displayed under the blank area. By moving the cursor on top of the blank area and occasionally pressing mouse buttons, you can fire mouse events.

Figure 10. The MouseEventDemo application.

graphics/10fig10.gif

Try This:

  1. graphics/cd_icon.gif

    Run MouseEventDemo using Java Web Start or compile and run the example yourself. [27]

    [27] To run MouseEventDemo using Java Web Start, click the MouseEventDemo link on the RunExamples/events.html page on the CD. You can find the source files here: JavaTutorial/uiswing/events/example-1dot4/index.html#MouseEventDemo .

  2. Move the cursor into the yellow rectangle at the top of the window. You'll see one or more mouse-entered events.

  3. Press and hold the mouse button. You'll see a mouse-pressed event. You might see some extra mouse events, such as mouse-exited and then mouse-entered.

  4. Release the mouse button. You'll see a mouse-released event. If you didn't move the mouse, a mouse-clicked event will follow.

  5. Press and hold the mouse button, and then drag the mouse so that the cursor ends up outside the window. Release the mouse button. You'll see a mouse-pressed event, followed by a mouse-exited event, followed by a mouse-released event. You are not notified of the cursor's motion. To get mouse-motion events, you need to implement a mouse-motion listener.

You can find the demo's code in MouseEventDemo.java and BlankArea.java . Here's the demo's mouse event-handling code:

 public class MouseEventDemo ... implements MouseListener {  //where initialization occurs:  //Register for mouse events on blankArea and the panel.         blankArea.addMouseListener(this);         addMouseListener(this);     ...     public void mousePressed(MouseEvent e) {        saySomething("Mouse pressed; # of clicks: "                     + e.getClickCount(), e);     }     public void mouseReleased(MouseEvent e) {        saySomething("Mouse released; # of clicks: "                     + e.getClickCount(), e);     }     public void mouseEntered(MouseEvent e) {        saySomething("Mouse entered", e);     }     public void mouseExited(MouseEvent e) {        saySomething("Mouse exited", e);     }     public void mouseClicked(MouseEvent e) {        saySomething("Mouse clicked (# of clicks: "                     + e.getClickCount() + ")", e);     }     void saySomething(String eventDescription, MouseEvent e) {         textArea.append(eventDescription + " detected on "                         + e.getComponent().getClass().getName()                         + "." + newline);     } } 

The Mouse Listener API

Table 24 lists the methods in the MouseListener interface and Table 25 describes the methods in the MouseEvent class. Table 26 covers the methods in MouseEvent 's superclass, InputEvent . Also refer to the API documentation for MouseListener , MouseEvent , and InputEvent at:

http://java.sun.com/j2se/1.4.2/docs/api/java/awt/event/MouseListener.html

http://java.sun.com/j2se/1.4.2/docs/api/java/awt/event/MouseEvent.html

http://java.sun.com/j2se/1.4.2/docs/api/java/awt/event/InputEvent.html

Table 24. The MouseListener Interface (The corresponding adapter class is MouseAdapter . [a] )

Method

Purpose

mouseClicked(MouseEvent)

Called just after the user clicks the listened-to component.

mouseEntered(MouseEvent)

Called just after the cursor enters the bounds of the listened-to component.

mouseExited(MouseEvent)

Called just after the cursor exits the bounds of the listened-to component.

mousePressed(MouseEvent)

Called just after the user presses a mouse button while the cursor is over the listened-to component.

mouseReleased(MouseEvent)

Called just after the user releases a mouse button after a mouse press over the listened-to component.

[a] MouseAdapter API documentation: http://java.sun.com/j2se/1.4.2/docs/api/java/awt/event/MouseAdapter.html. You can also use the Swing adapter class, MouseInputAdapter , which has all the methods available from MouseListener and MouseMotionListener .

Table 25. The MouseEvent Class

Method

Purpose

int getClickCount()

Return the number of quick, consecutive clicks the user has made (including this event); for example, return 2 for a double click.

 int getX() int getY() Point getPoint() 

Return the ( x,y ) position at which the event occurred, relative to the component that fired the event.

int getButton()

Return which mouse button, if any, has changed state. One of the following constants is returned: NOBUTTON , BUTTON1 , BUTTON2 , or BUTTON3 . Introduced in release 1.4.

boolean isPopupTrigger()

Return true if the mouse event should cause a popup menu to appear. Because popup triggers are platform-dependent, if your program uses popup menus , call isPopupTrigger for all mouse-pressed and mouse-released events fired by components over which the popup can appear. See Bringing up a Popup Menu (page 284) for more information about popup menus.

String getMouseModifiersText(int)

Return a String describing the modifier keys and mouse buttons that were active during the event, such as "Shift," or "Ctrl+Shift." These strings can be localized using the awt.properties file. Introduced in release 1.4.

Table 26. The InputEvent Class [a]

Method

Purpose

 int getID() (  in  java.awt.AWTEvent) 

Return the event type.

 Component getComponent() (  in  ComponentEvent) 

Return the component that fired the event. You can use this method instead of the getSource method.

int getWhen()

Return the timestamp of when this event occurred. The higher the timestamp, the more recently the event occurred.

 boolean isAltDown() boolean isControlDown() boolean isMetaDown() boolean isShiftDown() 

Return the state of individual modifier keys at the time the event was fired.

int getModifiers()

Return the state of all modifier keys and mouse buttons when the event was fired. You can use this method to determine which mouse button was pressed (or newly released) when a mouse event was fired. The InputEvent class defines these constants for use with the getModifiers method: ALT_MASK , BUTTON1_MASK , BUTTON2_MASK , BUTTON3_MASK , CTRL_MASK , META_MASK , and SHIFT_MASK . For example, the following expression is true if the right button was pressed:

 (mouseEvent.getModifiers() & InputEvent.BUTTON3_MASK)                            == InputEvent.BUTTON3_MASK 

int getModifiersEx()

Return the extended modifier mask for this event. Extended modifiers represent the state of all modal keys, such as Alt, Control, Meta, and the mouse buttons just after the event occurred. You can check the status of the modifiers using one of the following predefined bitmasks : SHIFT_DOWN_MASK , CTRL_DOWN_MASK , META_DOWN_MASK , ALT_DOWN_MASK , BUTTON1_DOWN_MASK , BUTTON2_DOWN_MASK , BUTTON3_DOWN_MASK , or ALT_GRAPH_DOWN_MASK . For example, to check that button 1 is down, but that buttons 2 and 3 are up, you would use the following code snippet:

 if (event.getModifiersEx() & (BUTTON1_DOWN_MASK             BUTTON2_DOWN_MASK  BUTTON3_DOWN_MASK)         == BUTTON1_DOWN_MASK) {   ... } 

Introduced in release 1.4.

int getModifiersExText(int)

Return a string describing the extended modifier keys and mouse buttons, such as "Shift," "Button1," or "Ctrl+Shift." These strings can be localized by changing the awt.properties file. Introduced in release 1.4.

[a] InputEvent passes many useful methods to its subclass MouseEvent . MouseEvent also inherits a couple of handy methods from the ComponentEvent class and a couple of handy methods from the ComponentEvent and AWTEvent classes.

Examples That Use Mouse Listeners

The following examples use mouse listeners.

Example

Where Described

Notes

MouseEventDemo

This section

Reports all mouse events that occur within a blank panel to demonstrate the circumstances under which mouse events are fired.

CoordinatesDemo

Performing Custom Painting (page 129)

An applet that draws a small circle where the user clicks the mouse. The applet also reports the x, y location of the mouse click.

SelectionDemo

Performing Custom Painting (page 129)

An applet that lets the user drag a rectangle to select a portion of an image. Uses a subclass of MouseInputAdapter to listen to both mouse events and mouse-motion events.

GlassPaneDemo

How to Use Root Panes (page 316)

Uses a subclass of MouseInputAdapter to listen to mouse events and mouse-motion events on the root pane's glass pane. Redispatches the events to underlying components.

TableSorter

How to Use Tables (page 388)

Listens to mouse events on a table header. Sorts data in the selected column.

PopupMenuDemo

How to Use Menus (page 277)

Displays a popup menu in response to mouse clicks.

TrackFocusDemo

How to Use the Focus Subsystem (page 583)

The custom component, Picture , implements a mouse listener that requests the focus when a user clicks on the component.

 < Day Day Up > 


JFC Swing Tutorial, The. A Guide to Constructing GUIs
The JFC Swing Tutorial: A Guide to Constructing GUIs (2nd Edition)
ISBN: 0201914670
EAN: 2147483647
Year: 2004
Pages: 171

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net