How do I handle mouse event in swing?

package org.kodejava.example.swing;

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

public class MouseListenerDemo extends JFrame {
    public MouseListenerDemo() {
        initComponents();
    }

    protected void initComponents() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(400, 400);
        JTextArea textArea = new JTextArea();
        textArea.setText("Press the mouse button...");

        textArea.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                System.out.println("MouseListenerDemo.mouseClicked");
            }

            public void mousePressed(MouseEvent e) {
                System.out.println("MouseListenerDemo.mousePressed");
            }

            public void mouseReleased(MouseEvent e) {
                System.out.println("MouseListenerDemo.mouseReleased");
            }

            public void mouseEntered(MouseEvent e) {
                System.out.println("MouseListenerDemo.mouseEntered");
            }

            public void mouseExited(MouseEvent e) {
                System.out.println("MouseListenerDemo.mouseExited");
            }
        });

        getContentPane().add(textArea);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new MouseListenerDemo().setVisible(true);
            }
        });
    }
}

Wayan Saryada

Programmer, runner, recreational diver, live in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA.

Leave a Reply