DrawIt.java

Download DrawIt.java

  1: // This program creates a blank window and shows how to listen
  2: // and use mouse motion and key events.
  3: //
  4: // This program allows users to draw lines by dragging with the mouse.
  5: // Each time a mouse drag event is detected, we draw a (short) line
  6: // from the previous point to the current point.  Thus, a drawing
  7: // is reallly a series of lines.  The list of lines will be stored
  8: // in a List, which is a kind of array that can grow.  Every
  9: // call to the paint method will redraw all the lines in the List.
 10: //
 11: // We also need to listen for mouse press events; when the user
 12: // presses the mouse button we need to update the lastX and lastY
 13: // values.  Finally, a KeyListener is used to detect when the user
 14: // hits the escape key.  This will erase the drawing (by emptying
 15: // the List).  A popup menu is provided also, just for the
 16: // heck of it.  (AWT Applets can't have menubars!)
 17: 
 18: // (C) 2003-2011 by Wayne Pollock, Tampa FL USA.  All Rights Reserved.
 19: 
 20: import java.applet.*;
 21: import java.awt.*;
 22: import java.awt.event.*;
 23: import java.util.*;
 24: 
 25: public class DrawIt extends Applet implements MouseListener,
 26:                     MouseMotionListener, KeyListener, ActionListener
 27: {
 28:     private short lastX, lastY;  // The coordinates of mouse clicks.
 29:     private java.util.List<Line> lineList;  // "List" is ambiguous!
 30:     private String message = "Drag to draw, right-click or escape to erase";
 31:     private Font myFont;
 32:     private int messageX, messageY; // Where to draw the centered message.
 33:     private boolean appletInitialized = true;  // Shows message when true.
 34:     private PopupMenu popup;
 35:     private Dialog aboutWin;
 36: 
 37:     public void init ()
 38:     {
 39:         lastX = lastY = -1;
 40:         lineList = new ArrayList<Line>();
 41:         myFont = new Font( "SansSerif", Font.BOLD, 12 );
 42: 
 43:         // Determine the x and y coordinates to center the message:
 44:         Graphics g = getGraphics();
 45:         FontMetrics fm = g.getFontMetrics( myFont );
 46:         g.dispose();  // Must clean up extra Graphics objects!
 47:         int width = fm.stringWidth( message );
 48:         int height = fm.getAscent();  // Distance between baseline and top
 49:         messageX = ( getSize().width - width ) / 2;
 50:         messageY = ( getSize().height + height ) / 2;
 51: 
 52:         addMouseListener( this );
 53:         addMouseMotionListener( this );
 54:         addKeyListener( this );
 55: 
 56:         popup = new PopupMenu( "DrawIt" );
 57:           popup.add( new MenuItem( "Clear" ) );
 58:           popup.add( new MenuItem( "-" ) );  // or popup.addSeparator();
 59:           popup.add( new MenuItem( "About..." ) );
 60:           popup.addActionListener( this );
 61:           add( popup );
 62: 
 63:         // Setup popup "About..." window (actually a Dialog):
 64:         // First, find the Frame the Applet is drawn on.
 65:         Component c = this.getParent();
 66:         while ( c != null && !(c instanceof Frame) )
 67:             c = c.getParent();
 68:         aboutWin = new Dialog( (Frame) c );
 69: 
 70:           aboutWin.add( new Label("Demo of many GUI thingies."), "North" );
 71:           aboutWin.add(
 72:               new Label( "\u00A9 1999 by Wayne Pollock, Tampa FL USA" ),
 73:                         "Center" );
 74:           Button okBtn = new Button( "  OK  "  );
 75:           Panel btnPanel = new Panel();
 76:               btnPanel.add( okBtn );
 77:           aboutWin.add( btnPanel, "South" );
 78:           okBtn.addActionListener( new
 79:               ActionListener ()
 80:               {   public void actionPerformed( ActionEvent e )
 81:                   {    aboutWin.setVisible( false ); }
 82:               }
 83:           );
 84:           aboutWin.setBounds( 50, 50, 250, 150 );
 85: 
 86:         requestFocus();   // So our applet gets KeyEvents.
 87:     }
 88: 
 89:     public void paint ( Graphics g )
 90:     {
 91:         if ( appletInitialized )
 92:         {
 93:             g.setFont( myFont );
 94:             g.drawString( message, messageX, messageY );
 95:         }
 96:         else
 97:         {   // Draw all lines:
 98:             Iterator it = lineList.iterator();
 99:             while ( it.hasNext() )
100:             {
101:                 Line l = (Line) it.next();
102:                 g.drawLine( l.x1, l.y1, l.x2, l.y2 );
103:             }
104:         }
105:     }
106: 
107:     // Record the coordinates of the mouse.  Also, at the first
108:     // mouse press repaint the screen (to erase the message):
109:     public void mousePressed ( MouseEvent e )
110:     {
111:         lastX = (short) e.getX();
112:         lastY = (short) e.getY();
113: 
114:         if ( e.getButton() == MouseEvent.BUTTON3 )
115:         {
116:             popup.show( this, lastX, lastY );
117:         }
118: 
119:         else if ( appletInitialized )
120:         {
121:             appletInitialized = false;
122:             repaint();
123:         }
124:     }
125: 
126:     public void mouseDragged ( MouseEvent e )
127:     {   short x = (short) e.getX(),   y = (short) e.getY();
128: 
129:         // Add line to list (class "Line" is defined below):
130:         lineList.add( new Line(lastX, lastY, x, y) );
131: 
132:         // Repainting every time causes flicker.  Instead, we
133:         // can draw the line from here:
134:         Graphics g = getGraphics();
135:         g.drawLine( lastX, lastY, x, y );
136:         g.dispose();  // Must clean up extra Graphics objects!
137: 
138:         // Remember current mouse coordinates:
139:         lastX = x;
140:         lastY = y;
141:     }
142: 
143:     public void keyTyped ( KeyEvent e )
144:     {
145:         if ( e.getKeyChar() == e.VK_ESCAPE )
146:             clear();
147:     }
148: 
149:     // "Line" is a class to store the coordinates of one line.
150:     // The coordinates are shorts rather than ints to save memory.
151:     // This "static" class is sort of a non-anonymous, inner class.
152: 
153:     static class Line
154:     {
155:         public short x1, y1, x2, y2;
156: 
157:         public Line( short xx1, short yy1, short xx2, short yy2 )
158:         {
159:             x1 = xx1;  y1 = yy1; x2 = xx2; y2 = yy2;
160:         }
161:     }
162: 
163:     private void clear ()
164:     {
165:         lineList.clear();
166:         appletInitialized = true;      // Displays message again.
167:         repaint();
168:     }
169: 
170:     public void actionPerformed( ActionEvent e )
171:     {
172:         String cmd = e.getActionCommand();
173:         if ( cmd.equals( "Clear" ) )
174:             clear();
175:         else            // User must have selected "About...".
176:             aboutWin.setVisible( true );
177:     }
178: 
179:     public void mouseClicked  ( MouseEvent e ) { }
180:     public void mouseEntered  ( MouseEvent e ) { }
181:     public void mouseExited   ( MouseEvent e ) { }
182:     public void mouseReleased ( MouseEvent e ) { }
183:     public void mouseMoved    ( MouseEvent e ) { }
184:     public void keyPressed    ( KeyEvent e )   { }
185:     public void keyReleased   ( KeyEvent e )   { }
186: 
187: }  // End of DrawIt.