import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class Tasto4 extends JApplet implements ActionListener,MouseMotionListener {

 Display disegno;
 Color c;
 JButton cancella,rosso,verde,blu;
 JPanel b;
 boolean cancellaDisegno; 
 int x,y;
 int lunghezza,larghezza;

 public void init(){
  disegno = new Display(this);
  cancellaDisegno=false;
  getContentPane().add(disegno, BorderLayout.CENTER);
  b = new JPanel();
  rosso = new JButton("Rosso");
  rosso.addActionListener(this);
  b.add(rosso);
  verde = new JButton("Verde");
  verde.addActionListener(this);
  b.add(verde);
  blu = new JButton("Blu");
  blu.addActionListener(this);
  b.add(blu);
  getContentPane().add(b, BorderLayout.SOUTH); 
  cancella = new JButton("Cancella");
  cancella.addActionListener(this);
  getContentPane().add(cancella, BorderLayout.NORTH); 
 }

 public void actionPerformed(ActionEvent evt) {
    if(evt.getSource()==cancella){ 
    cancellaDisegno=true;
     disegno.repaint();
   } else {
     if(evt.getSource()==verde)c=Color.green;
     if(evt.getSource()==rosso)c=Color.red;
     if(evt.getSource()==blu)c=Color.blue;
     cancellaDisegno = true;
     disegno.repaint();
     }
   }
 public void mouseDragged(MouseEvent evt) {
  x = evt.getX();  // x-coordinate where user clicked.
  y = evt.getY();
  disegno.repaint();
 }
 public void mouseMoved(MouseEvent evt) { }

class Display extends JPanel {
 Tasto4  t; 
 Display(Tasto4 t1){ 
   t=t1;
   addMouseMotionListener(t);
  }
 public void paintComponent(Graphics g){
   g.setColor(c);
   if(!t.cancellaDisegno) {
       g.setColor(t.c);
       g.fillRect(t.x,t.y,1,1);
   } else {
       t.cancellaDisegno=false;
       t.larghezza=getSize().width;
       t.lunghezza=getSize().height;
       g.setColor(Color.black);
       g.fillRect(0,0,t.larghezza,t.lunghezza);
     }
  }
 }
 }
