- How to Write a Mouse-Motion Listener
- The Mouse-Motion Listener API
- Examples That Use Mouse-Motion Listeners
- Java событие нажатие мыши
- Interface MouseListener
- Method Summary
- Method Detail
- mouseClicked
- mousePressed
- mouseReleased
- mouseEntered
- mouseExited
- Обработка событий от мыши Java
- Java событие нажатие мыши
- Interface MouseListener
- Method Summary
- Method Detail
- mouseClicked
- mousePressed
- mouseReleased
How to Write a Mouse-Motion Listener
Mouse-motion events notify when the user uses the mouse (or a similar input device) to move the onscreen cursor. For information on listening for other kinds of mouse events, such as clicks, see How to Write a Mouse Listener. For information on listening for mouse-wheel events, see How to Write a Mouse Wheel Listener.
If an application requires the detection of both mouse events and mouse-motion events, use the MouseInputAdapter class, which implements the MouseInputListener a convenient interface that implements both the MouseListener and MouseMotionListener interfaces.
Alternatively, use the corresponding MouseAdapter AWT class, which implements the MouseMotionListener interface, to create a MouseMotionEvent and override the methods for the specific events.
The following demo code contains a mouse-motion listener. This demo is exactly the same as the demo described in the How to Write a Mouse Listener section, except for substituting the MouseMotionListener interface for the MouseListener interface. Additionally, MouseMotionEventDemo implements the mouseDragged and mouseMoved methods instead of the mouse listener methods, and displays coordinates instead of numbers of clicks.
Try this:
- Click the Launch button to run MouseMotionEventDemo using Java™ Web Start (download JDK 7 or later). Alternatively, to compile and run the example yourself, consult the example index.
- Move the cursor into the yellow rectangle at the top of the window.
You will see one or more mouse-moved events. - Press and hold the mouse button, and then move the mouse so that the cursor is outside the yellow rectangle.
You will see mouse-dragged events.
You can find the demo’s code in MouseMotionEventDemo.java and BlankArea.java . The following code snippet from MouseMotionEventDemo implements the mouse-motion event handling:
public class MouseMotionEventDemo extends JPanel implements MouseMotionListener < //. in initialization code: //Register for mouse events on blankArea and panel. blankArea.addMouseMotionListener(this); addMouseMotionListener(this); . > public void mouseMoved(MouseEvent e) < saySomething("Mouse moved", e); >public void mouseDragged(MouseEvent e) < saySomething("Mouse dragged", e); >void saySomething(String eventDescription, MouseEvent e) < textArea.append(eventDescription + " (" + e.getX() + "," + e.getY() + ")" + " detected on " + e.getComponent().getClass().getName() + newline); >>
The SelectionDemo example, draws a rectangle illustrating the user’s current dragging. To draw the rectangle, the application must implement an event handler for three kinds of mouse events: mouse presses, mouse drags, and mouse releases. To be informed of all these events, the handler must implement both the MouseListener and MouseMotionListener interfaces, and be registered as both a mouse listener and a mouse-motion listener. To avoid having to define empty methods, the handler doesn’t implement either listener interface directly. Instead, it extends MouseInputAdapter , as the following code snippet shows.
. //where initialization occurs: MyListener myListener = new MyListener(); addMouseListener(myListener); addMouseMotionListener(myListener); . private class MyListener extends MouseInputAdapter < public void mousePressed(MouseEvent e) < int x = e.getX(); int y = e.getY(); currentRect = new Rectangle(x, y, 0, 0); updateDrawableRect(getWidth(), getHeight()); repaint(); >public void mouseDragged(MouseEvent e) < updateSize(e); >public void mouseReleased(MouseEvent e) < updateSize(e); >void updateSize(MouseEvent e) < int x = e.getX(); int y = e.getY(); currentRect.setSize(x - currentRect.x, y - currentRect.y); updateDrawableRect(getWidth(), getHeight()); Rectangle totalRepaint = rectToDraw.union(previouseRectDrawn); repaint(totalRepaint.x, totalRepaint.y, totalRepaint.width, totalRepaint.height); >>
The Mouse-Motion Listener API
The corresponding adapter classes are MouseMotionAdapter and MouseAdapter .
Method | Purpose |
---|---|
mouseDragged(MouseEvent) | Called in response to the user moving the mouse while holding a mouse button down. This event is fired by the component that fired the most recent mouse-pressed event, even if the cursor is no longer over that component. |
mouseMoved(MouseEvent) | Called in response to the user moving the mouse with no mouse buttons pressed. This event is fired by the component that’s currently under the cursor. |
Each mouse-motion event method has a single parameter — and it’s not called MouseMotionEvent ! Instead, each mouse-motion event method uses a MouseEvent argument. See The MouseEvent API for information about using MouseEvent objects.
Examples That Use Mouse-Motion Listeners
The following table lists the examples that use mouse-motion listeners.
Example | Where Described | Notes |
---|---|---|
MouseMotionEventDemo | This section | Reports all mouse motion events that occur within a blank panel to demonstrate the circumstances under which mouse motion events are fired. |
LayeredPaneDemo and LayeredPaneDemo2 | How to Use Layered Panes | Moves an image of Duke around within a layered pane in response to mouse motion events. |
SelectionDemo | 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 | 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. |
ScrollDemo | How to Use Scroll Panes | The label subclass, ScrollablePicture, uses a mouse-motion listener to allow the user to scroll the picture even when the user drags the cursor outside the window. |
Java событие нажатие мыши
Interface MouseListener
- All Superinterfaces: EventListener All Known Subinterfaces: MouseInputListener All Known Implementing Classes: AWTEventMulticaster , BasicButtonListener , BasicComboPopup.InvocationMouseHandler , BasicComboPopup.ListMouseHandler , BasicDesktopIconUI.MouseInputHandler , BasicFileChooserUI.DoubleClickListener , BasicInternalFrameUI.BorderListener , BasicInternalFrameUI.GlassPaneDispatcher , BasicListUI.MouseInputHandler , BasicMenuItemUI.MouseInputHandler , BasicMenuUI.MouseInputHandler , BasicScrollBarUI.ArrowButtonListener , BasicScrollBarUI.TrackListener , BasicSliderUI.TrackListener , BasicSplitPaneDivider.MouseHandler , BasicTabbedPaneUI.MouseHandler , BasicTableHeaderUI.MouseInputHandler , BasicTableUI.MouseInputHandler , BasicTextUI.BasicCaret , BasicToolBarUI.DockingListener , BasicTreeUI.MouseHandler , BasicTreeUI.MouseInputHandler , DefaultCaret , FormView.MouseEventListener , HTMLEditorKit.LinkController , MetalFileChooserUI.SingleClickListener , MetalToolBarUI.MetalDockingListener , MouseAdapter , MouseDragGestureRecognizer , MouseInputAdapter , ToolTipManager
The listener interface for receiving «interesting» mouse events (press, release, click, enter, and exit) on a component. (To track mouse moves and mouse drags, use the MouseMotionListener .) The class that is interested in processing a mouse event either implements this interface (and all the methods it contains) or extends the abstract MouseAdapter class (overriding only the methods of interest). The listener object created from that class is then registered with a component using the component’s addMouseListener method. A mouse event is generated when the mouse is pressed, released clicked (pressed and released). A mouse event is also generated when the mouse cursor enters or leaves a component. When a mouse event occurs, the relevant method in the listener object is invoked, and the MouseEvent is passed to it.
Method Summary
Method Detail
mouseClicked
mousePressed
mouseReleased
mouseEntered
mouseExited
Report a bug or suggest an enhancement
For further API reference and developer documentation see the Java SE Documentation, which contains more detailed, developer-targeted descriptions with conceptual overviews, definitions of terms, workarounds, and working code examples.
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 1993, 2023, Oracle and/or its affiliates, 500 Oracle Parkway, Redwood Shores, CA 94065 USA.
All rights reserved. Use is subject to license terms and the documentation redistribution policy.
Обработка событий от мыши Java
Чтобы обработать события от мыши, следует реализовать интерфейсы MouseListener и MouseMotionListener. Можно было бы также реализовать интерфейс MouseWheelListener, но мы не станем здесь этого делать.
Весь процесс обработки событий от мыши демонстрируется в приведенном ниже примере аплета. В строке состояния окна этого аплета выводятся текущие координаты мыши.
Всякий раз, когда нажимается кнопка мыши, на месте курсора мыши появляется слово «Down»(Нажато). И всякий раз, когда кнопка мыши отпускается, слово «Up» (Отпущено) . А если производится щелчок кнопкой мыши, то в левом верхнем углу области отображения аплета выводится сообщение «Mouseclicked» (Произведен щелчок кнопкой мыши ).
Когда же курсор мыши наводится на окно аплета или отводится от него, то в левом верхнем углу области отображения аплета также выводится соответствующее сообщение. При перетаскивании курсора мыши выводится символ *, сопровождающий курсор мыши.
Обратите внимание на то, что в двух переменных, mouseX и mouseY, сохраняются координаты местоположения курсора мыши, когда происходят события нажатия и отпускания кнопки мыши, а также события перетаскивания. Эти координаты затем используются методом paint() для вывода соответствующего сообщения в той точке, где возникает событие.
Собственно весь код нашей программы:
Пример выполнения данного аплета приведен на рис. 1.
Рис. 1. Пример выполнения аплета, в котором обрабатываются события мыши
Рассмотрим данный пример аплета более подробно. В частности, класс MouseEvents расширяет класс Applet и реализует интерфейсы MouseListener и MouseMotionListener.
Оба эти интерфейса содержат методы, принимающие и обрабатывающие различные типы событий от мыши. Обратите внимание на то, что аплет одновременно является источником и приемником этих событий. И это вполне допустимо, поскольку класс Component, предоставляющий методы addMouseListener() и addMouseMotionListener(), служит суперклассом для класса Аррlеt. Вообще, использование одного и того же объекта в качестве источника и приемника событий характерно для аплетов.
Заказать дешевую рекламу с видимым результатом в Одноклассниках теперь стало еще проще. Вам больше не придется выделять огромный бюджет на очередную кампанию, настраивать ее и тестировать — Вы получаете все, что нужно для развития в соцсети в одном пакетном предложении по очень низкой цене. Здесь доступны и подписчики, и друзья, и классы, и прочие ресурсы — торопитесь, пока на сайте действуют скидки.
В методе init() аплет регистрирует себя в качестве приемника событий от мыши. Это делается с помощью методов addMouseListener() и addMouseMotionListener(), которые, как упоминалось ранее, являются членами класса Component. Ниже приведены общие формы этих методов:
Java событие нажатие мыши
Interface MouseListener
- All Superinterfaces: EventListener All Known Subinterfaces: MouseInputListener All Known Implementing Classes: AWTEventMulticaster, BasicButtonListener, BasicComboPopup.InvocationMouseHandler, BasicComboPopup.ListMouseHandler, BasicDesktopIconUI.MouseInputHandler, BasicFileChooserUI.DoubleClickListener, BasicInternalFrameUI.BorderListener, BasicInternalFrameUI.GlassPaneDispatcher, BasicListUI.MouseInputHandler, BasicMenuItemUI.MouseInputHandler, BasicMenuUI.MouseInputHandler, BasicScrollBarUI.ArrowButtonListener, BasicScrollBarUI.TrackListener, BasicSliderUI.TrackListener, BasicSplitPaneDivider.MouseHandler, BasicTabbedPaneUI.MouseHandler, BasicTableHeaderUI.MouseInputHandler, BasicTableUI.MouseInputHandler, BasicTextUI.BasicCaret, BasicToolBarUI.DockingListener, BasicTreeUI.MouseHandler, BasicTreeUI.MouseInputHandler, DefaultCaret, FormView.MouseEventListener, HTMLEditorKit.LinkController, MetalFileChooserUI.SingleClickListener, MetalToolBarUI.MetalDockingListener, MouseAdapter, MouseDragGestureRecognizer, MouseInputAdapter, ToolTipManager
The listener interface for receiving «interesting» mouse events (press, release, click, enter, and exit) on a component. (To track mouse moves and mouse drags, use the MouseMotionListener .) The class that is interested in processing a mouse event either implements this interface (and all the methods it contains) or extends the abstract MouseAdapter class (overriding only the methods of interest). The listener object created from that class is then registered with a component using the component’s addMouseListener method. A mouse event is generated when the mouse is pressed, released clicked (pressed and released). A mouse event is also generated when the mouse cursor enters or leaves a component. When a mouse event occurs, the relevant method in the listener object is invoked, and the MouseEvent is passed to it.