// Scribble0d Applet ... Etch and Sketch Applet ( erase button added ) package Scribble2; import java.applet.*; import java.awt.*; import java.util.*; public class Scribble0d extends Applet { private Button clear_button, erase_button; private Choice color_choices; private int last_x, last_y; private Color current_color; private Vector lines = new Vector(100, 100); public void init( ) { this.setBackground( Color.white ); clear_button = new Button( "Clear" ); clear_button.setBackground( Color.lightGray ); clear_button.setForeground( Color.black ); this.add( clear_button ); this.add( new Label( "Color:" ) ); color_choices = new Choice( ); color_choices.addItem( "black" ); color_choices.addItem( "red" ); color_choices.addItem( "yellow" ); color_choices.addItem( "green" ); color_choices.addItem( "blue" ); color_choices.addItem( "white" ); color_choices.setForeground( Color.black ); color_choices.setBackground( Color.lightGray ); this.add( color_choices ); erase_button = new Button( "Erase" ); erase_button.setBackground( Color.lightGray ); erase_button.setForeground( Color.black ); this.add( erase_button ); } public boolean mouseDown( Event e, int x, int y ) { last_x = x; last_y = y; return true; } public boolean mouseDrag( Event e, int x, int y ) { Graphics g = this.getGraphics( ); g.setColor( current_color ); g.drawLine( last_x, last_y, x, y ); lines.addElement( new LineC( last_x, last_y, x, y, current_color ) ); last_x = x; last_y = y; return true; } public void update (Graphics g) { paint( g ); } public void paint (Graphics g) { LineC l; //Graphics g = canvas.getGraphics(); for( int i = 0; i < lines.size(); i++ ) { l = (LineC)lines.elementAt( i ); g.setColor( l.clr ); g.drawLine( l.x1, l.y1, l.x2, l.y2 ); } } public boolean action( Event event, Object arg ) { if ( event.target == color_choices ) { if (arg.equals( "black" ) ) current_color = Color.black; if (arg.equals( "red" ) ) current_color = Color.red; if (arg.equals( "yellow" ) ) current_color = Color.yellow; if (arg.equals( "green" ) ) current_color = Color.green; if (arg.equals( "blue" ) ) current_color = Color.blue; if (arg.equals( "white" ) ) current_color = Color.white; return true; } else if ( event.target == clear_button ) { Graphics g = this.getGraphics(); Rectangle r = this.bounds( ); g.setColor( this.getBackground( ) ); g.fillRect( r.x, r.y, r.width, r.height ); lines.removeAllElements( ); repaint( ); return true; } else if ( event.target == erase_button ) { if ( !lines.isEmpty() ) { Graphics g = this.getGraphics(); g.setColor( this.getBackground( ) ); LineC l = (LineC)lines.lastElement(); g.drawLine( l.x1, l.y1, l.x2, l.y2 ); lines.removeElement( l ); repaint(); } return true; } else return super.action( event, arg ); } }