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



  public class Anim1 extends JApplet implements Runnable,ActionListener {
   
   Display disegno;
   Thread animazione;
   JButton b1,b2;
   int x,y,r,x0;
   boolean running;
   
   public void init() {

     disegno = new Display();
     getContentPane().setLayout(new BorderLayout());
     getContentPane().add(disegno, BorderLayout.CENTER); 
     b1 = new JButton("Start");
     b1.addActionListener(this);
     getContentPane().add(b1, BorderLayout.NORTH); 
     b2 = new JButton("Stop");
     getContentPane().add(b2, BorderLayout.SOUTH); 
     b2.addActionListener(this);
     
     x = 0; y=10; r=20; x0=r;
     running = true;
       }

   public void start() {
    if (animazione == null) {
        animazione = new Thread(this);
        animazione.start();
    }
   }

  public void stop() {
     if (animazione != null) {
       animazione = null;
     }
   }

   public void run() {
    while(running) {
      for (x = x0; x <= disegno.getSize().width&&running ; x=x+1) {
        disegno.repaint();
        try { Thread.sleep(100);}
       catch (InterruptedException e) { }
 }
 }
      x0 = x;
 }
 public void actionPerformed(ActionEvent evt) {
   if(evt.getSource()==b1){running=true;start();} 
      else {running=false;stop();}
 }
   class Display extends JPanel{

    public void  paintComponent(Graphics g) {
      super.paintComponent(g);
      g.setColor(Color.red);
      g.fillOval(x,y,2*r,2*r);
   }
}
}
