lunes, 2 de febrero de 2009

Un poco de programacion

haciendo una pequeña aplicacion en java
un frame que muestra como lanzar un hilo

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Frame1 extends JFrame{
private Button LanzarHilo;
private Button Terminar;
private Container c;
public Frame1()

{
super("mestra de hilos");

c=getContentPane();
c.setLayout(new FlowLayout());
///////////////////////////////////////////////////////////////////////////////////
//boton iniciar hilo
LanzarHilo=new Button("Lanzar hilo");

LanzarHilo.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent event)
{
if(event.getSource()==LanzarHilo)
{
Graphics g=getGraphics();
Pelota pelota= new Pelota(g);
pelota.start();
}
}//fin de action performend


});
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////boton terminar programa
Terminar = new Button("Fin");

Terminar.addActionListener( new ActionListener(){

public void actionPerformed(ActionEvent event)
{
if(event.getSource()==Terminar)
{
System.exit(0);
}
}//fin de action performend


});//fin de action listener

///////////////////////////////////////////////////////////////////////////////////////////////
c.add(LanzarHilo);
c.add(Terminar);
setSize(700,600);



show();
}

//////////////////////////////////////////////////////

public static void main(String[] args) {

// TODO, add your application code
Frame1 panel1=new Frame1();


System.out.println("Hello World!");
}
/////////////////////////////////////////////

class Pelota extends Thread{
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 Pelota(Graphics graficos)
{
g=graficos;
}

public void run(){
g.drawRect(rectIzqX, rectSupY, rectDerX-rectIzqX+10,rectInfY-rectSupY+10);

for(int n =1; n< 1000 ;n++)
{
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);

try{
Thread.sleep(50);
}catch(InterruptedException e){
System.err.println("excepcion de inactividad");
}

}


}
}

}