MouseMotionListener (and MouseAdapter) Example

This program demonstrates both MouseMotionListener and MouseAdapter. We could easily have used MouseListener instead of MouseAdapter. It draws a cross-hair when you move the mouse. If you drag the mouse it will constantly draw a line from where you started dragging to where you are currently dragging.

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

public class MouseMotionListenerExample implements MouseMotionListener
{
   Drawing draw = new Drawing();
   int x1, y1, x2 = -1, y2;
   boolean moving = false;
   
   public MouseMotionListenerExample()
   {
      JFrame frame = new JFrame("MouseMotionListener");
      frame.setSize(600,600);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.add(draw);
      draw.addMouseMotionListener(this);
      draw.addMouseListener(new MouseListen());
      frame.setVisible(true);
   }
   
   class MouseListen extends MouseAdapter
   {
      public void mousePressed(MouseEvent e)
      {
         x1 = e.getX();
         y1 = e.getY();
      }
   }
   class Drawing extends JComponent
   {
      public void paint(Graphics g)
      {
         if (moving)
         {
            g.drawLine(x1 - 15, y1, x1 + 15, y1);
            g.drawLine(x1, y1 - 15, x1, y1 + 15);
         }
         else if (x2 > 0)
            g.drawLine(x1, y1, x2, y2);
      }
   }
   
   public void mouseMoved(MouseEvent e)
   {
      x1 = e.getX();
      y1 = e.getY();
      moving = true;
      draw.repaint();
   }
   
   public void mouseDragged(MouseEvent e)
   {
      moving = false;
      x2 = e.getX();
      y2 = e.getY();
      draw.repaint();
   }
   
   public static void main(String[] args)
   {
      new MouseMotionListenerExample();
   }
}