import java.awt.*;
import java.awt.event.*;
public class DoodlePad extends java.applet.Applet implements ActionListener {
DrawPad dp;
public void init() {
setLayout( new BorderLayout() );
add( "Center", dp = new DrawPad() );
Panel p = new Panel();
Button clearButton = new Button("Clear");
clearButton.addActionListener( this );
p.add( clearButton );
add( "South", p );
}
public void actionPerformed( ActionEvent e ) {
System.out.println("clear!");
dp.clear();
}
}
class DrawPad extends Canvas {
Image drawImg;
Graphics drawGr;
int xpos, ypos, oxpos, oypos;
DrawPad() {
setBackground( Color.white );
enableEvents( AWTEvent.MOUSE_EVENT_MASK
| AWTEvent.MOUSE_MOTION_EVENT_MASK );
}
public void processEvent( AWTEvent e ) {
int x = ((MouseEvent)e).getX(), y = ((MouseEvent)e).getY();
if ( e.getID() == MouseEvent.MOUSE_DRAGGED ) {
xpos = x; ypos = y;
if ( drawGr != null )
drawGr.drawLine( oxpos, oypos, oxpos=xpos, oypos=ypos );
repaint();
} else
if ( e.getID() == MouseEvent.MOUSE_PRESSED ) {
oxpos = x; oypos = y;
}
super.processEvent(e);
}
public void update( Graphics g ) {
paint(g);
}
public void paint( Graphics g ) {
if ( drawImg == null ) {
drawImg = createImage( getSize().width, getSize().height );
drawGr = drawImg.getGraphics();
}
g.drawImage(drawImg, 0, 0, null);
}
public void clear() {
drawGr.clearRect(0, 0, getSize().width, getSize().height);
repaint();
}
}
|