Java AWT MouseEvent Handle mouse event and mouse motion event

Introduction

To handle mouse events, implement the MouseListener and the MouseMotionListener interfaces.

You can also implement MouseWheelListener.

// Demonstrate the key event handlers.
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;

class SimpleKey extends JTextArea implements  MouseListener, MouseMotionListener  {

  public SimpleKey() {
    addMouseListener(this);
    addMouseMotionListener(this);
  }/*w ww .  j  a  v a  2 s  .  c o  m*/
  // Handle mouse clicked.
  public void mouseClicked(MouseEvent me) {
    System.out.println("Mouse Clicked");
    System.out.println(me);
    
  }

  // Handle mouse entered.
  public void mouseEntered(MouseEvent me) {

    System.out.println("Mouse entered");
    System.out.println(me);

  }

  // Handle mouse exited.
  public void mouseExited(MouseEvent me) {
    System.out.println("Mouse exited");
    System.out.println(me);
  }

  // Handle button pressed.
  public void mousePressed(MouseEvent me) {
    System.out.println("Mouse Pressed");
    System.out.println(me);
  }

  // Handle button released.
  public void mouseReleased(MouseEvent me) {
    System.out.println("Mouse Released");
    System.out.println(me);
  }

  // Handle mouse dragged.
  public void mouseDragged(MouseEvent me) {
    System.out.println("Dragging mouse");
    System.out.println(me);
  }

  // Handle mouse moved.
  public void mouseMoved(MouseEvent me) {
    System.out.println("Dragging Moved");
    System.out.println(me);
  }
}

public class Main {
  public static void main(String args[]) {
    // Create the frame on the event dispatching thread.
    SwingUtilities.invokeLater(new Runnable() {
      public void run() {
        // Create a new JFrame container.
        JFrame jfrm = new JFrame("java2s.com");

        // Give the frame an initial size.
        jfrm.setSize(220, 200);

        // Terminate the program when the user closes the application.
        jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        // Add the label to the content pane.
        jfrm.add(new JScrollPane(new SimpleKey()));

        // Display the frame.
        jfrm.setVisible(true);

      }
    });
  }
}



PreviousNext

Related