Mostrando entradas con la etiqueta Taller de POO. Mostrar todas las entradas
Mostrando entradas con la etiqueta Taller de POO. Mostrar todas las entradas

martes, 1 de noviembre de 2011

Evento, Errores y Excepciones

Eventos
 
 public void agregarActionListener(ActionListener listener)
 {
  biniciar.addActionListener(listener);
  biniciar.setActionCommand("Jugar");
  salir.addActionListener(listener);
  salir.setActionCommand("Salir");
  jugar.addActionListener(listener);
  jugar.setActionCommand("jugar");
  ver.addActionListener(listener);
  ver.setActionCommand("Ver");
 }     
 
public void actionPerformed(ActionEvent e)
 {
      vista = new Vista();
  String evento = e.getActionCommand();
        if(evento.equals("Jugar"))
        {   
              vista.tablero();
    
        }
        else if(evento.equals("Salir")){
          System.exit(0);
        }
        else if(evento.equals("Ver")){
         }
   }
    
Errores y Excepciones
  try{ ImageIcon ima = new ImageIcon("damas.png");
    } catch(NullPointerException e){
 System.out.println("No se pudó cargar la imagen");
    }

Patrones de Diseño

Modelo Vista Controlador

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

public class Vista{
    private JFrame ventana;
    private JButton b1, b3;
    private JButton b2 [][] = new JButton [8][8];
    private JPanel p1 = new JPanel();
    private JPanel der,izq;
    private JPanel p2, p3,arr,aba;
    private JLabel l2;
    private JMenuBar barra;
    JMenu archivo, ayuda;
    JMenuItem jugar,salir,ver;
    Image img;

    public Vista(){
 ventana = new JFrame ();
 ventana.setTitle("DAMAS");
 menu();
 ventanai();
 ventana.setResizable(false);
 ventana.setSize(600,600);
 ventana.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 ventana.setVisible(true);
     }

    public void menu(){
 barra = new JMenuBar();
 archivo = new JMenu("Juego");
 ayuda = new JMenu("Ayuda");
        jugar = new JMenuItem("Jugar");
 salir = new JMenuItem("Salir");
 ver = new JMenuItem("Ver");
 archivo.add(jugar);
 archivo.add(salir);
 ayuda.add(ver);
        barra.add(archivo);
 barra.add(ayuda);
        ventana.setJMenuBar(barra);
    }

    public void ventanai (){
 p1 = new JPanel();
 l2 = new JLabel();
 ImageIcon ima = new ImageIcon("damas.jpg");
 p1.setLayout(null);
 p1.setBackground(Color.WHITE);
 b1 = new JButton ("JUGAR");
 b1.setBackground(Color.WHITE);
 b1.setBounds(250, 240, 100, 50);
 p1.add(l2);
 l2.setIcon(ima);
 l2.setSize(600,600);
 l2.setVisible(true);
        p1.add(b1);
 ventana.add(p1);
 ventana.pack();
 p1.setVisible(true); 
    }
 
 public void agregarActionListener(ActionListener listener)
 {
  b1.addActionListener(listener);
  b1.setActionCommand("JUGAR");
  salir.addActionListener(listener);
  salir.setActionCommand("SALIR");
 }
    
    public void tablero(){
 p2 = new JPanel();
 p2.setBackground(Color.WHITE);
 p2.setLayout ( new GridLayout(8,8)); 
 for( int i = 0; i < 3; i++){
     for( int j = 0; j < 8; j++){
         if((i + j) % 2 != 0){
      b2[i][j] = new JButton("", new ImageIcon("rojo.png"));
      b2[i][j].setBackground(Color.BLACK);
  }
  else {
      b2[i][j] = new JButton("");
      b2[i][j].setBackground(Color.WHITE); 
       }    
     }
 }
        for( int i = 3; i <= 4; i++){
       for( int j = 0; j < 8; j++){
         if((i + j) % 2 != 0){
      b2[i][j] = new JButton("");
      b2[i][j].setBackground(Color.BLACK);
      }
  else {
      b2[i][j] = new JButton("");
      b2[i][j].setBackground(Color.WHITE); 
      }
        }
 }
 
    for( int i = 5; i < 8; i++){
      for( int j = 0; j < 8; j++){
      if((i + j) % 2 != 0){
      b2[i][j] = new JButton("", new ImageIcon("azul.png"));
      b2[i][j].setBackground(Color.BLACK);
      }
    else {
      b2[i][j] = new JButton("");
      b2[i][j].setBackground(Color.WHITE); 
     }
      }
   } 
     
    for( int i = 0; i < 8; i++){
       for( int j = 0; j < 8; j++){
    p2.add(b2[i][j]);
         }
      }
        ventana.add(p2);      
    }
 }

Controlador
  
import java.awt.event.*;

public class Controlador implements ActionListener{
    Vista vista;
    Modelo modelo;

    public Controlador(Vista vista, Modelo modelo){
  this.vista = vista;
  this.modelo = modelo;
        vista.agregarActionListener(this);
    }

     public void actionPerformed(ActionEvent e)
 {
      vista = new Vista();
  String evento = e.getActionCommand();
        if(evento.equals("JUGAR"))
        {   
              vista.tablero();
    
        }
        else if(evento.equals("SALIR")){
          System.exit(0);
        }
 }

}
Modelo
  

public class Modelo {
 
 public Modelo(){
  
 }
 
 public void iniciar(){
 
 }
 
 public void salir(){
  
 }
 
 public void terminar(){
  
 }

}
Main
  
public class Damas
{
 public static void main (String[] args)
 {
  Vista vista1= new Vista();
  Modelo modelo1 = new Modelo();
  Controlador contr1 = new Controlador(vista1, modelo1);
 }
}

Interfaz Gráfica

Ventana principal que se compone de un botón que nos permite inicializar el juego


Menu con las opciones de juego y ayuda



Ventana que se muestra al inicializar el juego


Referencia
Imagen

jueves, 29 de septiembre de 2011

Autogeneración de código

Equipo
import java.util.*;


/**
 * Class Equipo
 */
public class Equipo {

  //
  // Fields
  //

  private int cantidad;
  private int color;
  private String nombre;
  private boolean activo;
  
  //
  // Constructors
  //
  public Equipo () { };
  
  //
  // Methods
  //


  //
  // Accessor methods
  //

  /**
   * Set the value of cantidad
   * @param newVar the new value of cantidad
   */
  private void setCantidad ( int newVar ) {
    cantidad = newVar;
  }

  /**
   * Get the value of cantidad
   * @return the value of cantidad
   */
  private int getCantidad ( ) {
    return cantidad;
  }

  /**
   * Set the value of color
   * @param newVar the new value of color
   */
  private void setColor ( int newVar ) {
    color = newVar;
  }

  /**
   * Get the value of color
   * @return the value of color
   */
  private int getColor ( ) {
    return color;
  }

  /**
   * Set the value of nombre
   * @param newVar the new value of nombre
   */
  private void setNombre ( String newVar ) {
    nombre = newVar;
  }

  /**
   * Get the value of nombre
   * @return the value of nombre
   */
  private String getNombre ( ) {
    return nombre;
  }

  /**
   * Set the value of activo
   * @param newVar the new value of activo
   */
  private void setActivo ( boolean newVar ) {
    activo = newVar;
  }

  /**
   * Get the value of activo
   * @return the value of activo
   */
  private boolean getActivo ( ) {
    return activo;
  }

  //
  // Other methods
  //

  /**
   */
  public void generar(  )
  {
  }


}

Tablero
import java.util.*;


/**
 * Class Tablero
 */
abstract public class Tablero {

  //
  // Fields
  //

  private int tamaño;
  private int color;
  
  //
  // Constructors
  //
  public Tablero () { };
  
  //
  // Methods
  //


  //
  // Accessor methods
  //

  /**
   * Set the value of tamaño
   * @param newVar the new value of tamaño
   */
  private void setTamaño ( int newVar ) {
    tamaño = newVar;
  }

  /**
   * Get the value of tamaño
   * @return the value of tamaño
   */
  private int getTamaño ( ) {
    return tamaño;
  }

  /**
   * Set the value of color
   * @param newVar the new value of color
   */
  private void setColor ( int newVar ) {
    color = newVar;
  }

  /**
   * Get the value of color
   * @return the value of color
   */
  private int getColor ( ) {
    return color;
  }

  //
  // Other methods
  //

  /**
   */
  public void iniciar(  )
  {
  }


  /**
   */
  public void empatar(  )
  {
  }


  /**
   */
  public void salir(  )
  {
  }


}


Pieza
import java.util.*;


/**
 * Class Pieza
 */
public class Pieza {

  //
  // Fields
  //

  protected boolean activa;
  protected int posicion;
  
  //
  // Constructors
  //
  public Pieza () { };
  
  //
  // Methods
  //


  //
  // Accessor methods
  //

  /**
   * Set the value of activa
   * @param newVar the new value of activa
   */
  protected void setActiva ( boolean newVar ) {
    activa = newVar;
  }

  /**
   * Get the value of activa
   * @return the value of activa
   */
  protected boolean getActiva ( ) {
    return activa;
  }

  /**
   * Set the value of posicion
   * @param newVar the new value of posicion
   */
  protected void setPosicion ( int newVar ) {
    posicion = newVar;
  }

  /**
   * Get the value of posicion
   * @return the value of posicion
   */
  protected int getPosicion ( ) {
    return posicion;
  }

  //
  // Other methods
  //

  /**
   */
  public void mover(  )
  {
  }


  /**
   */
  protected void capturar(  )
  {
  }


}


Reina
/**
 * Class Reina
 */
public class Reina extends Pieza{

  //
  // Fields
  //

  
  //
  // Constructors
  //
  public Reina () { };
  
  //
  // Methods
  //


  //
  // Accessor methods
  //

  //
  // Other methods
  //

  /**
   */
  public void mover(  )
  {
  }


}

Comparando mi código con el código autogenerado, se puede apreciar que es practicamente igual, en lo único que varía es que el código autogenerado utiliza métodos set y get.

Documentación

Clase Damas
/** 
* @author Julio Garcia
* @version 1.0
*/
import java.util.Scanner;

/** Clase principal */
public class Damas{

public static void main(String args []){
    Scanner lectura = new Scanner (System.in);
    System.out.print("Nombre del jugador: ");
    String nombre  = lectura.nextLine();  
    Tablero a1 = new Tablero ("negro");
    Equipo e1 = new Equipo ("roja",nombre,true);
    Equipo e2 = new Equipo ("blanca","Computadora",false);
    System.out.println();
    System.out.println("Jugador: "+e1.getnombre());   
    System.out.println();
    e1.generar();
    System.out.println();
    System.out.println("Jugador 2: "+e2.getnombre());
    System.out.println();
    e2.generar();
    System.out.println();
    System.out.println("Tablero\n");
    a1.iniciar();
}
}

Clase Equipo
/** Clase para generar el equipo */
public class Equipo {
    private int cantidad = 12;
    private String color;
    private String nombre;
    private boolean activo;

/**Constructor
 @param color indica el color de las piezas
 @param nombre indica el nombre del jugador
 @param activo indica si es el turno del jugador*/
public Equipo(String color, String nombre, boolean activo){
    this.color = color;
    this.nombre = nombre;
    this.activo = activo;
}

/** Genera las piezas del equipo */
public void generar(){
    int i;
    Pieza [] ficha;
    ficha = new Pieza [cantidad];
    for(i = 0; i < cantidad; i++){
 ficha [i] = new Pieza (true,color); 
 System.out.println("Ficha: "+(i+1)+" Color: "+color);
}

}


/**  Método para imprimir el nombre del jugador 
* @return nombre */
public String getnombre(){
return nombre;
}

}
Clase Pieza
/** Características de la Pieza */
public class Pieza{
    protected boolean activa;
    protected String color;

/** Constructor
    @param activa inidica si la pieza esta disponible
    @param color indica el color de la pieza*/
    public Pieza(boolean activa, String color){
 this.activa = activa;
        this.color = color; 
    }
/**  Método para el movimiento de la pieza hacia adelante*/
    public void mover(){
    }
/**  Método para eliminar una pieza */
    public void capturar(){
    }

} 

Clase Reina
/** Clase hija que hereda de la clase Pieza */
public class Reina extends Pieza{
/** Constructor 
*hereda los atributos de pieza
*/
    public Reina(boolean activa, String color){
    super (activa, color);
}

/**   Método que permite mover la pieza, ya sea avanzar o retroceder */
    public void mover(){

}
}
Clase Tablero
/** En está clase interactúan las demás clases*/
public class Tablero{
    private String color = "Rojo";

/**Constructor
  @param color indica el color del tablero
*/
public Tablero (String color){
    this.color = color;
  
}

/**  Método que se encarga de inicializar el juego*/
public void iniciar(){
   int [][] a = new int[8][8];
    int i, j;   
    for(i = 0; i < 3; i++){
 for(j = 0; j < 8; j++){
     if(i%2 == 0){
  if(j%2 != 0){
      a[i][j] = 1;
      System.out.print("*");
  }
  else {
      System.out.print(0);
  }
     }
      else { 
    if(j%2 == 0){
        a[i][j]= 1;
        System.out.print("*");
    }
    else {
        System.out.print(0);
    }
      }
 }
 System.out.println();
    }

    for (i = 3; i < 5; i++){
 for(j = 0; j < 8; j++){
 a[i][j]= 0;
 System.out.print(0);
 }
 System.out.println();
    }

   for(i = 5; i < 8; i++){
 for(j = 0; j < 8; j++){
     if(i%2 == 0){
  if(j%2 != 0){
      a[i][j] = 1;
      System.out.print("*");
  }
  else {
      System.out.print(0);
  }
     }
      else { 
    if(j%2 == 0){
        a[i][j]= 1;
        System.out.print("*");
    }
    else {
        System.out.print(0);
    }
      }
 }
 System.out.println();
    }


}

/**  Método para terminar el juego en empate*/
public void empatar(){

}

/**  Método para abandonar el juego*/
public void salir(){

}

}

Para generar la documentación nos ubicamos en la carpeta, ponemos lo siguiente



Nos generará la documentación en html



Para descargar la documentación

Herencia y Polimorfismo

Pieza
public class Pieza{
    protected boolean activa;
    protected String color;

/*Constructor*/
    public Pieza(boolean activa, String color){
        this.activa = activa;
        this.color = color;
    }

    public void mover(){
    }

    public void capturar(){
    }

}




Reina
public class Reina extends Pieza{

    public Reina(boolean activa, String color){
    super (activa, color);
}

    public void mover();
}

martes, 30 de agosto de 2011

Esqueleto de clases

Clase Tablero
public class Tablero{
    private int color;
    private int tamano;
}

/*Constructor*/
public Tablero (int color, int tamano){
    this.color = color;
    this.tamano = tamano;
}

public void iniciar(){
}

public void empatar(){
}

public void salir(){
}


Clase Pieza
public class Pieza{
    private boolean activa;
    private int coordenada;
}
/*Constructor*/
public Pieza (boolean activa, int coordenada){
    this.activa = activa;
    this.coordenada = coordenada;
}

public void mover(int x, int y){
return coordenada;
}

public void capturar (){
}


Clase Reina
public class Reina{
    private boolean activa;
    int coordenada;

}
/*Constructor*/
public Reina (boolean activa, int coordenada){
    this.activa = activa;
    this.coordenada = coordenada;
   
}

public int mover(int x, int y){
return coordenada;
}

public void capturar (){
}


Clase Equipo
public class Equipo {
    private int cantidad;
    private int color;
    private string nombre;
    private boolean activo;
}
/*Constructor*/
public Equipo(int cantidad, int color, string nombre, boolean activo){
    this.cantidad = cantidad;
    this.color = color;
    this.nombre = nombre;
    this.activo = activo;
}

public void generar(){
}

Ejemplo

Programa simple para convertir de grados celsius a kelvin y fahrenheit

public class Temperatura {
    private double grados;
    private double kelvin = 273.15; //atributos

//constructor
public Temperatura(double grados){
    this.grados = grados;
}

//método
public double convertirk(){
    grados+=kelvin;
    return grados;
}

//método
public double convertirf(){
    grados=(1.8)*(grados)+32;
    return grados;
}

public static void main (String args[]){   
    Temperatura o1 = new Temperatura(10.5);
    Temperatura o2 = new Temperatura (30);
    System.out.println("Conversión a Kelvin es: "+o1.convertirk());
    System.out.println("Conversión a Fahrenheit es: "+o2.convertirf());
}
}

 

lunes, 29 de agosto de 2011

Instalación de herramientas

Para desarrollar el proyecto utilizaré Ubuntu en su versión 11.04.



Para el proyecto, utilizare el lenguaje de programación orientado a objetos Java. Para poder crear herramientas en java es necesario instalar el JDK (Java Development Kit), el cual nos permitirá compilar.


Para descargarlo e instalarlo, en la terminal ponemos lo siguiente:

sudo apt-get install openjdk-6-jdk



Esperamos a que se descargue y se instale. Finalmente para comprobar que se ha instalado correctamente, en la terminal ponemos javac y si no nos marca error ya se encuentra instalado.

El editor de texto voy a utilizar es Emacs, uno de los mas populares.



Para instalarlo en la terminal ponemos lo siguiente:

sudo apt-get install emacs23



Esperamos a que se descargue y se instale, para verificar que se ha instalado correctamente, ponemos en la terminal emacs y se ejecutara el programa.




Una herramienta importante que nos ayudara en la creación de diagramas de clases y casos de uso es el Umbrello.



Para descargar e instalar el Umbrello ponemos en la terminal lo siguiente:

sudo apt-get install umbrello



Esperamos a que se descargue y se instale. Finalmente para verificar que se ha instalado correctamente, ponemos en la terminal umbrello y se ejecuta el programa



Referencias