Sketcher.java

Download this source file

// This program creates a blank window and shows how to listen
// and use mouse events.  This program allows users to draw
// lines by clicking with the mouse.  A double-click ends
// the current series of lines.  A right-click clears the window.
// (In addition to the test for a right-click shown, you can also
// test a MouseEvent e for shift-click, alt-click, ctl-click, etc.)

// Written 2003 by Wayne Pollock, Tampa FL USA.

import java.awt.*;
import java.awt.event.*;

public class Sketcher extends Frame implements MouseListener
{  private int lastX, lastY, x, y;  // The coordinates of mouse clicks.
   private boolean clearWindow, newSeriesOfLines;

   public static void main ( String [] args )
   {  Sketcher win = new Sketcher();

      // Window closing handler:
      win.addWindowListener( new WindowAdapter()
         {  public void windowClosing ( WindowEvent we )
            {  System.exit( 0 );  }
         }
      );
   }

   Sketcher ()
   {  setTitle( "Sketcher" );
      setSize( 350, 250 );
      clearWindow = true;
      newSeriesOfLines = true;

      // Hook up event handling:
      addMouseListener( this );
      setVisible( true );
   }

   public void mouseReleased( MouseEvent e )
   {  // Check for a right-click:
      if ( e.getButton() == MouseEvent.BUTTON3 )
      {  clearWindow = newSeriesOfLines = true;
         System.err.println( "Right-Click!" );
         repaint();

      } else if ( e.getClickCount() == 1 )  // A single click, or
      {  x = e.getX();                      // 1st of a dbl click.
         y = e.getY();
         System.err.println( "Single-Click at (" + x + ", " + y + ")" );
         repaint();

      } else  // A double (or more) click!
      {  newSeriesOfLines = true;
         System.err.println( "Double-Click!" );
      }
   }

   public void mouseEntered  ( MouseEvent e ) { }

   public void mouseExited   ( MouseEvent e ) { }

   public void mousePressed  ( MouseEvent e ) { }

   public void mouseClicked ( MouseEvent e ) { }

   // Over-ride update to prevent "flicker":
   public void update( Graphics g )
   {  paint( g );
   }

   public void paint ( Graphics g )
   {
      System.err.println( "In paint(): x=" + x + ", y=" + y +
                          ", lastX=" + lastX + ", lastY=" + lastY );
      if ( clearWindow )
      {  Dimension d = this.getSize();
         g.clearRect( 0, 0, d.width, d.height );
         int topInset = getInsets().top;
         g.drawString( "Double-click to mark end of series, " +
                       "right-click to erase.", 15, topInset + 15 );
         clearWindow = false;
         return;
      }

      if ( ! newSeriesOfLines )
         g.drawLine( lastX, lastY, x, y );
       else
         newSeriesOfLines = false;

      lastX = x;
      lastY = y;
   }
}