/home/wpollock1/public_html/Java/MouseEventDemo.java

// Demonstrates mouseClicked and MouseMoved events, by
// redrawing a box where you click, and having a star follow
// the cursor.
//
// Written 2016 by Wayne Pollock, Tampa Florida USA

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

class MouseEventDemo extends JPanel
{
    // Holds box and star coordinates.
    // The star coordinates are actually (0,0), but then the star is
    // drawn under the cursor.  By faking the initial coords to the bottom-
    // right of the bounding box, the star is drawn above and to the left of
    // the cursor.
    int boxX = 0, boxY = 0, starX = 10, starY = 10;
    Polygon star = new Polygon();

    public MouseEventDemo()
    {
        // Construct a 5-point star in a 10x10 box:
        star.addPoint(5, 0);
        star.addPoint(7, 3);
        star.addPoint(10, 3);
        star.addPoint(8, 6);
        star.addPoint(8, 10);
        star.addPoint(5, 7);
        star.addPoint(2, 10);
        star.addPoint(2, 6);
        star.addPoint(0, 3);
        star.addPoint(3, 3);

        addMouseListener(new MouseAdapter()
        {
            @Override
            public void mousePressed(MouseEvent e)
            {
                boxX = e.getX();
                boxY = e.getY();
                repaint();
            }
        });

        addMouseMotionListener(new MouseMotionAdapter()
        {
            @Override
            public void mouseMoved(MouseEvent e)
            {
                int deltaX = e.getX() - starX;
                starX = e.getX();
                int deltaY = e.getY() - starY;
                starY = e.getY();
                star.translate( deltaX, deltaY );
                repaint();
            }
        });
    }

    @Override
    public void paintComponent(Graphics g)
    {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g;
        g2.fillRect(boxX, boxY, 10, 10);
        g2.fill( star );
    }

   public static void main ( String [] args )
   {
      JFrame frame = new JFrame( "MouseEventDemo - Click to draw rect" );
      frame.add( new MouseEventDemo() );
      frame.setSize( 400, 200 );
      frame.setDefaultCloseOperation( JFrame.DISPOSE_ON_CLOSE );
      frame.setVisible( true );
   }
}