Home » Desktop Java » awt » event » MouseMotion event example

About Ilias Tsagklis

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

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

  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.

(No Ratings Yet)
Start the discussion Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Leave a Reply

avatar
  Subscribe  
Notify of