event

Mouse motion listener 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 behaves 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.BorderLayout;
import java.awt.Component;
import java.awt.Frame;
import java.awt.TextArea;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;

public class MouseMotionListener {

  public static void main(String[] args) {

// Create frame with specific title

Frame frame = new Frame("Example Frame");

// Create a component to add to the frame; in this case a text area with sample text

Component textArea = new TextArea("Move mouse here to see mouse motion info...");

// Add a mouse motion listener to capture mouse motion events

textArea.addMouseMotionListener(new MouseMotionAdapter() {

    public void mouseMoved(MouseEvent evt) {

    TextArea source = (TextArea) evt.getSource();

  // Process current position of cursor while all mouse buttons are up.

    source.setText(source.getText() + "nMouse moved [" + evt.getPoint().x + "," + evt.getPoint().y + "]");

    }

    public void mouseDragged(MouseEvent evt) {

    TextArea source = (TextArea) evt.getSource();

  // Process current position of cursor while mouse button is pressed.

    source.setText(source.getText() + "nMouse dragged [" + evt.getPoint().x + "," + evt.getPoint().y + "]");

    }

});

// Add the components to the frame; by default, the frame has a border layout

frame.add(textArea, BorderLayout.NORTH);

// Show the frame

int width = 300;

int height = 300;

frame.setSize(width, height);

frame.setVisible(true);

  }

}

 
This was an example on how to work with MouseMotionListener components.

Ilias Tsagklis

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

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

0 Comments
Inline Feedbacks
View all comments
Back to top button