Programacion Concurrente
  Rebotador 3
 

import java.awt.*;
import java.applet.Applet;
import java.awt.event.*;

public class Rebotador3 extends Applet implements ActionListener
{


    private Pelota3 pelota;
 private Button iniciar,detener;
 
 
 public void init ()
 {
  iniciar=new Button ("iniciar");
  add(iniciar);
  iniciar.addActionListener(this);
     detener=new Button("Detener");
     add(detener);
     detener.addActionListener(this);
 }
 
 
 public void actionPerformed(ActionEvent event)
 {
  if (event.getSource()== iniciar)
  {
   Graphics g = getGraphics();
      Pelota3 pelota= new Pelota3(g);
   pelota.start();
  }
  if(event.getSource()==detener)
     pelota.porFavorDetente();
 }

}


class Pelota3 extends Thread
{
 private boolean seguirRebotando;
 private Graphics g;
 private int x=7,xCambio=7;
 private int y=0,yCambio=2;
 private int diametro=10;
 private int rectIzqX=0,rectDerX=100;
 private int rectSupY=0,rectInfY=100;
 
   public Pelota3(Graphics graficos)
   {
    g=graficos;
    seguirRebotando=true;
   }
  
   public void porFavorDetente(){
    seguirRebotando=false;
   }
  
   public void run()
   {
    g.drawRect(rectIzqX,rectSupY,rectDerX-rectIzqX+10, rectInfY-rectSupY+10);
    
    while (seguirRebotando)
    {
     g.setColor(Color.white);
     g.fillOval(x,y,diametro,diametro);
     
     if (x+xCambio<=rectIzqX)
         xCambio=-xCambio;
     
     if (x+xCambio>=rectDerX)
         xCambio=-xCambio;
        
     if (y+yCambio<=rectSupY)
         yCambio=-yCambio;
        
     if (y+yCambio>=rectInfY)
         yCambio=-yCambio;
        
        x=x+xCambio;
        y=y+yCambio;
       
        g.setColor(Color.red);
        g.fillOval(x,y,diametro,diametro);
        //repaint();
       
        try {
         Thread.sleep(50);
        }       
       
        catch (InterruptedException e){
         System.err.println("excepcion de inactividad");
         
        }
    }
   }
}

 
   
 
Este sitio web fue creado de forma gratuita con PaginaWebGratis.es. ¿Quieres también tu sitio web propio?
Registrarse gratis