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 mouseMovedmouseDragged 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);


    public MouseMotionEvent() {



    public void mouseMoved(MouseEvent event) {

  x = (int) event.getPoint().getX();

  y = (int) event.getPoint().getY();


    public void mouseDragged(MouseEvent event) {


    public void paint(Graphics g) {


  g.fillRect(x, y, 10, 10);

This was an example on how to handle MouseMotion events in Java.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks
View all comments
Back to top button