Mouse Event Handling

This section presents the MouseListener and MouseMotionListener event-listener interfaces for handling mouse events. Mouse events can be trapped for any GUI component that derives from java.awt.Component. The methods of interfaces MouseListener and MouseMotionListener are summarized in Figure 11.27. Package javax.swing.event contains interface MouseInputListener, which extends interfaces MouseListener and MouseMotionListener to create a single interface containing all the MouseListener and MouseMotionListener methods. The MouseListener and MouseMotionListener methods are called when the mouse interacts with a Component if appropriate event-listener objects are registered for that Component.

Figure 11.27. MouseListener and MouseMotionListener interface methods.

(This item is displayed on page 552 in the print version)

MouseListener and MouseMotionListener interface methods

Methods of interface MouseListener

public void mousePressed( MouseEvent event )

Called when a mouse button is pressed while the mouse cursor is on a component.

public void mouseClicked( MouseEvent event )

Called when a mouse button is pressed and released while the mouse cursor remains stationary on a component. This event is always preceded by a call to mousePressed.

public void mouseReleased( MouseEvent event )

Called when a mouse button is released after being pressed. This event is always preceded by a call to mousePressed and one or more calls to mouseDragged.

public void mouseEntered( MouseEvent event )

Called when the mouse cursor enters the bounds of a component.

public void mouseExited( MouseEvent event )

Called when the mouse cursor leaves the bounds of a component.

Methods of interface MouseMotionListener

public void mouseDragged( MouseEvent event )

Called when the mouse button is pressed while the mouse cursor is on a component and the mouse is moved while the mouse button remains pressed. This event is always preceded by a call to mousePressed. All drag events are sent to the component on which the user began to drag the mouse.

public void mouseMoved( MouseEvent event )

Called when the mouse is moved when the mouse cursor is on a component. All move events are sent to the component over which the mouse is currently positioned.

Each of the mouse event-handling methods takes a MouseEvent object as its argument. A MouseEvent object contains information about the mouse event that occurred, including the x- and y-coordinates of the location where the event occurred. These coordinates are measured from the upper-left corner of the GUI component on which the event occurred. The x-coordinates start at 0 and increase from left to right. The y-coordinates start at 0 and increase from top to bottom. In addition, the methods and constants of class InputEvent (MouseEvent's superclass) enable an application to determine which mouse button the user clicked.

Look-and-Feel Observation 11.12

Method calls to mouseDragged and mouseReleased are sent to the MouseMotionListener for the Component on which a mouse drag operation started. Similarly, the mouseReleased method call at the end of a drag operation is sent to the MouseListener for the Component on which the drag operation started.

Java also provides interface MouseWheelListener to enable applications to respond to the rotation of a mouse wheel. This interface declares method mouseWheelMoved, which receives a MouseWheelEvent as its argument. Class MouseWheelEvent (a subclass of MouseEvent) contains methods that enable the event handler to obtain information about the amount of wheel rotation.

Tracking Mouse Events on a JPanel

The MouseTracker application (Fig. 11.28 and Fig. 11.29) demonstrates the MouseListener and MouseMotionListener interface methods. The application class implements both interfaces so it can listen for its own mouse events. Note that all seven methods from these two interfaces must be declared by the programmer when a class implements both interfaces. Each mouse event in this example displays a string in the JLabel called statusBar at the bottom of the window.

Figure 11.28. Mouse event handling.

(This item is displayed on pages 553 - 554 in the print version)

 1 // Fig. 11.28: MouseTrackerFrame.java
 2 // Demonstrating mouse events.
 3 import java.awt.Color;
 4 import java.awt.BorderLayout;
 5 import java.awt.event.MouseListener;
 6 import java.awt.event.MouseMotionListener;
 7 import java.awt.event.MouseEvent;
 8 import javax.swing.JFrame;
 9 import javax.swing.JLabel;
10 import javax.swing.JPanel;
11
12 public class MouseTrackerFrame extends JFrame
13 {
14 private JPanel mousePanel; // panel in which mouse events will occur
15 private JLabel statusBar; // label that displays event information
16
17 // MouseTrackerFrame constructor sets up GUI and
18 // registers mouse event handlers
19 public MouseTrackerFrame()
20 {
21 super( "Demonstrating Mouse Events" );
22
23 mousePanel = new JPanel(); // create panel 
24 mousePanel.setBackground( Color.WHITE ); // set background color
25 add( mousePanel, BorderLayout.CENTER ); // add panel to JFrame 
26
27 statusBar = new JLabel( "Mouse outside JPanel" ); 
28 add( statusBar, BorderLayout.SOUTH ); // add label to JFrame
29
30 // create and register listener for mouse and mouse motion events
31 MouseHandler handler = new MouseHandler(); 
32 mousePanel.addMouseListener( handler ); 
33 mousePanel.addMouseMotionListener( handler ); 
34 } // end MouseTrackerFrame constructor
35
36 private class MouseHandler implements MouseListener,
37  MouseMotionListener 
38 {
39 // MouseListener event handlers
40 // handle event when mouse released immediately after press
41 public void mouseClicked( MouseEvent event )
42 {
43 statusBar.setText( String.format( "Clicked at [%d, %d]",
44 event.getX(), event.getY() ) );
45 } // end method mouseClicked
46
47 // handle event when mouse pressed
48 public void mousePressed( MouseEvent event )
49 {
50 statusBar.setText( String.format( "Pressed at [%d, %d]",
51 event.getX(), event.getY() ) );
52 } // end method mousePressed
53
54 // handle event when mouse released after dragging
55 public void mouseReleased( MouseEvent event )
56 {
57 statusBar.setText( String.format( "Released at [%d, %d]",
58 event.getX(), event.getY() ) );
59 } // end method mouseReleased
60
61 // handle event when mouse enters area
62 public void mouseEntered( MouseEvent event )
63 {
64 statusBar.setText( String.format( "Mouse entered at [%d, %d]",
65 event.getX(), event.getY() ) );
66 mousePanel.setBackground( Color.GREEN );
67 } // end method mouseEntered
68
69 // handle event when mouse exits area
70 public void mouseExited( MouseEvent event )
71 {
72 statusBar.setText( "Mouse outside JPanel" );
73 mousePanel.setBackground( Color.WHITE );
74 } // end method mouseExited
75
76 // MouseMotionListener event handlers
77 // handle event when user drags mouse with button pressed
78 public void mouseDragged( MouseEvent event )
79 {
80 statusBar.setText( String.format( "Dragged at [%d, %d]",
81 event.getX(), event.getY() ) );
82 } // end method mouseDragged
83
84 // handle event when user moves mouse
85 public void mouseMoved( MouseEvent event )
86 {
87 statusBar.setText( String.format( "Moved at [%d, %d]",
88 event.getX(), event.getY() ) );
89 } // end method mouseMoved
90 } // end inner class MouseHandler
91 } // end class MouseTrackerFrame

Figure 11.29. Test class for MouseTrackerFrame.

(This item is displayed on page 555 in the print version)

 1 // Fig. 11.29: MouseTrackerFrame.java
 2 // Testing MouseTrackerFrame.
 3 import javax.swing.JFrame;
 4
 5 public class MouseTracker
 6 {
 7 public static void main( String args[] )
 8 {
 9 MouseTrackerFrame mouseTrackerFrame = new MouseTrackerFrame();
10 mouseTrackerFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
11 mouseTrackerFrame.setSize( 300, 100 ); // set frame size
12 mouseTrackerFrame.setVisible( true ); // display frame
13 } // end main
14 } // end class MouseTracker
 

Line 23 in Fig. 11.28 creates JPanel mousePanel. This JPanel's mouse events will be tracked by the application. Line 24 sets mousePanel's background color to white. When the user moves the mouse into the mousePanel, the application will change mousePanel's background color to green. When the user moves the mouse out of the mousePanel, the application will change the background color back to white. Line 25 attaches mousePanel to the JFrame. As you learned in Section 11.4, you typically must specify the layout of the GUI components in a JFrame. In that section, we introduced the layout manager FlowLayout. Here we use the default layout of a JFrame's content paneBorderLayout. This layout manager arranges components into five regions: NORTH, SOUTH, EAST, WEST and CENTER. NORTH corresponds to the top of the container. This example uses the CENTER and SOUTH regions. Line 25 uses a two-argument version of method add to place mousePanel in the CENTER region. The BorderLayout automatically sizes the component in the CENTER to use all the space in the JFrame that is not occupied by components in the other regions. Section 11.17.2 discusses BorderLayout in more detail.

Lines 2728 in the constructor declare JLabel statusBar and attach it to the JFrame's SOUTH region. This JLabel occupies the width of the JFrame. The region's height is determined by the JLabel.

Line 31 creates an instance of inner class MouseHandler (lines 3690) called handler that responds to mouse events. Lines 3233 register handler as the listener for mousePanel's mouse events. Methods addMouseListener and addMouseMotionListener are inherited indirectly from class Component and can be used to register MouseListeners and MouseMotionListeners, respectively. A MouseHandler object is both a MouseListener and a MouseMotionListener because the class implements both interfaces. [Note: In this example, we chose to implement both interfaces to demonstrate a class that implements more than one interface. However, we also could have implemented interface MouseInputListener here.]

When the mouse enters and exits mousePanel's area, methods mouseEntered (lines 6267) and mouseExited (lines 7074) are called, respectively. Method mouseEntered displays a message in the statusBar indicating that the mouse entered the JPanel and changes the background color to green. Method mouseExited displays a message in the statusBar indicating that the mouse is outside the JPanel (see the first sample output window) and changes the background color to white.

When any of the other five events occurs, it displays a message in the statusBar that includes a string containing the event and the coordinates at which it occurred. MouseEvent methods getX and getY return the x- and y-coordinates, respectively, of the mouse at the time the event occurred.

Introduction to Computers, the Internet and the World Wide Web

Introduction to Java Applications

Introduction to Classes and Objects

Control Statements: Part I

Control Statements: Part 2

Methods: A Deeper Look

Arrays

Classes and Objects: A Deeper Look

Object-Oriented Programming: Inheritance

Object-Oriented Programming: Polymorphism

GUI Components: Part 1

Graphics and Java 2D™

Exception Handling

Files and Streams

Recursion

Searching and Sorting

Data Structures

Generics

Collections

Introduction to Java Applets

Multimedia: Applets and Applications

GUI Components: Part 2

Multithreading

Networking

Accessing Databases with JDBC

Servlets

JavaServer Pages (JSP)

Formatted Output

Strings, Characters and Regular Expressions

Appendix A. Operator Precedence Chart

Appendix B. ASCII Character Set

Appendix C. Keywords and Reserved Words

Appendix D. Primitive Types

Appendix E. (On CD) Number Systems

Appendix F. (On CD) Unicode®

Appendix G. Using the Java API Documentation

Appendix H. (On CD) Creating Documentation with javadoc

Appendix I. (On CD) Bit Manipulation

Appendix J. (On CD) ATM Case Study Code

Appendix K. (On CD) Labeled break and continue Statements

Appendix L. (On CD) UML 2: Additional Diagram Types

Appendix M. (On CD) Design Patterns

Appendix N. Using the Debugger

Inside Back Cover



Java(c) How to Program
Java How to Program (6th Edition) (How to Program (Deitel))
ISBN: 0131483986
EAN: 2147483647
Year: 2003
Pages: 615

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