All mouse events java

How to Write a Mouse Listener

Mouse events notify 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. That is why mouse-motion events are separated into Mouse Motion listener type (see How to Write a Mouse Motion Listener).

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

If an application requires the detection of both mouse events and mouse-motion events, use the MouseInputAdapter class. This class implements the MouseInputListener , a convenient interface that implements the MouseListener and MouseMotionListener interfaces. However, the MouseInputListener interface does not implement the MouseWheelListener interface.

Alternatively, use the corresponding AWT MouseAdapter class, which implements the MouseListener , MouseMotionListener , and MouseWheelListener interfaces.

The following example 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.

MouseEventDemo screen shot

Try this:

  1. Click the Launch button to run MouseEventDemo using Java™ Web Start (download JDK 7 or later). Alternatively, to compile and run the example yourself, consult the example index.
  2. Move the cursor into the yellow rectangle at the top of the window.
    You will see one or more mouse-entered events.
  3. Press and hold the left mouse button without moving the mouse.
    You will 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 will see a mouse-released event. If you did not move the mouse, a mouse-clicked event will follow.
  5. Press and hold the mouse button again, and then drag the mouse so that the cursor ends up outside the window. Release the mouse button.
    You will 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.
Читайте также:  Java using new keyword

You can find the demo’s code in MouseEventDemo.java and BlankArea.java . Here is 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

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.

The MouseAdapter class (the AWT adapter class) is abstract. All its methods have an empty body. So a developer can define methods for events specific to the application. You can also use the MouseInputAdapter class, which has all the methods available from MouseListener and MouseMotionListener .

Method Purpose
int getClickCount() Returns the number of quick, consecutive clicks the user has made (including this event). For example, returns 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 getXOnScreen()
int getYOnScreen()
int getLocationOnScreen()
Return the absolute (x,y) position of the event. These coordinates are relative to the virtual coordinate system for the multi-screen environment. Otherwise, these coordinates are relative to the coordinate system associated with the Component’s Graphics Configuration.
int getButton() Returns which mouse button, if any, has a changed state. One of the following constants is returned: NOBUTTON , BUTTON1 , BUTTON2 , or BUTTON3 .
boolean isPopupTrigger() Returns true if the mouse event should cause a popup menu to appear. Because popup triggers are platform dependent, if your program uses popup menus, you should 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 for more information about popup menus.
String getMouseModifiersText(int) Returns 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.
Читайте также:  Css анимация изменение цвета фона

The MouseEvent class inherits many useful methods from InputEvent and a couple handy methods from the ComponentEvent and AWTEvent classes.

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

if (event.getModifiersEx() & (BUTTON1_DOWN_MASK | BUTTON2_DOWN_MASK | BUTTON3_DOWN_MASK) == BUTTON1_DOWN_MASK)

The MouseInfo class provides methods to obtain information about the mouse pointer location at any time while an application runs.

Method Purpose
getPointerInfo() Returns a PointerInfo instance that represents the current location of the mouse pointer.
getNumberOfButtons() Returns the number of buttons on the mouse or -1 , if a system does not support a mouse.

Examples That Use Mouse Listeners

The following table lists the examples that 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.
GlassPaneDemo How to Use Root Panes Uses a subclass of MouseInputAdapter to listen to mouse events and mouse-motion events on the root pane’s glass pane. Re-dispatches the events to underlying components.
TableSortDemo How to Use Tables Listens to mouse events on a table header. Sorts data in the selected column.
PopupMenuDemo How to Use Menus Displays a popup menu in response to mouse clicks.
TrackFocusDemo How to Use the Focus Subsystem The custom component, Picture , implements a mouse listener that requests the focus when a user clicks on the component.

Previous page: How to Write a List Selection Listener
Next page: How to Write a Mouse-Motion Listener

Источник

All mouse events java

A MouseEvent object is passed to every MouseListener or MouseAdapter object which is registered to receive the «interesting» mouse events using the component’s addMouseListener method. ( MouseAdapter objects implement the MouseListener interface.) Each such listener object gets a MouseEvent containing the mouse event.

A MouseEvent object is also passed to every MouseMotionListener or MouseMotionAdapter object which is registered to receive mouse motion events using the component’s addMouseMotionListener method. ( MouseMotionAdapter objects implement the MouseMotionListener interface.) Each such listener object gets a MouseEvent containing the mouse motion event.

Читайте также:  Python приведение к целому типу

When a mouse button is clicked, events are generated and sent to the registered MouseListener s. The state of modal keys can be retrieved using InputEvent.getModifiers() and InputEvent.getModifiersEx() . The button mask returned by InputEvent.getModifiers() reflects only the button that changed state, not the current state of all buttons. (Note: Due to overlap in the values of ALT_MASK/BUTTON2_MASK and META_MASK/BUTTON3_MASK, this is not always true for mouse events involving modifier keys). To get the state of all buttons and modifier keys, use InputEvent.getModifiersEx() . The button which has changed state is returned by getButton()

For example, if the first mouse button is pressed, events are sent in the following order:

 id modifiers button MOUSE_PRESSED: BUTTON1_MASK BUTTON1 MOUSE_RELEASED: BUTTON1_MASK BUTTON1 MOUSE_CLICKED: BUTTON1_MASK BUTTON1 

For example, if the user presses button 1 followed by button 2, and then releases them in the same order, the following sequence of events is generated:

 id modifiers button MOUSE_PRESSED: BUTTON1_MASK BUTTON1 MOUSE_PRESSED: BUTTON2_MASK BUTTON2 MOUSE_RELEASED: BUTTON1_MASK BUTTON1 MOUSE_CLICKED: BUTTON1_MASK BUTTON1 MOUSE_RELEASED: BUTTON2_MASK BUTTON2 MOUSE_CLICKED: BUTTON2_MASK BUTTON2 

If button 2 is released first, the MOUSE_RELEASED / MOUSE_CLICKED pair for BUTTON2_MASK arrives first, followed by the pair for BUTTON1_MASK .

Some extra mouse buttons are added to extend the standard set of buttons represented by the following constants: BUTTON1 , BUTTON2 , and BUTTON3 . Extra buttons have no assigned BUTTONx constants as well as their button masks have no assigned BUTTONx_DOWN_MASK constants. Nevertheless, ordinal numbers starting from 4 may be used as button numbers (button ids). Values obtained by the getMaskForButton(button) method may be used as button masks.

  • In a multi-screen environment without a virtual device:
    The reported coordinates for mouse drag events are clipped to fit within the bounds of the GraphicsConfiguration associated with the Component .
  • In a multi-screen environment with a virtual device:
    The reported coordinates for mouse drag events are clipped to fit within the bounds of the virtual device associated with the Component .

An unspecified behavior will be caused if the id parameter of any particular MouseEvent instance is not in the range from MOUSE_FIRST to MOUSE_LAST -1 ( MOUSE_WHEEL is not acceptable).

Источник

Оцените статью