/home/wpollock1/public_html/Java/DrawIt.java

// This program creates a blank window and shows how to listen
// and use mouse motion and key events.
//
// This program allows users to draw lines by dragging with the mouse.
// Each time a mouse drag event is detected, we draw a (short) line
// from the previous point to the current point.  Thus, a drawing
// is reallly a series of lines.  The list of lines will be stored
// in a List, which is a kind of array that can grow.  Every
// call to the paint method will redraw all the lines in the List.
//
// We also need to listen for mouse press events; when the user
// presses the mouse button we need to update the lastX and lastY
// values.  Finally, a KeyListener is used to detect when the user
// hits the escape key.  This will erase the drawing (by emptying
// the List).  A popup menu is provided also, just for the
// heck of it.  (AWT Applets can't have menubars!)

// (C) 2003-2011 by Wayne Pollock, Tampa FL USA.  All Rights Reserved.

import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;

public class DrawIt extends Applet implements MouseListener,
                    MouseMotionListener, KeyListener, ActionListener
{
    private short lastX, lastY;  // The coordinates of mouse clicks.
    private java.util.List<Line> lineList;  // "List" is ambiguous!
    private String message = "Drag to draw, right-click or escape to erase";
    private Font myFont;
    private int messageX, messageY; // Where to draw the centered message.
    private boolean appletInitialized = true;  // Shows message when true.
    private PopupMenu popup;
    private Dialog aboutWin;

    public void init ()
    {
        lastX = lastY = -1;
        lineList = new ArrayList<Line>();
        myFont = new Font( "SansSerif", Font.BOLD, 12 );

        // Determine the x and y coordinates to center the message:
        Graphics g = getGraphics();
        FontMetrics fm = g.getFontMetrics( myFont );
        g.dispose();  // Must clean up extra Graphics objects!
        int width = fm.stringWidth( message );
        int height = fm.getAscent();  // Distance between baseline and top
        messageX = ( getSize().width - width ) / 2;
        messageY = ( getSize().height + height ) / 2;

        addMouseListener( this );
        addMouseMotionListener( this );
        addKeyListener( this );

        popup = new PopupMenu( "DrawIt" );
          popup.add( new MenuItem( "Clear" ) );
          popup.add( new MenuItem( "-" ) );  // or popup.addSeparator();
          popup.add( new MenuItem( "About..." ) );
          popup.addActionListener( this );
          add( popup );

        // Setup popup "About..." window (actually a Dialog):
        // First, find the Frame the Applet is drawn on.
        Component c = this.getParent();
        while ( c != null && !(c instanceof Frame) )
            c = c.getParent();
        aboutWin = new Dialog( (Frame) c );

          aboutWin.add( new Label("Demo of many GUI thingies."), "North" );
          aboutWin.add(
              new Label( "\u00A9 1999 by Wayne Pollock, Tampa FL USA" ),
                        "Center" );
          Button okBtn = new Button( "  OK  "  );
          Panel btnPanel = new Panel();
              btnPanel.add( okBtn );
          aboutWin.add( btnPanel, "South" );
          okBtn.addActionListener( new
              ActionListener ()
              {   public void actionPerformed( ActionEvent e )
                  {    aboutWin.setVisible( false ); }
              }
          );
          aboutWin.setBounds( 50, 50, 250, 150 );

        requestFocus();   // So our applet gets KeyEvents.
    }

    public void paint ( Graphics g )
    {
        if ( appletInitialized )
        {
            g.setFont( myFont );
            g.drawString( message, messageX, messageY );
        }
        else
        {   // Draw all lines:
            Iterator it = lineList.iterator();
            while ( it.hasNext() )
            {
                Line l = (Line) it.next();
                g.drawLine( l.x1, l.y1, l.x2, l.y2 );
            }
        }
    }

    // Record the coordinates of the mouse.  Also, at the first
    // mouse press repaint the screen (to erase the message):
    public void mousePressed ( MouseEvent e )
    {
        lastX = (short) e.getX();
        lastY = (short) e.getY();

        if ( e.getButton() == MouseEvent.BUTTON3 )
        {
            popup.show( this, lastX, lastY );
        }

        else if ( appletInitialized )
        {
            appletInitialized = false;
            repaint();
        }
    }

    public void mouseDragged ( MouseEvent e )
    {   short x = (short) e.getX(),   y = (short) e.getY();

        // Add line to list (class "Line" is defined below):
        lineList.add( new Line(lastX, lastY, x, y) );

        // Repainting every time causes flicker.  Instead, we
        // can draw the line from here:
        Graphics g = getGraphics();
        g.drawLine( lastX, lastY, x, y );
        g.dispose();  // Must clean up extra Graphics objects!

        // Remember current mouse coordinates:
        lastX = x;
        lastY = y;
    }

    public void keyTyped ( KeyEvent e )
    {
        if ( e.getKeyChar() == e.VK_ESCAPE )
            clear();
    }

    // "Line" is a class to store the coordinates of one line.
    // The coordinates are shorts rather than ints to save memory.
    // This "static" class is sort of a non-anonymous, inner class.

    static class Line
    {
        public short x1, y1, x2, y2;

        public Line( short xx1, short yy1, short xx2, short yy2 )
        {
            x1 = xx1;  y1 = yy1; x2 = xx2; y2 = yy2;
        }
    }

    private void clear ()
    {
        lineList.clear();
        appletInitialized = true;      // Displays message again.
        repaint();
    }

    public void actionPerformed( ActionEvent e )
    {
        String cmd = e.getActionCommand();
        if ( cmd.equals( "Clear" ) )
            clear();
        else            // User must have selected "About...".
            aboutWin.setVisible( true );
    }

    public void mouseClicked  ( MouseEvent e ) { }
    public void mouseEntered  ( MouseEvent e ) { }
    public void mouseExited   ( MouseEvent e ) { }
    public void mouseReleased ( MouseEvent e ) { }
    public void mouseMoved    ( MouseEvent e ) { }
    public void keyPressed    ( KeyEvent e )   { }
    public void keyReleased   ( KeyEvent e )   { }

}  // End of DrawIt.