SlideShare una empresa de Scribd logo
En esta práctica vamos a crear un Applet Java donde una pelota rebota en los límites de un recinto. Se utiliza la técnica del
doble buffer para evitar parpadeos y para asegurar que la imagen está cargada se utiliza un objeto MediaTracker.




import java.applet.*;
import java.awt.*;

public class PelotaRebote extends Applet implements Runnable{

       private static final long serialVersionUID = 1L;

       private   static   final   int   ANCHO_APPLET = 250;
       private   static   final   int   ALTO_APPLET = 310;
       private   static   final   int   T_PAUSA = 10;
       private   static   final   int   VELOCIDAD = 3;

       //---
       private static final int K = 50;
       //---

       private Thread hilo;
       private Image pelota;

       //Doble_Buffer::Evitar parpadeo
       Graphics doble_buffer;
       Image imagen_db;

       //Propiedades de la pelota

       private   int   direc_X = 1;
       private   int   direc_Y = 1;
       private   int   pelota_X, pelota_Y;
       private   int   limite_der, limite_izq, limite_inf, limite_sup;




                                                                                bitCoach::Juan Bautista Cascallar Lorenzo
public void init(){

       precarga_de_imagenes();

       //--- doble buffer ---
       imagen_db = createImage(2*K + ANCHO_APPLET, 2*K + ALTO_APPLET);
       doble_buffer = imagen_db.getGraphics();

       //valores iniciales de la pelota
       pelota_X = (2 * K + ANCHO_APPLET) / 2;
       pelota_Y = (2 * K + ALTO_APPLET) / 2;
       limite_izq = K; //pared izquierda
       limite_der = ANCHO_APPLET + K - pelota.getWidth(this);
       limite_sup = K;
       limite_inf = ALTO_APPLET + K - pelota.getHeight(this);

}

public void precarga_de_imagenes(){
       pelota = getImage(getCodeBase(), "pelota.gif");
       //--- Utilizamos el tracker para asegurar que se carga la imagen (precarga) ---
       MediaTracker tracker = new MediaTracker(this);
       tracker.addImage(pelota, 0);
       try{
               tracker.waitForAll();
       }catch(InterruptedException e){}
}


public void start(){
       hilo = new Thread(this);
       hilo.start();
}

public void run(){
       while(true){
               actualizar_datos();
               repaint();//Llama a update()
               try{
                      Thread.sleep(T_PAUSA);
               }catch(Exception e){};
       }
}

public void actualizar_datos(){

       //Rebotes de la pelota con las paredes
       boolean reb_x = (pelota_X <= limite_izq) || (pelota_X >= limite_der);
       boolean reb_y = (pelota_Y >= limite_inf) || (pelota_Y <= limite_sup);

       //Si rebota en las paredes izq o der cambia la dirección del movimiento en el eje X.
       if(reb_x){ direc_X = -direc_X; }

       //Si rebota en las paredes inf o sup cambia la dirección del movimiento en el eje Y.
       if(reb_y){ direc_Y = -direc_Y; }

       //actualiza la posición de la pelota
       pelota_X = pelota_X + (VELOCIDAD * direc_X);
       pelota_Y = pelota_Y + (VELOCIDAD * direc_Y);
}

public void update(Graphics g){
       paint(g);
}




                                                                   bitCoach::Juan Bautista Cascallar Lorenzo
public void paint(Graphics g){

              // --- Relleno de Fondo del Applet ---

              doble_buffer.setColor(Color.GRAY);
              doble_buffer.fillRect(K - 5, K -5, ANCHO_APPLET + 10, ALTO_APPLET + K + 5);
              doble_buffer.setColor(Color.WHITE);
              doble_buffer.drawString("Java Applet::Pelota Rebotona", K, ALTO_APPLET + K + 15);
              doble_buffer.drawString("bitCoach::Juan Bautista Cascallar Lorenzo", K, ALTO_APPLET + K + 30);

              //Vaciamos el doble_buffer
              doble_buffer.fillRect(K, K, ANCHO_APPLET , ALTO_APPLET);

              //pintamos la pelota
              doble_buffer.drawImage(pelota,pelota_X,pelota_Y,this);

              //Volcamos todo los pintado en segundo plano al objeto Graphics del Applet
              g.drawImage(imagen_db, 0, 0, this);

       }

       public void stop(){
              if(hilo != null){
                      hilo = null;
              }
       }
}//FIN CLASE




                                                                         bitCoach::Juan Bautista Cascallar Lorenzo

Más contenido relacionado

PPTX
Comercio electronico
PPTX
Lecture 01
PPT
Flooring
PPTX
Topología de estrella
PPTX
Green building construction and materials aayush kumar
PPTX
Fərhadlı Rəvan.pptx
PDF
Ejemplo de movimiento en un applet (Thread::Runnable)
PDF
Codigo ejemplo j2 me
Comercio electronico
Lecture 01
Flooring
Topología de estrella
Green building construction and materials aayush kumar
Fərhadlı Rəvan.pptx
Ejemplo de movimiento en un applet (Thread::Runnable)
Codigo ejemplo j2 me

Similar a Java Applet:::Pelota que rebota en un recinto. (10)

DOCX
Parte 15
DOCX
PPTX
PPTX
Presentacion03
PPTX
Presentacion03
PPTX
PDF
Develop Mobile Apps with Corona SDK
PDF
EJERCICIOS TEMA 1. MICROCONTROLADORES II EN C
PPTX
Videojuegos
PPTX
Videojuegos
Parte 15
Presentacion03
Presentacion03
Develop Mobile Apps with Corona SDK
EJERCICIOS TEMA 1. MICROCONTROLADORES II EN C
Videojuegos
Videojuegos
Publicidad

Más de jubacalo (20)

PDF
jQuery Mobile :: Cuadros de diálogo
PDF
jQuery Mobile :: Enlaces a páginas internas.
PDF
MIT App Inventor2 Pintar en Imagen
PDF
Cronómetro con MIT App Inventor 2
PDF
App Android MiniBanco
PDF
Configurar entorno Android
PDF
Acceso a BBDD mediante un servlet
PDF
Find File Servlet DB
PDF
Acciones JSP
PDF
Servlets que manejan datos de formularios HTML
PDF
Jsp directiva page
PDF
Elementos de script en JSP
PDF
Proyecto JSP
PDF
Explicación del código del Servlet HolaMundo
PDF
Servlet Hola Mundo con Eclipse y Tomcat
PDF
Crear Base de Datos en Oracle
PDF
Web de noticias en Ajax
PDF
Escenarios
PDF
Matrices02
PDF
Gráficos
jQuery Mobile :: Cuadros de diálogo
jQuery Mobile :: Enlaces a páginas internas.
MIT App Inventor2 Pintar en Imagen
Cronómetro con MIT App Inventor 2
App Android MiniBanco
Configurar entorno Android
Acceso a BBDD mediante un servlet
Find File Servlet DB
Acciones JSP
Servlets que manejan datos de formularios HTML
Jsp directiva page
Elementos de script en JSP
Proyecto JSP
Explicación del código del Servlet HolaMundo
Servlet Hola Mundo con Eclipse y Tomcat
Crear Base de Datos en Oracle
Web de noticias en Ajax
Escenarios
Matrices02
Gráficos
Publicidad

Último (20)

PPTX
AGENTES PATÓGENOS Y LAS PRINCIPAL ENFERMEAD.pptx
PDF
COMPLETO__PROYECTO_VIVAN LOS NIÑOS Y SUS DERECHOS_EDUCADORASSOS.pdf
PDF
ACERTIJO Súper Círculo y la clave contra el Malvado Señor de las Formas. Por ...
PDF
SESION 12 INMUNIZACIONES - CADENA DE FRÍO- SALUD FAMILIAR - PUEBLOS INDIGENAS...
DOCX
PROYECTO DE APRENDIZAJE para la semana de fiestas patrias
DOCX
2 GRADO UNIDAD 5 - 2025.docx para primaria
PDF
Salcedo, J. et al. - Recomendaciones para la utilización del lenguaje inclusi...
PDF
benveniste-problemas-de-linguistica-general-i-cap-6 (1)_compressed.pdf
PDF
Escuela de Negocios - Robert kiyosaki Ccesa007.pdf
PDF
Escuelas Desarmando una mirada subjetiva a la educación
PDF
el - LIBRO-PACTO-EDUCATIVO-GLOBAL-OIEC.pdf
PDF
Fundamentos_Educacion_a_Distancia_ABC.pdf
PDF
TRAUMA_Y_RECUPERACION consecuencias de la violencia JUDITH HERMAN
PDF
Guia de Tesis y Proyectos de Investigacion FS4 Ccesa007.pdf
DOCX
Tarea De El Colegio Coding For Kids 1 y 2
PDF
Crear o Morir - Andres Oppenheimer Ccesa007.pdf
PDF
PFB-MANUAL-PRUEBA-FUNCIONES-BASICAS-pdf.pdf
PDF
La Evaluacion Formativa en Nuevos Escenarios de Aprendizaje UGEL03 Ccesa007.pdf
PDF
Habitos de Ricos - Juan Diego Gomez Ccesa007.pdf
PDF
Didactica de la Investigacion Educativa SUE Ccesa007.pdf
AGENTES PATÓGENOS Y LAS PRINCIPAL ENFERMEAD.pptx
COMPLETO__PROYECTO_VIVAN LOS NIÑOS Y SUS DERECHOS_EDUCADORASSOS.pdf
ACERTIJO Súper Círculo y la clave contra el Malvado Señor de las Formas. Por ...
SESION 12 INMUNIZACIONES - CADENA DE FRÍO- SALUD FAMILIAR - PUEBLOS INDIGENAS...
PROYECTO DE APRENDIZAJE para la semana de fiestas patrias
2 GRADO UNIDAD 5 - 2025.docx para primaria
Salcedo, J. et al. - Recomendaciones para la utilización del lenguaje inclusi...
benveniste-problemas-de-linguistica-general-i-cap-6 (1)_compressed.pdf
Escuela de Negocios - Robert kiyosaki Ccesa007.pdf
Escuelas Desarmando una mirada subjetiva a la educación
el - LIBRO-PACTO-EDUCATIVO-GLOBAL-OIEC.pdf
Fundamentos_Educacion_a_Distancia_ABC.pdf
TRAUMA_Y_RECUPERACION consecuencias de la violencia JUDITH HERMAN
Guia de Tesis y Proyectos de Investigacion FS4 Ccesa007.pdf
Tarea De El Colegio Coding For Kids 1 y 2
Crear o Morir - Andres Oppenheimer Ccesa007.pdf
PFB-MANUAL-PRUEBA-FUNCIONES-BASICAS-pdf.pdf
La Evaluacion Formativa en Nuevos Escenarios de Aprendizaje UGEL03 Ccesa007.pdf
Habitos de Ricos - Juan Diego Gomez Ccesa007.pdf
Didactica de la Investigacion Educativa SUE Ccesa007.pdf

Java Applet:::Pelota que rebota en un recinto.

  • 1. En esta práctica vamos a crear un Applet Java donde una pelota rebota en los límites de un recinto. Se utiliza la técnica del doble buffer para evitar parpadeos y para asegurar que la imagen está cargada se utiliza un objeto MediaTracker. import java.applet.*; import java.awt.*; public class PelotaRebote extends Applet implements Runnable{ private static final long serialVersionUID = 1L; private static final int ANCHO_APPLET = 250; private static final int ALTO_APPLET = 310; private static final int T_PAUSA = 10; private static final int VELOCIDAD = 3; //--- private static final int K = 50; //--- private Thread hilo; private Image pelota; //Doble_Buffer::Evitar parpadeo Graphics doble_buffer; Image imagen_db; //Propiedades de la pelota private int direc_X = 1; private int direc_Y = 1; private int pelota_X, pelota_Y; private int limite_der, limite_izq, limite_inf, limite_sup; bitCoach::Juan Bautista Cascallar Lorenzo
  • 2. public void init(){ precarga_de_imagenes(); //--- doble buffer --- imagen_db = createImage(2*K + ANCHO_APPLET, 2*K + ALTO_APPLET); doble_buffer = imagen_db.getGraphics(); //valores iniciales de la pelota pelota_X = (2 * K + ANCHO_APPLET) / 2; pelota_Y = (2 * K + ALTO_APPLET) / 2; limite_izq = K; //pared izquierda limite_der = ANCHO_APPLET + K - pelota.getWidth(this); limite_sup = K; limite_inf = ALTO_APPLET + K - pelota.getHeight(this); } public void precarga_de_imagenes(){ pelota = getImage(getCodeBase(), "pelota.gif"); //--- Utilizamos el tracker para asegurar que se carga la imagen (precarga) --- MediaTracker tracker = new MediaTracker(this); tracker.addImage(pelota, 0); try{ tracker.waitForAll(); }catch(InterruptedException e){} } public void start(){ hilo = new Thread(this); hilo.start(); } public void run(){ while(true){ actualizar_datos(); repaint();//Llama a update() try{ Thread.sleep(T_PAUSA); }catch(Exception e){}; } } public void actualizar_datos(){ //Rebotes de la pelota con las paredes boolean reb_x = (pelota_X <= limite_izq) || (pelota_X >= limite_der); boolean reb_y = (pelota_Y >= limite_inf) || (pelota_Y <= limite_sup); //Si rebota en las paredes izq o der cambia la dirección del movimiento en el eje X. if(reb_x){ direc_X = -direc_X; } //Si rebota en las paredes inf o sup cambia la dirección del movimiento en el eje Y. if(reb_y){ direc_Y = -direc_Y; } //actualiza la posición de la pelota pelota_X = pelota_X + (VELOCIDAD * direc_X); pelota_Y = pelota_Y + (VELOCIDAD * direc_Y); } public void update(Graphics g){ paint(g); } bitCoach::Juan Bautista Cascallar Lorenzo
  • 3. public void paint(Graphics g){ // --- Relleno de Fondo del Applet --- doble_buffer.setColor(Color.GRAY); doble_buffer.fillRect(K - 5, K -5, ANCHO_APPLET + 10, ALTO_APPLET + K + 5); doble_buffer.setColor(Color.WHITE); doble_buffer.drawString("Java Applet::Pelota Rebotona", K, ALTO_APPLET + K + 15); doble_buffer.drawString("bitCoach::Juan Bautista Cascallar Lorenzo", K, ALTO_APPLET + K + 30); //Vaciamos el doble_buffer doble_buffer.fillRect(K, K, ANCHO_APPLET , ALTO_APPLET); //pintamos la pelota doble_buffer.drawImage(pelota,pelota_X,pelota_Y,this); //Volcamos todo los pintado en segundo plano al objeto Graphics del Applet g.drawImage(imagen_db, 0, 0, this); } public void stop(){ if(hilo != null){ hilo = null; } } }//FIN CLASE bitCoach::Juan Bautista Cascallar Lorenzo