How do I handle mouse motion event?

package org.kodejava.example.swing;

import javax.swing.*;
import java.awt.event.MouseMotionAdapter;
import java.awt.event.MouseEvent;

public class MouseMotionListenerDemo extends JFrame {
    public MouseMotionListenerDemo() {

    private void initComponents() {
        setSize(400, 400);

        JTextArea textArea = new JTextArea("Hello World... try to move the mouse, click and drag it...");
        textArea.addMouseMotionListener(new MouseMotionAdapter() {
            public void mouseDragged(MouseEvent e) {
                System.out.println("Mouse Dragged...");

            public void mouseMoved(MouseEvent e) {
                System.out.println("Mouse Moved...");


    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new MouseMotionListenerDemo().setVisible(true));

Wayan Saryada

Founder at Kode Java Org
I am a programmer, a runner, a recreational diver, currently live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. If these posts help, you can support me, buy me a cup of coffee or tea. Thank you 🥳

Leave a Reply

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