event
MouseMotion event example
With this tutorial we shall show you how to work with the MouseMotionListener
interface in Java. It is a very useful feature when you want to have full control over mouse events and mouse input that the users give. It also particularly useful when you want to make your application behave according to the mouse events that occur. This is very important as it’s very easy for the user to make use of the mouse in order to provide input for your application.
In short in order to work with MouseMotionListener
, one should follow these steps:
- Create a class that implements the
MouseMotionListener
- Override
mouseMoved
,mouseDragged
methods in order to customize the handling of these specific event. Now every time the user moves the mouse o drags an object, the corresponding method will be executed.
Let’s take a look at the code snippets that follow.
package com.javacodegeeks.snippets.desktop; import java.awt.Color; import java.awt.Graphics; import java.awt.event.MouseEvent; import java.awt.event.MouseMotionListener; import javax.swing.JFrame; import javax.swing.JPanel; public class MouseMotionEvent extends JPanel implements MouseMotionListener { private int x, y; public static void main(String[] args) { JFrame jFrame = new JFrame(); jFrame.getContentPane().add(new MouseMotionEvent()); jFrame.setSize(600, 500); jFrame.setVisible(true); } public MouseMotionEvent() { addMouseMotionListener(this); setVisible(true); } @Override public void mouseMoved(MouseEvent event) { x = (int) event.getPoint().getX(); y = (int) event.getPoint().getY(); repaint(); } @Override public void mouseDragged(MouseEvent event) { mouseMoved(event); } @Override public void paint(Graphics g) { g.setColor(Color.RED); g.fillRect(x, y, 10, 10); } }
This was an example on how to handle MouseMotion events in Java.