Handling Mouse Events in Swing - Java Swing

Java examples for Swing:Mouse Event

Introduction

You can handle mouse event (clicked, entered, exited, pressed, and released) on a component.

The MouseEvent class has many methods that provide the details about a mouse event:

  • getClickCount() returns the number of clicks a mouse made.
  • getX() and getY() return the x and y positions of the mouse with respect to the component.
  • getXOnScreen() and getYOnScreen() return the absolute x and y positions of the mouse.

The following code has an implementation for all five methods of the MouseListener interface.

Demo Code

import java.awt.FlowLayout;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import javax.swing.JButton;
import javax.swing.JFrame;

public class Main extends JFrame {
  JButton mouseButton = new JButton("No Mouse Movement Yet!");

  public Main() {
    super("Handling Mouse Event");

    this.setDefaultCloseOperation(EXIT_ON_CLOSE);
    this.setLayout(new FlowLayout());
    this.getContentPane().add(mouseButton);

    mouseButton.addMouseListener(new MouseListener() {
      @Override//w  w w.j  a  v  a  2 s.c om
      public void mouseClicked(MouseEvent e) {
      }

      @Override
      public void mousePressed(MouseEvent e) {
      }

      @Override
      public void mouseReleased(MouseEvent e) {
      }

      @Override
      public void mouseEntered(MouseEvent e) {
        mouseButton.setText("Mouse has entered!");
      }

      @Override
      public void mouseExited(MouseEvent e) {
        mouseButton.setText("Mouse has exited!");
      }
    });
  }

  public static void main(String[] args) {
    Main frame = new Main();
    frame.pack();
    frame.setVisible(true);
  }
}

Related Tutorials