Page 715 - Introduction to Programming with Java: A Problem Solving Approach
P. 715

                16.18 Mouse Listeners and Images (Optional) 681
   MouseListener Interface Event Handlers
   public void mouseClicked(MouseEvent event)
Called when the user presses and releases the mouse button while the mouse cursor is stationary on a MouseListener-registered component.
public void mouseEntered(MouseEvent event)
Called when the mouse cursor enters the bounds of a MouseListener-registered component. public void mouseExited(MouseEvent event)
Called when the mouse cursor exits from the bounds of a MouseListener-registered component.
public void mousePressed(MouseEvent event)
Called when the user presses the mouse button while the mouse cursor is on a MouseListener- registered component.
public void mouseReleased(MouseEvent event)
Called when the user releases the mouse button, but only if the prior mouse press was on a MouseListener-registered component.
   MouseMotionListenerAInptearfagceoEventPHDandFlers Enhancer
   public void mouseDragged(MouseEvent event)
Called when the user holds the mouse button down while moving the mouse cursor, but only if the initial mouse press was on a MouseMotionListener-registered component.
public void mouseMoved(MouseEvent event)
Called when the user moves the mouse while the mouse cursor is on a MouseMotionListener- registered component.
  Figure 16.15 API headings and descriptions for the methods in the MouseListener and MouseMotionListener interfaces
defined by the two interfaces. Read through the API headings and descriptions to get an idea of what’s pos- sible in terms of mouse event handling.
As a programmer, you don’t have to worry about calling the mouse event handler methods. They’re called automatically when their associated mouse events occur. For example, if the user presses the mouse button while the mouse cursor is on a MouseListener-registered component, the JVM automatically calls the mousePressed event handler.
In the upcoming program, the goal is to enable a user to drag an image across a window using the mouse. To do that, you need to detect the mouse being pressed and moved (i.e., dragged) while the mouse cursor is on the image. And to do that, you need to register a mouse listener. But you can register a mouse listener only with a component, not with an image. So what’s the solution? You’re already familiar with some components—JLabel, JTextField, and JButton components. Those classes are component















































































   713   714   715   716   717