Please enable / Bitte aktiviere JavaScript!
Veuillez activer / Por favor activa el Javascript![ ? ]
Este foro usa cookies
Este foro usa cookies para almacenar tu sesión de inicio si estás registrado, y de tu última visita si no lo estás. Las Cookies son un pequeños documento de texto almacenado en tu PC; las cookies de este foro sólo pueden ser usadas en el mismo y no suponen ninguna amenaza para tu seguridad. Estas Cookies también anotan los hilos que has leído y cuándo lo has hecho. Por favor, confirma si aceptas o declinas el uso de estas cookies.

Una cookie será almacenada en tu navegador a pesar de tu decisión para prevenir que este mensaje te vuelva a aparecer. Podrás cambiar la configuración de las cookies en cualquier momento siguiendo el enlace de la parte inferior.

Calificación:
  • 0 voto(s) - 0 Media
  • 1
  • 2
  • 3
  • 4
  • 5
Práctica 5
#1
Código PHP:
package p5;

public class 
Punto implements IForma {
    private 
double x,y;
    private 
int color;
    
    public 
Punto(){
        
this.setX(0);
        
this.setY(0);        
    }
    public 
Punto(double edouble i){
        
this.setX(e);
        
this.setY(i);        
    }
    public 
void setX(double e){
        
this.e;
    }
    public 
void setY(double i){
        
this.i;
    }
    public 
Punto clonar(){
        return new 
Punto(this.getX(),this.getY());
    }
    public 
String toString(){
        return 
"P[" getX()+", "getY()+"]";
    }

    @
Override
    
public double getX() {
        
// TODO Auto-generated method stub
        
return this.x;
    }

    @
Override
    
public double getY() {
        
// TODO Auto-generated method stub
        
return this.y;
    }

    @
Override
    
public double getOrientacion() {
        
// TODO Auto-generated method stub
        
return 0;
    }

    @
Override
    
public IForma girar(double gradosdouble xdouble y) {
        
double angulo Math.toRadians(grados);
 
       double x1 x+Math.cos(angulo)*(this.x-x)-Math.sin(angulo)*(this.y-y);
 
       double y1 y+Math.sin(angulo)*(this.x-x)+Math.cos(angulo)*(this.y-y);
 
       return new Punto (x1y1);
    }

    @
Override
    
public IForma girar(double grados) {
        
// TODO Auto-generated method stub
        
return this.clonar();
    }

    @
Override
    
public IForma trasladar(double deltaXdouble deltaY) {
        return new 
Punto (this.x+deltaX,this.y+deltaY);
    }

    @
Override
    
public double distancia(double xdouble y) {
        
// TODO Auto-generated method stub
        
return 0;
    }

    @
Override
    
public IForma escalar(double k) {
        
// TODO Auto-generated method stub
        
return null;
    }

    @
Override
    
public void setColor(int code) {
        
color code;        
    }

    @
Override
    
public int getColor() {
        return 
this.color;
    }
    



Código PHP:
package p5;

public class 
TrianguloEquilatero implements IPoligonoRegularIForma {
    private 
Punto p1,p2,p3;
    private 
double y;
    private 
int color;

    public 
TrianguloEquilatero() {
        
double y1 50*Math.tan(Math.toRadians(30));
        
p1 = new Punto (0,y1);
        
p2 = (Puntop1.girar(120,0,0);
        
p3 = (Puntop2.girar(120,0,0);
    }
    public 
TrianguloEquilatero(double lado){
        
double y1 lado*Math.tan(Math.toRadians(30));
 
       p1 = new Punto (0,y1);
 
       p2 = (Puntop1.girar(120,0,0);
 
       p3 = (Puntop2.girar(120,0,0);    
    }

    public 
Punto[] getVertices() {
 
       Punto vertices [] = {p1,p2,p3};
 
       return vertices;
 
   }

 
   public double getLado() {
 
       return p1.distancia(p2.getX(), p2.getY());
 
   }

 
   public void orientar(Vector v) {
 
       double orientacion v.getOrientacion()-getOrientacion();
 
       girar(orientacion,getCentro());
 
   }

 
   public void girar(double gradosPunto cdg) {
 
       p1 = (Puntop1.girar(gradoscdg.getX(), cdg.getY());
 
       p2 = (Puntop2.girar(gradoscdg.getX(), cdg.getY());
 
       p3 = (Puntop3.girar(gradoscdg.getX(), cdg.getY());
 
   }


 
   public void trasladar(Vector v) {
 
       p1 = (Puntop1.trasladar(v.getCompX(), v.getCompY());
 
       p2 = (Puntop2.trasladar(v.getCompX(), v.getCompY());
 
       p3 = (Puntop3.trasladar(v.getCompX(), v.getCompY());
 
   }

 
   public Punto getCentro() {
 
       double x p1.getX()+p2.getX()+p3.getX();
 
       double y p1.getY()+p2.getY()+p3.getY();
 
       return new Punto (x/3,y/3);
 
   }

 
   public Vector getUnitario() {
 
       Vector a = new Vector (getCentro(),p1);
 
       return new Vector (getCentro(),1,a.getOrientacion());
 
   }

 
   public double getArea() {  
        double h 
getLado()*Math.sin(Math.PI/3);
 
       return getLado()*h/2;
 
   }

 
   public double getPerimetro() {
 
       return 3*getLado();
 
   }

 
   public void reset() {
 
       Vector trasladar = new Vector (getCentro(),new Punto());
 
       trasladar(trasladar);
 
   }

 
   public double getX() {
 
       return getCentro().getX();
 
   }

 
   public double getY() {
 
       return getCentro().getY();
 
   }

 
   public double getOrientacion() {
 
       return getUnitario().getOrientacion();
 
   }

 
   public IForma girar(double gradosdouble xdouble y) {
 
       p1 = (Puntop1.girar(grados,x,y);
 
       p2 = (Puntop2.girar(grados,x,y);
 
       p3 = (Puntop3.girar(grados,x,y);
 
       return this;
 
   }

 
   public IForma girar(double grados) {
 
       double x getX();
 
       double y getY();
 
       p1 = (Puntop1.girar(grados,x,y);
 
       p2 = (Puntop2.girar(grados,x,y);
 
       p3 = (Puntop3.girar(grados,x,y);
 
       return this;
 
   }

 
   public IForma trasladar(double deltaXdouble deltaY) {
 
       p1 = (Puntop1.trasladar(deltaXdeltaY);
 
       p2 = (Puntop2.trasladar(deltaXdeltaY);
 
       p3 = (Puntop3.trasladar(deltaXdeltaY);
 
       return this;
 
   }

 
   public double distancia(double xdouble y) {
 
       return getCentro().distancia(xy);
 
   }

 
   public IForma escalar(double k) {
 
       Punto centro getCentro();
 
       Vector a = (Vector) new Vector (centro,p1).escalar(k);
 
       p1 a.getExtremo();
 
       p2 = (Puntop1.girar(120,centro.getX(),centro.getY());
 
       p3 = (Puntop2.girar(120,centro.getX(),centro.getY());
 
       return this;
 
   }

 
   public void setColor(int code) {
 
       color code;
 
   }

 
   public int getColor() {
 
       return color;
 
   }

 
   public String toString (){
 
       return "Triángulo --> C:P[" +getX()+ ", " +getY()+ "], L:" +getLado()+ 
 
               ", P[" p1.getX() +", " +p1.getY()+ "], P[" +p2.getX()+ ", " +p2.getY()+ 
 
               "], P[" +p3.getX()+ ", " +p3.getY()+ "], theta = "+getOrientacion(); 
 
   }


Código PHP:
package p5;

public class 
Vector implements IForma {
    private 
Punto o,e;
    private 
double modang;
    private final static 
Punto defecto = new Punto(0,0);
    private 
int color;

    public 
Vector() {
        
= new Punto(0,0);
        
= new Punto(1,0);
        
//mod=1;
        
ang=0;
    }
    public 
Vector(double fdouble i){
        
= new Punto(0,0);
        
= new Punto(f,i);
        
//mod=Math.sqrt((f*f)+(i*i));
        
ang=Math.toRadians(Math.atan(i/f));
    }
    public 
Vector(Punto a){
        
= new Punto(0,0);
        
a.clonar();
        
//mod=Math.sqrt((a.getX()*a.getX())+(a.getY()*a.getY()));
        
ang=Math.toRadians(Math.atan(a.getY()/a.getX()));
    }
    public 
Vector(Punto aPunto b){
        
a.clonar();
        
b.clonar();
        
//mod=Math.sqrt(Math.pow((b.getX()-a.getX()),2)+(Math.pow((b.getY()-a.getY()), 2)));
        
ang=Math.toRadians(Math.atan((b.getY()-a.getY())/(b.getX()-a.getX())));
    }
    public 
Vector(Punto adouble bdouble c){
        
mod b;
        
ang =Math.toRadians(c);
        
a.clonar();
        
= new Punto((a.getX()+Math.cos(ang)*mod),a.getY()+(Math.sin(ang)*mod));        
    }
    public 
Vector clonar(){
        return new 
Vector(this.o,this.e);
    }
    public 
String toString(){
        
String h = ("Vector O: P["+o.getX() +","+o.getY()+"] E["+e.getX()+","+e.getY()+"] |v|="+mod+", ang = "+ang);
        return 
h;
    }
    public 
double getCompX(){
        return 
e.getX()-o.getX();
    }
    public 
double getCompY(){
        return 
e.getY()-o.getY();
    }
    public 
Punto getPuntoAplicacion(){
        return 
o;
    }
    public 
Punto getExtremo(){
        return 
e;
    }
    public 
double modulo(){
        return 
Math.sqrt(getCompX()*getCompX()+getCompY()*getCompY());
    }
    public 
Vector getUnitario(){
        return new 
Vector(this.o,1,this.ang);        
    }
    public static 
Vector getUnitario(double gr){
        return new 
Vector(defecto,1,gr);    
    }

    @
Override
    
public double getX() {
        return 
o.getX();
    }

    @
Override
    
public double getY() {
        return 
o.getY();
    }

    @
Override
    
public double getOrientacion() {
        return 
Math.toDegrees(Math.atan2(getCompY(),getCompX()));
    }

    @
Override
    
public IForma girar(double gradosdouble xdouble y) {
        
Punto o = (Puntothis.o.girar(grados,x,y);
        
Punto e = (Puntothis.e.girar(grados,x,y);
        return new 
Vector (o,e);
    }

    @
Override
    
public IForma girar(double grados) {
        return new 
Vector(o,(Puntoe.girar(grados,o.getX(),o.getY()));
    }

    @
Override
    
public IForma trasladar(double deltaXdouble deltaY) {
        return new 
Vector(new Punto (o.getX()+deltaXo.getY()+deltaY),new Punto (e.getX()+deltaXe.getY()+deltaY));
    }

    @
Override
    
public double distancia(double xdouble y) {
        return 
o.distancia(xy);
    }

    @
Override
    
public IForma escalar(double k) {
        return new 
Vector (omodulo()*k,getOrientacion());
    }

    @
Override
    
public void setColor(int code) {
        
color=code;
    }

    @
Override
    
public int getColor() {
        return 
color;
    }


"Que yo sepa, el español medio no es más honrado que los políticos que lo gobiernan" Cool
Responder
#2
Aquí las interfaces proporcionadas por el profesor y usadas en la clases que hay que implementar:
Código PHP:
/**
 * 
 */
package p5;

/**
 * Modela un objeto geométrico que está situado en una posición de un espacio de dos 
 * dimensiones con  una orientación dada y que puede ser trasladado y girado 
 * respecto de un centro de giro. 
 * 
 * @author LSI
 *
 */
public interface IForma {
    
    
/**
     * Devuelve coordenada x del objeto
     * @return coordenada x del objeto
     */
    
public double getX();
    
    
    
/**
     * Devuelve coordenada y del objeto
     * @return coordenada y del objeto
     */
    
public double getY();
    
    
    
/**
     * Devuelve el ángulo que forma el objeto con el eje X.
     * @return ángulo que forma el objeto con el eje X.
     */
    
public double getOrientacion();
    
    
    
/**
     * Giro del objeto respecto de un punto.
     * @param grados del giro
     * @param x coordenada x del centro de giro.
     * @param y coordenada y del centro de giro
     * @return referencia a la forma girada. 
     *         La clase debe definir si el método
     *         gira al objeto receptor del mensaje o se crea un nuevo objeto resultado
     *         de girar al receptor.
     */
    
public IForma girar(double gradosdouble xdouble y);
    
    
    
/**
     * Giro del objeto respecto de sí mismo (punto definido por getX y getY).
     * @param grados grados de giro.
     */
    
public IForma girar(double grados);

    
/**
     * Traslación del objeto.
     * @param deltaX traslación en X
     * @param deltaY traslación en Y
     * @return referencia a la forma girada.
     *         La clase debe definir si el método
     *         traslada al objeto receptor del mensaje o se crea un nuevo objeto resultado
     *         de trasladar al receptor.
     */
    
public IForma trasladar(double deltaXdouble deltaY);
    
    
/**
     * Devuelve la distancia del objeto al punto definido por las coordenadas x e y
     * @param x coordenada x del punto respecto del cual se calcula la distancia.
     * @param y coordenada y del punto respecto del cual se calcula la distancia.
     * @return distancia del objeto al punto definido por las coordenadas x e y.
     */
    
public double distancia(double xdouble y);
    
    
    
/**
     * Escala el objeto en un factor k, manteniendo la posición de su centro geométrico.
     * @param k factor de escala.
     * @return referencia a la forma escalada.
     *         La clase debe definir si el método
     *         escala al objeto receptor del mensaje o se crea un nuevo objeto resultado
     *         de escalar al receptor.
     */
    
public IForma escalar(double k);

    
    
/**
     * Fija un código que sirve para determinar el color de la figura.
     * La interprestación del código depende del cliente.
     * 
     * @param code código 
     * 
     */
    
public void setColor(int code);
    
    
/**
     * Devuelve el código de color del objeto.
     * @return Código de color.
     */
    
public int getColor();
    


Código PHP:
package p5;

/**
 * Modela un polígono regular a partir de sus vértices
 * @author LSI
 *
 */
public interface IPoligonoRegular {
    
    
/**
     * Devuelve los vértices del polígono, en orden consecutivo.
     * @return vértices del polígono, en orden consecutivo.
     */
    
public Punto [] getVertices();
    
    
    
/**
     * Devuelve el lado del polígono.
     * @return lado del polígono
     */
    
public double getLado();
            
    
/**
     * Orienta al polígono según el vector v
     * Es decir, gira al poligono sobre su centro de tal forma
     * que queda orientado respecto del eje x como el 
     * vector que se pasa como argumento.
     * @param v vector de orientación
     */
    
public void orientar(Vector v);
    
    
/**
     * Gira al polígono respecto un centro de giro
     * @param grados grados del giro
     * @param cdg centro de giro
     */
    
public void girar(double gradosPunto cdg);
    
    
/**
     * Traslada al polígono según un vector de traslación.
     * @param v vector de traslación.
     */
    
public void trasladar(Vector v);
    
    
    
/**
     * Devuelve un punto cuya posición es el centro geométrico de
     * del poligono.
     * 
     * @return     punto cuya posición es la del centro geométrico de
     *             del polígono.
     */
    
public Punto getCentro();
    
    
    
/**
     * Devuelve un vector con la orientación del polígono.
     * @return vector orientación del polígono.
     */
    
public Vector getUnitario();
    
    
    
/**
     * Área del polígono.
     * @return área del polígono.
     */
    
public double getArea();
    
    
    
/**
     * Perímetro del polígono.
     * @return perímetro del polígono.
     */
    
public double getPerimetro();
    
    
    
/**
     * Coloca el objeto en la posición (0,0) con orientación según vector unitario j.
     */
    
public void reset();
    

"Que yo sepa, el español medio no es más honrado que los políticos que lo gobiernan" Cool
Responder
#3
Y aquí las clases proporcionadas por el profesor para comprobar el correcto funcionamiento de la práctica:

Código PHP:
package p5;

/**
 * Gestiona formas geométricas que implementan la
 * interfaz IMovible.
 * 
 * @author Juan Ángel
 *
 */

public class GestorFormas {
 
   
    
/**
     * Identificadores de tipos de formas de objetos.
     */
 
   public static final int FPrimeraForma   1;
 
   public static final int FPunto            1;
 
   public static final int FVector            2;
 
   public static final int FTriangulo        3;
 
   public static final int FCualquiera        4;
 
   public static final int FUltimaForma    4;

 
   /**
     * Tamaños predeterminados
     */
 
   public static final int Tiny      1;
 
   public static final int Small     2;
 
   public static final int Medium     3;
 
   public static final int Large     4;
 
   public static final int KingSize  5;
 
   
    
/**
     * Máximo de objetos permitidos en el gestor.
     */
 
   public static final int MaxFormas 18;
 
   public static final int LimiteFormasAlcanzado = -1;
 
   public static final int ArgumntoNulo = -2;

 
   
    private  IForma 
[] misFormas = new IForma[MaxFormas];
 
   private  int nroFormas 0;
 
   
    
/**
     * Añade un objeto al gestor si no se excede el máximo de objetos permitidos.
     * Cuando un objeto se añade al gestor decimos que está registrado en el gestor.
     * 
     * @param obj objeto añadido. obj debe ser distinto de null y no estar ya añadido.
     * @return número de objetos registrados contando con el añadido, 
     *         -1 si no se ha podido añadir la forma.        
     */
 
   public int aniadirForma(IForma obj){
 
       if (obj==null)
 
           return -1;
 
       int count 0;
 
       for (int i=0i<misFormas.lengthi++){
 
           if (misFormas[i]!=null)
 
               count++;
 
       }
 
       if (count == MaxFormas)
 
           return -1;
 
       IForma [] misFormashechas = new IForma[count+1];
 
       count 0;
 
       for (int i=0i<misFormas.lengthi++){
 
           if (misFormas[i]!=null){
 
               misFormashechas[count++]=misFormas[i];
 
           }
 
           if (misFormas[i]==obj)
 
               return -1;
 
       }
 
       misFormashechas[count]=obj;
 
       misFormas misFormashechas;
 
       return ++nroFormas;
 
   }
 
   
    
/**
     * Elimina todos los objetos del gestor.
     */
 
   public void resetFormas(){
 
       misFormas = new IForma[0];
 
       nroFormas 0;
 
   }
 
   
    
    
/**
     * Devuelve array con todos los objetos registrados en el gestor.
     * @return array con todos los objetos registrados en el gestor.
     */
 
   public IForma [] getFormas (){
 
       IForma[] misFormashechas = new IForma[misFormas.length];
 
       for (int i=0i<misFormashechas.lengthi++)
 
           misFormashechas[i] = misFormas[i];
 
       return misFormashechas;
 
   }
 
   
    
/**
     * Devuelve array con todos los puntos registrados en el gestor.
     * @return array con todos los puntos registrados en el gestor.
     */ 
   
    public Punto 
[] getPuntos(){
 
       int count 0;
 
       for (int i=0i<misFormas.lengthi++)
 
           if (misFormas[i] instanceof Punto)
 
               count++;
 
       Punto [] misPuntos = new Punto [count];
 
       count 0;
 
       for (int i=0i<misFormas.lengthi++){
 
           if (misFormas[i] instanceof Punto){
 
               misPuntos[count] = (PuntomisFormas[i];
 
               count++;
 
           }
 
       }
 
       return misPuntos;
 
   }
 
   
    
/**
     * Devuelve array con todos los vectores registrados en el gestor.
     * @return array con todos los vectores registrados en el gestor.
     */
 
   public Vector [] getVectores(){
 
       int count 0;
 
       for (int i=0i<misFormas.lengthi++)
 
           if (misFormas[i] instanceof Vector)
 
               count++;
 
       Vector [] misVectores = new Vector [count];
 
       count 0;
 
       for (int i=0i<misFormas.lengthi++){
 
           if (misFormas[i] instanceof Vector)
 
               misVectores[count++] = (VectormisFormas[i];
 
       }
 
       return misVectores;
 
   }
 
   
    
/**
     * Devuelve array con todos los triángulos registrados en el gestor.
     * @return array con todos los triángulos registrados en el gestor.
     */
 
   public TrianguloEquilatero [] getTriangulos(){
 
       int count 0;
 
       for (int i=0i<misFormas.lengthi++)
 
           if (misFormas[i] instanceof TrianguloEquilatero)
 
               count++;
 
       TrianguloEquilatero [] misTriangulos = new TrianguloEquilatero [count];
 
       count 0;
 
       for (int i=0i<misFormas.lengthi++){
 
           if (misFormas[i] instanceof TrianguloEquilatero)
 
               misTriangulos[count++] = (TrianguloEquilateromisFormas[i];
 
       }
 
       return misTriangulos;
 
   }
 
   
    
    
    
/**
     * Mueve el objeto obj al punto especificado.
     * Coloca el centro del objeto en el punto destino y lo 
     * orienta respecto del eje X según un determinado ángulo.
     * 
     * Si el objeto no está registrado no hace nada.
     * 
     * @param obj objeto a mover
     * @param destino punto destino del objeto.
     * @param orientacion angulo en grados de la figura con el eje X 
     */
 
   public void moverA(IForma objPunto destinodouble orientacion){
 
       if (obj instanceof Punto)
 
           obj destino;
 
       if (obj instanceof Vector)
 
           obj = new Vector (destino, ((Vectorobj).modulo(), orientacion);
 
       if (obj instanceof TrianguloEquilatero){
 
           TrianguloEquilatero a = (TrianguloEquilateroobj;
 
           Vector traslada = new Vector (a.getCentro(),destino);
 
           Vector orienta = new Vector (new Punto(),1,orientacion);
 
           a.trasladar(traslada);
 
           a.orientar(orienta);
 
       }
 
   }
 
   
    
/**
     * Mueve todas las formas de un cierto tipo a un punto determinado.
     * Coloca todos los centros de las figuras en el punto destino y
     * las orienta de igual forma respecto del eje X.
     * 
     * @param tipoForma tipo de las formas a agrupar.
     * @param destino punto de agrupamiento.
     * @param orientacion angulo en grados de la figura con el eje X 
     */
 
   public void agruparFormas(int tipoFormaPunto destinodouble orientacion){
 
       if (tipoForma == FPunto){
 
           for (int i=0i<getPuntos().lengthi++)
 
               moverA(getVectores()[i],destino,orientacion);
 
       }
 
       if (tipoForma == FVector){
 
           for (int i=0i<getVectores().lengthi++)
 
               moverA(getVectores()[i],destino,orientacion);
 
       }
 
       if (tipoForma == FTriangulo){
 
           for (int i=0i<getTriangulos().lengthi++){
 
               moverA(getTriangulos()[i],destino,orientacion);
 
           }
 
       }
 
   }

 
   
    
/**
     * Devuelve una forma de un cierto tipo y tamaño colocada en el
     * origen de coordenadas y orientada según eje Y.
     * 
     * @param formaId Tipo de forma solicitada.
     * @param size tamaño según tamaños predefinidos en la clase.
     * 
     * @return forma generada.
     */
 
   public static IForma getForma(int formaIdint size){
 
       if (formaId == FPunto)
 
           return new Punto();
 
       if (formaId == FVector){
 
           if (size == Tiny)
 
               return new Vector (new Punto(),10,90);
 
           if (size == Small)
 
               return new Vector (new Punto(),20,90);
 
           if (size == Medium)
 
               return new Vector (new Punto(),30,90);
 
           if (size == Large)
 
               return new Vector (new Punto(),40,90);
 
           if (size == KingSize)
 
               return new Vector (new Punto(),50,90);
 
       }
 
       if (formaId == FTriangulo){
 
           if (size == Tiny)
 
               return new TrianguloEquilatero (10);
 
           if (size == Small)
 
               return new TrianguloEquilatero (20);
 
           if (size == Medium)
 
               return new TrianguloEquilatero (30);
 
           if (size == Large)
 
               return new TrianguloEquilatero (40);
 
           if (size == KingSize)
 
               return new TrianguloEquilatero (50);
 
       }
 
       return null;
 
   }


Código PHP:
package p5;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Polygon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DecimalFormat;


public class 
TestGestorFormas extends JFrame implements ActionListener {

    
/**
     * 
     */
    
private static final long serialVersionUID 1L;

    
/*******************************************************************************
     *  Model elements
     */

    
private GestorFormas miGestor = new GestorFormas();

    
// Meeting points.
    
public static final Punto Origin = new Punto(0,0);
    public static 
Vector V1 = new Vector(new Punto(150150), new Punto(160160)).getUnitario();
    public static 
Vector V2 = new Vector(new Punto(150, -150), new Punto(160, -160)).getUnitario();
    public static 
Vector V3 = new Vector(new Punto(-150, -150), new Punto(-160, -160)).getUnitario();
    public static 
Vector V4 = new Vector(-150150).getUnitario();

    
// Predefined forms
    
    
private  Punto [] puntos;
    private 
 IForma [] triangulos;
    private 
 IForma [] vectores;
    
    

    
Punto pos = new Punto();
    
Vector orientacion = new Vector();

    private 
boolean rgPtorgTrirgVec;

    
// Color codes.
    
Color [] colors = {Color.DARK_GRAYColor.blackColor.blueColor.red};
    
int colorIndex 0;

    
DecimalFormat form = new DecimalFormat();


    
/*******************************************************************************
     *  Graphical elements
     */

    
JMenuBar menuBar;

    
// Figure selection menu
    
JMenu menuFigs
    
JMenuItem itCrearPuntositCrearTriangulositListar;


    
JMenu menuOperaciones;

    
// Rotation center entries
    
JMenuItem itDistanciasitAgruparTriangulositAreasPerimetros;

    
// Reset Panel
    
JButton btReset;

    
// Drawing area
    
private Lienzo lienzo;


    public 
TestGestorFormas(){

        
super("Práctica 3. Test Gestor Formas");

        
form.setMaximumFractionDigits(2);

        
// Create and arrange application menus, controls and panels
        
buildMenus();
        
lienzo = new Lienzo();


        
// Event subscription. Window handles all events.
        // Event sources have been instantiated in buildMenus.
        // This code can be moved there.

        // Form creation
        
itCrearPuntos.addActionListener(this);
        
itCrearTriangulos.addActionListener(this);
        
itListar.addActionListener(this);


        
// Operations
        
itDistancias.addActionListener(this);
        
itAgruparTriangulos.addActionListener(this);
        
itAreasPerimetros.addActionListener(this);

        
// Debug trace activation
        
btReset.addActionListener(this);


        
// Window layout.
        
getContentPane().add(lienzo);

        
// Window arrangements.
        
setSize (540,650);
        
setVisible(true);  
        validate
();
        
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

    }

    public 
void actionPerformed(ActionEvent ae){

        
int signo 1;

        if (
ae.getSource() == btReset){
            
System.out.println("btReset clicked.");

            
rgPto rgTri rgVec false;
            
triangulos vectores null;

            
miGestor.resetFormas();
            
lienzo.updateForma();

            
System.out.println("-------------------------------------------------------");
            
System.out.println();
            return;
        }

        
// Form Selection
        
if (ae.getSource() == itCrearPuntos){
            
System.out.println("itCrearPuntos: Obteniendo y dibujando Puntos...");

            if (!
rgPto){

                
Punto p = new Punto(100100);
                
p.setColor(colorIndex);
                
miGestor.aniadirForma(p);
                
System.out.println("Punto creado en: " " y añadido a gestor de formas.");

                
= new Punto(-10050);
                
p.girar(20);
                
p.setColor(colorIndex);
                
miGestor.aniadirForma(p);
                
System.out.println("Punto creado en: " " y añadido a gestor de formas.");


                
= new Punto(-5050);
                
p.girar(-60);
                
p.setColor(colorIndex);
                
miGestor.aniadirForma(p);
                
System.out.println("Punto creado en: " " y añadido a gestor de formas.");

                
colorIndex = (colorIndex+1)%colors.length;

                
rgPto true;
            }

            
puntos miGestor.getPuntos();
            
lienzo.updateForma();

            
System.out.println("-------------------------------------------------------");
            
System.out.println();

            return;
        }


        if (
ae.getSource() == itCrearTriangulos){
            
System.out.println("itCrearTriangulos: Obteniendo y dibujando triángulos...");

            if (!
rgTri){

                
System.out.println("registrarFormas: Creando y registrando triángulos...");

                
TrianguloEquilatero tr null;
                for(
int i 03i++){
                    
tr = new TrianguloEquilatero(30 * (i+1));
                    
tr.trasladar(new Vector((-signo) * 60 i, (-signo) * 40));
                    
tr.girar(45 * (i+1));
                    
tr.setColor(colorIndex);
                    
miGestor.aniadirForma(tr);
                    
colorIndex = (colorIndex+1)%colors.length;
                    
signo = -signo;

                    
System.out.println("Triángulo creado en: " tr.getCentro());
                }        
                
rgTri true;
            }

            
triangulos miGestor.getTriangulos();
            
lienzo.updateForma();

            
lienzo.updateForma();

            
System.out.println("-------------------------------------------------------");
            
System.out.println();

            return;
        }

        if (
ae.getSource() == itListar){

            
System.out.println("itListar: Lista de figuras registradas ...");


            
IForma misFormas [] =  miGestor.getFormas();

            for (
int i 0misFormas.lengthi++){
                
System.out.println(misFormas[i]);
            }
            
System.out.println("-------------------------------------------------------");
            
System.out.println();

            return;
        }    

        if (
ae.getSource() == itAreasPerimetros){

            
System.out.println("itAreasPerimetros: Lista áreas y perímetros de figuras registradas ...");


            
IForma misFormas [] =  miGestor.getFormas();

            for (
int i 0misFormas.lengthi++){
                if (
misFormas[i] instanceof IPoligonoRegular){
                    
IPoligonoRegular f = (IPoligonoRegularmisFormas[i];
                    
System.out.println("Forma ("misFormas[i].getClass() +")" " Área = " form.format(f.getArea()) + " perímetro = " form.format(f.getPerimetro()));
                }
                else{
                    
System.out.println("Forma (" misFormas[i].getClass() + ") " " no tiene definida ni área ni perímetro.");
                }
            }

            
System.out.println("-------------------------------------------------------");
            
System.out.println();

            return;
        }    


        if (
ae.getSource() == itDistancias){

            
System.out.println("Calculando distancias ... ");


            
IForma [] misFormas miGestor.getFormas();    

            for (
int i 0misFormas.length-1i++){
                
System.out.println("Distancia forma " " a: ");
                
Punto p1 = new Punto(misFormas[i].getX(), misFormas[i].getY());
                for(
int j i+1misFormas.lengthj++){
                    
Punto p2 = new Punto(misFormas[j].getX(), misFormas[j].getY());
                    
System.out.println("Forma " " = " p1.distancia(p2.getX(), p2.getY()));
                }
                
System.out.println();
            }
            
System.out.println("-------------------------------------------------------");
            
System.out.println();

            return;
        }        


        if (
ae.getSource() == itAgruparTriangulos){

            
System.out.println("Agrupando triángulos en pC ... ");

            
miGestor.agruparFormas(GestorFormas.FTrianguloV3.getPuntoAplicacion(), V3.getOrientacion());
            
lienzo.updateForma();

            
System.out.println("-------------------------------------------------------");
            
System.out.println();

            return;
        }    
    }


    private 
void buildMenus(){

        
menuBar = new JMenuBar();

        
// Figure creation menu
        
menuFigs = new JMenu("Dibujar Figuras");

        
itCrearPuntos = new JMenuItem("Dibujar Puntos");
        
itCrearTriangulos = new JMenuItem("Dibujar Triángulos"); 
        
itListar = new JMenuItem("Listar en consola"); 
        
itAreasPerimetros = new JMenuItem("Listar áreas en consola"); 

        
menuBar.add(menuFigs);

        
menuFigs.add(itCrearPuntos);
        
menuFigs.add(itCrearTriangulos);
        
menuFigs.add(itListar);
        
menuFigs.add(itAreasPerimetros);


        
// Operations menu
        
menuOperaciones = new JMenu("Operaciones");

        
itDistancias               = new JMenuItem("Calcular distancias");
        
itAgruparTriangulos       = new JMenuItem("Agrupar triángulos");

        
menuBar.add(menuOperaciones);

        
menuOperaciones.add(itDistancias);
        
menuOperaciones.add(itAgruparTriangulos);

        
// Debug buttons

        
btReset = new JButton("Reset");
        
menuBar.add(btReset);

        
setJMenuBar(menuBar);
    }


    public static 
void main(String[] args) {
        new 
TestGestorFormas();

    }


    public class 
Lienzo extends JPanel{

        private static final 
long serialVersionUID 1L;
        
IForma forma null;
        
boolean debug true;
        
boolean updated false;

        
Color colorPincel Color.white;

        
int LxLyOxOy;
        
int margen 20;
        
int longEjes 100;
        
int anchoPunto 4;

        public 
void debugOn(){
            
debug true;
            
System.out.println("Lienzo: Trace ON");
        }

        public 
void debugOff(){
            
debug false;
            
System.out.println("Lienzo: Trace OFF");
        }

        public 
void setForma(IForma ob){
            if (
ob != null){
                
forma ob;
                
repaint();
            }
            else if (
debug){
                
System.out.println("Lienzo: Error --> setForma(null)");                
            }
        }

        public 
void updateForma(){
            
updated false;
            
repaint();
        }

        public 
Lienzo(){
            
setBorder(BorderFactory.createLineBorder(Color.GREEN));
            
setBackground(Color.white);
        }

        public 
void setColor(Color c){
            
colorPincel c;
        }

        public 
void paintComponent(Graphics g){

            
super.paintComponent(g);

            
g.setColor(Color.black);

            
// Drawing canvas edges
            
Dimension dim this.getSize();
            
Lx dim.width margen;
            
Ly dim.height margen;
            
Ox dim.width 2;
            
Oy dim.height dim.height/2;
            
g.drawLine(Ox longEjesOyOx longEjesOy);            
            
g.drawLine(OxOy longEjesOxOy longEjes);
            
g.drawRect(1010LxLy);

            
// Drawing rotation points
            
            
dibujarVector(V1"v1"g);
            
dibujarVector(V2"v2"g);
            
dibujarVector(V3"v3"g);
            
dibujarVector(V4"v4"g);
            

            
IForma [] misFormas miGestor.getFormas();

            if (
misFormas != null){
                for (
int i 0misFormas.lengthi++){
                    
dibujarForma(misFormas[i], "f_" g);
                }
            }
            
updated true;
        }

        public 
void dibujarForma(IForma formaString idGraphics g){
            if (
forma == null){
                return;
            }

            if (
forma instanceof Punto){
                
dibujarPunto((Punto)formaidg);
            }
            if (
forma instanceof Vector){
                
dibujarVector((Vector)formaidg);
            }
            else if (
forma instanceof IPoligonoRegular){
                
dibujarPoligono((IPoligonoRegular)formaidg);
            }        
        }


        
        public 
void dibujarVector(Vector vtrString idGraphics g){

            
Color c g.getColor();
            
g.setColor(colors[vtr.getColor()]);

            
Punto p vtr.getPuntoAplicacion();

            
int x1 = (int)p.getX();
            
int y1 = (int)p.getY();
            
            
int x2 x1 + (int)(vtr.getCompX() * 30);
            
int y2 y1 + (int)(vtr.getCompY() * 30);

            
int ax x2 - (int)(vtr.getUnitario().getCompX() * 15);
            
int ay y2 - (int)(vtr.getUnitario().getCompY() * 15);

            
double tetha vtr.getUnitario().getOrientacion() * Math.PI 180.0;
            
            
            
int bx ax - (int)(10 Math.cos((Math.PI/2) - tetha));
            
int by ay + (int)(10 Math.sin((Math.PI/2) - tetha));
            
int cx ax + (int)(10 Math.cos((Math.PI/2) - tetha));
            
int cy ay - (int)(10 Math.sin((Math.PI/2) - tetha));

            
g.drawLine(Ox x1Oy y1Ox x2Oy y2);

            
g.drawLine(Ox x2Oy y2Ox bxOy by);
            
g.drawLine(Ox x2Oy y2Ox cxOy cy);
            
            
g.drawString(idOx + (int)p.getX() + 10Oy - (int)p.getY() + 10);

            
g.setColor(c);    
        }


        public 
void dibujarPunto(Punto pString idGraphics g){

            
g.setColor(colors[p.getColor()]);
            
g.fillOval(Ox + (int)((p.getX() - anchoPunto)), 
                    
Oy - (int)((p.getY() + anchoPunto)), 
                    
anchoPunto 2anchoPunto 2);

            
g.drawString(idOx + (int)p.getX() + 10Oy - (int)p.getY() + 10);

            
Color color g.getColor();
            
colorPincel Color.GREEN;
            
colorPincel color;            
        }



        public 
void dibujarPoligono(IPoligonoRegular prString idGraphics g){

            if (!(
pr instanceof IPoligonoRegular)){
                return;
            }

            
IPoligonoRegular pr1 = (IPoligonoRegularpr;

            
g.setColor(colors[((IForma)pr).getColor()]);

            
Punto pto [] = pr1.getVertices();

            
int xC [] = new int[pto.length];
            
int yC [] = new int[pto.length];

            for (
int i 0pto.lengthi++){
                
xC[i] = (int) pto[i].getX() + Ox;
                
yC[i] = Oy - (int) pto[i].getY();
            }

            
Polygon pol = new Polygon(xCyCxC.length);
        
            
dibujarPunto(pr.getCentro(), idg);

            
g.drawPolygon(pol);

        }    
    }
    
        
        
    
/*
    private String toCoords(double x, double y){
        return "[" + x + ", " + y + "]";
    }
    */


Código PHP:
package p5;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.Polygon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DecimalFormat;

public class 
TestMovimientos extends JFrame implements ActionListener {

    private static final 
long serialVersionUID 1L;

    
/*******************************************************************************
     *  Model elements
     */

    // Translation modes:
    
public static final int PuntosCardinales 1;
    public static final 
int EjeFigura        2;

    
// Rotation modes:
    
public static final int CentroExterno 1;
    public static final 
int CentroDeMasas 2;

    
// Vectores de traslación según ejes x e y
    
public static final Vector I = new Vector(10);
    public static final 
Vector MenosI = new Vector(-10);
    public static final 
Vector J = new Vector(01);
    public static final 
Vector MenosJ = new Vector(0, -1);    

    
// Rotation centers.
    
public static final Punto Origin = new Punto(0,0);
    public static final 
Punto P1 = new Punto(100100);
    public static final 
Punto P2 = new Punto(100, -100);
    public static final 
Punto P3 = new Punto(-100, -100);
    public static final 
Punto P4 = new Punto(-100100);

    
// Current shape
    
private IForma forma null//new Punto();

    // Current shift and rotation steps
    
private double pasoLineal 10;
    private 
double pasoGiro   10;
    private 
double zoom 1;

    
// Current translation model;
    
private int modoTraslacion PuntosCardinales;

    
// Current rotation center and mode
    
private Punto roc Origin;
    private 
int modoRotacion CentroExterno;

    
// Color codes.
    
Color [] colors = {Color.blackColor.orangeColor.greenColor.blueColor.red};
    
int colorIndex 0;

    
DecimalFormat form = new DecimalFormat();

    
/*******************************************************************************
     *  Graphical elements
     */

    
JMenuBar menuBar;

    
// Figure selection menu
    
JMenu menuFigs
    
JMenuItem itVectoritTrianguloitPunto;

    
// Motion parameters menu
    
JMenu menuParametrosMovimiento

    
JMenu menuRotacion;
    
JMenu menuTraslacion;

    
// Rotation center entries
    
JMenuItem itRotOrigitRotCdmitRotP1itRotP2itRotP3itRotP4
    
JMenuItem itR10itR30itR90// Rotation step in degrees.

    // Translation configuration entries
    
JMenuItem itTrasladarSgOritTrasladarSgNSEO                  
    JMenuItem itD10
itD20itD40// Shift step


    // Motion panels: Translation and rotation panels.
    
JPanel pnTranslatepnRotate;
    
JButton btUpbtDownbtRigthbtLeftbtTurnRigthbtTurnLeft
    
JLabel lbRotatelbTranslate;
    
JLabel lbXlbYlbGrados;

    
// Reset Panel
    
JButton btResetbtZoomInbtZoomOut;

    
// Drawing area
    
private Lienzo lienzo;

    
// Control area 
    
private JPanel pnControl;


    public 
TestMovimientos(){

        
super("Practica 3. Test Movimientos.");

        
// Create and arrange application menus, controls and panels
        
buildMenus();
        
buildMotionPanels();
        
lienzo = new Lienzo();

        
// Event subscription. Window handles all events.
        // Event sources have been instantiated in buildMenus and buildMotion methods.
        // This code can be moved there.

        // Form selection
        
itVector.addActionListener(this);
        
itTriangulo.addActionListener(this);
        
itPunto.addActionListener(this);

        
// Translation mode selection
        
itTrasladarSgOr.addActionListener(this);
        
itTrasladarSgNSEO.addActionListener(this);

        
// Rotation center selection
        
itRotOrig.addActionListener(this);
        
itRotCdm.addActionListener(this); 
        
itRotP1.addActionListener(this);
        
itRotP2.addActionListener(this);
        
itRotP3.addActionListener(this);
        
itRotP4.addActionListener(this);

        
// Translation buttons.
        
btUp.addActionListener(this);
        
btDown.addActionListener(this); 
        
btRigth.addActionListener(this); 
        
btLeft.addActionListener(this);

        
// Rotation buttons
        
btTurnRigth.addActionListener(this); 
        
btTurnLeft.addActionListener(this);

        
// Reset Button
        
btReset.addActionListener(this);
        
        
// Zoom buttons
        
btZoomIn.addActionListener(this);
        
btZoomOut.addActionListener(this);


        
// Window layout.
        
getContentPane().add(lienzo);
        
getContentPane().add(pnControlBorderLayout.SOUTH);

        
// Window arrangements.
        
setSize (500,650);
        
setVisible(true);  
        validate
();
        
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

        
// Double numbers representation.
        
form.setMaximumFractionDigits(2);    

        
System.out.println("Centros de Rotación: ");
        
System.out.println("P1: " P1);
        
System.out.println("P2: " P2);
        
System.out.println("P3: " P3);
        
System.out.println("P4: " P4);
        
System.out.println("-------------------------------------------------------");
    }

    public 
void actionPerformed(ActionEvent ae){

        if (
ae.getSource() == btReset){
            
            
System.out.println("btReset clicked.");
            
            if (
forma != null){
                
forma = new Punto(0,0);
                
lienzo.setForma(forma);
                
updateLabels();
            }
            
            
System.out.println("-------------------------------------------------------");
            
System.out.println();
            return;
        }
        
        if (
ae.getSource() == itPunto){
            
            
System.out.println("Se ha seleccionado un PUNTO.");

            
forma = new Punto(0,0);
            
System.out.println("Punto Creado --> " forma);
            
lienzo.setForma(forma);

            
System.out.println("-------------------------------------------------------");
            
System.out.println();
            return;
        }

        if (
ae.getSource() == itVector){
            
            
System.out.println("Se ha seleccionado un VECTOR.");

            
forma = new Vector();
            
System.out.println("Punto Creado --> " forma);
            
lienzo.setForma(forma);

            
System.out.println("-------------------------------------------------------");
            
System.out.println();
            return;
        }

        if (
ae.getSource() == itTriangulo){
            
            
System.out.println("Se ha seleccionado un TRIANGULO.");
            
forma = new TrianguloEquilatero(100);
            
System.out.println("Trinagulo Creado --> " forma);
            
lienzo.setForma(forma);

            
System.out.println("-------------------------------------------------------");
            
System.out.println();
            return;
        }
        
        
// Escalado
 
       if (ae.getSource() == btZoomIn){
            
System.out.println("Se ha seleccionado ZOOM IN.");
 
           if (zoom 0.25){
 
               zoom /= 2;
 
               forma forma.escalar(0.5);
 
               lienzo.setForma(forma);
 
           }
 
           return;
 
       }
 
       
        if 
(ae.getSource() == btZoomOut){
            
System.out.println("Se ha seleccionado ZOOM OUT.");
 
           if (zoom <= 4){
 
               zoom *= 2;
 
               forma forma.escalar(2);
 
               lienzo.setForma(forma);
 
           }
 
           return;
 
       }
    

        
// Traslation
        
if (ae.getSource() == btUp || ae.getSource() == btDown || ae.getSource() == btRigth || ae.getSource() == btLeft){
            
            if (
forma == null){
                
System.out.println("Movimiento imposible: No hay figura activa.");
                return;
            }
            
            
System.out.print("Traslación según  " 
                    (
modoTraslacion == PuntosCardinales" NSEO ":" Eje figura ") +
                    
" From: " toCoords(forma.getX(), forma.getY()) + " Grados: " form.format(forma.getOrientacion()) + " To ");

            
Vector vtrTraslacion null;
            if (
modoTraslacion == PuntosCardinales) {
                if (
ae.getSource() == btUp){
                    
vtrTraslacion = (VectorJ.escalar(pasoLineal);
                }
                else if (
ae.getSource() == btDown){
                    
vtrTraslacion = (VectorJ.escalar(-pasoLineal);
                }
                else if (
ae.getSource() == btRigth){
                    
vtrTraslacion = (VectorI.escalar(pasoLineal);
                }
                else if (
ae.getSource() == btLeft){
                    
vtrTraslacion = (VectorI.escalar(-pasoLineal);
                }
                
forma forma.trasladar(vtrTraslacion.getCompX(), vtrTraslacion.getCompY());
            }
            else{
                if (
ae.getSource() == btUp){                    
                    
vtrTraslacion = (VectorVector.getUnitario(forma.getOrientacion()).escalar(pasoLineal);
                }
                else if (
ae.getSource() == btDown){
                    
vtrTraslacion = (VectorVector.getUnitario(forma.getOrientacion()).escalar(-pasoLineal);
                }
                
forma forma.trasladar(vtrTraslacion.getCompX(), vtrTraslacion.getCompY());
            }
            
System.out.println(toCoords(forma.getX(), forma.getY()) + " Grados: " form.format(forma.getOrientacion()));
            
System.out.println("-------------------------------------------------------");
            
System.out.println();

            
lienzo.setForma(forma);
            
//lienzo.updateForma();
            
updateLabels();
            return;
        }

        
// Rotation
        
if (ae.getSource() == btTurnRigth || ae.getSource() == btTurnLeft){
            
            if (
forma == null){
                
System.out.println("Movimiento imposible: No hay figura activa.");
                return;
            }
            
            
System.out.print("Rotación segun  " 
                    (
modoRotacion == CentroDeMasas? (" cdm " toCoords(forma.getX(), forma.getY())):(" roc " roc)) +
                    
" From " toCoords(forma.getX(), forma.getY()) + " Grados: " form.format(forma.getOrientacion()) + " To ");

            if (
modoRotacion == CentroExterno) {
                if (
ae.getSource() == btTurnRigth){
                    
forma forma.girar(-pasoGiroroc.getX(), roc.getY());
                }
                else if (
ae.getSource() == btTurnLeft){
                    
forma forma.girar(pasoGiroroc.getX(), roc.getY());
                }
            }
            else{
                if (
ae.getSource() == btTurnRigth){
                    
forma forma.girar(-pasoGiro);
                }
                else if (
ae.getSource() == btTurnLeft){
                    
forma forma.girar(pasoGiro);
                }                
            }

            
System.out.println(toCoords(forma.getX(), forma.getY()) + " Grados: " form.format(forma.getOrientacion()));
            
System.out.println("-------------------------------------------------------");
            
System.out.println();

            
lienzo.setForma(forma);
            
//lienzo.updateForma();
            
updateLabels();
            return;
        }


        
// Translation mode.        
        
if (ae.getSource() == itTrasladarSgOr ){
            
            
System.out.println("Cambiando modo traslación ---> Según Orientación " );

            
btRigth.setEnabled(false);
            
btLeft.setEnabled(false);
            
modoTraslacion EjeFigura;

            
System.out.println("-------------------------------------------------------");
            
System.out.println();
            return;
        }
        if (
ae.getSource() == itTrasladarSgNSEO){
            
            
System.out.println("Cambiando modo traslación ---> Según XY " );

            
btRigth.setEnabled(true);
            
btLeft.setEnabled(true);
            
modoTraslacion PuntosCardinales;

            
System.out.println("-------------------------------------------------------");
            
System.out.println();
            return;
        }


        
// Rotation Center and mode
        
if (ae.getSource() == itRotOrig || 
                
ae.getSource() == itRotP1 ||ae.getSource() == itRotP2 ||ae.getSource() == itRotP3 ||ae.getSource() == itRotP4 ||
                
ae.getSource() == itRotCdm){

            
System.out.print("Cambiando centro de rotación a ");

            if (
ae.getSource() == itRotCdm){
                
System.out.println(" centro del cuerpo. ");
                
modoRotacion CentroDeMasas;
            }
            else{
                
System.out.print(" punto externo: ");

                
modoRotacion CentroExterno;
                if (
ae.getSource() == itRotP1){
                    
roc P1;
                }
                if (
ae.getSource() == itRotP2){
                    
roc P2;
                }
                if (
ae.getSource() == itRotP3){
                    
roc P3;
                }
                if (
ae.getSource() == itRotP4){
                    
roc P4;
                }    
                if (
ae.getSource() == itRotOrig){
                    
roc Origin;
                }
                
System.out.println(roc);
            }
            
System.out.println("-------------------------------------------------------");
            
System.out.println();
            return;
        }
    }

    private 
void updateLabels(){
        
DecimalFormat form = new DecimalFormat();
        
form.setMaximumFractionDigits(2);
        
lbX.setText(String.valueOf(form.format(forma.getX())));
        
lbY.setText(String.valueOf(form.format(forma.getY())));
        
lbGrados.setText(String.valueOf(form.format(forma.getOrientacion())));
    }

    private 
void buildMenus(){

        
menuBar = new JMenuBar();

        
// Figure selection menu
        
menuFigs = new JMenu("Figura");

        
itVector = new JMenuItem("Vector");
        
itTriangulo = new JMenuItem("Triángulo"); 
        
itPunto = new JMenuItem("Punto"); 

        
menuBar.add(menuFigs);
        
menuFigs.add(itVector);
        
menuFigs.add(itTriangulo);
        
menuFigs.add(itPunto);

        
// Rotation center menu
        
menuParametrosMovimiento = new JMenu("Parametros de Movimiento");

        
// Rotation parameters
        
menuRotacion = new JMenu("Rotacion");

        
itRotOrig = new JMenuItem("Respecto Origen de Coordenadas");
        
itRotCdm  = new JMenuItem("Respecto Centro de la figura");
        
itRotP1   = new JMenuItem("Respecto P1");
        
itRotP2   = new JMenuItem("Respecto P2");
        
itRotP3   = new JMenuItem("Respecto P3");
        
itRotP4   = new JMenuItem("Respecto P4");

        
menuRotacion.add(itRotOrig);
        
menuRotacion.add(itRotCdm);
        
menuRotacion.add(itRotP1);
        
menuRotacion.add(itRotP2);
        
menuRotacion.add(itRotP3);
        
menuRotacion.add(itRotP4);

        
// Translation parameters
        
menuTraslacion     = new JMenu("Traslación");
        
itTrasladarSgOr    = new JMenuItem("Según orientación");
        
itTrasladarSgNSEO  = new JMenuItem("NSEO");
        
itD10     = new JMenuItem("Paso 10");
        
itD20     = new JMenuItem("Paso 20");
        
itD40     = new JMenuItem("Paso 40º");

        
menuTraslacion.add(itTrasladarSgOr);
        
menuTraslacion.add(itTrasladarSgNSEO);

        
// Menu Bar
        
menuBar.add(menuRotacion);
        
menuBar.add(menuTraslacion);
        
//menuBar.add(btReset);


        
setJMenuBar(menuBar);
    }

    private 
void buildMotionPanels(){

        
// Translation panel.
        
pnTranslate = new JPanel();
        
pnTranslate.setBorder(BorderFactory.createLineBorder(Color.BLUE));
        
btUp = new JButton("Ar"); 
        
btDown = new JButton("Ab"); 
        
btRigth = new JButton("D"); 
        
btLeft = new JButton("I");
        
btReset = new JButton("Reset Motion");
        
btZoomIn = new JButton("ZoomIn");
        
btZoomOut = new JButton("ZoomOut");


        
lbTranslate = new JLabel("Trasladar");
        
lbX = new JLabel("0");
        
lbY = new JLabel("0");


        
// Auxiliar elements.
        
JLabel [] relleno1 = new JLabel[5];
        for (
int i 0relleno1.lengthi++){
            
relleno1[i] = new JLabel();
        }

        
JPanel pnButtons1 = new JPanel();
        
pnButtons1.setBorder(BorderFactory.createLineBorder(Color.BLUE));
        
pnButtons1.setLayout(new GridLayout(3,3));
        
pnButtons1.add(relleno1[1]);
        
pnButtons1.add(btUp);
        
pnButtons1.add(relleno1[2]);
        
pnButtons1.add(btLeft);
        
pnButtons1.add(relleno1[3]);
        
pnButtons1.add(btRigth);
        
pnButtons1.add(relleno1[4]);
        
pnButtons1.add(btDown);
        
pnButtons1.add(relleno1[0]);

        
pnTranslate.setLayout(new GridLayout(1,2));
        
JPanel pnLabels1 = new JPanel();
        
pnLabels1.setLayout(new GridLayout(1,3));
        
pnLabels1.add(lbTranslate);
        
pnLabels1.add(lbX);
        
pnLabels1.add(lbY);

        
pnTranslate.add(pnLabels1);
        
pnTranslate.add(pnButtons1);

        
// Rotation panel.
        
pnRotate = new JPanel();
        
pnRotate.setBorder(BorderFactory.createLineBorder(Color.BLUE));

        
btTurnRigth = new JButton("Dcha"); 
        
btTurnLeft = new JButton("Izda"); 


        
lbRotate = new JLabel("Rotar");
        
lbGrados = new JLabel("0");

        
// Auxiliar elements.
        
JLabel relleno2  new JLabel();

        
JPanel pnButtons2 = new JPanel();
        
pnButtons2.setBorder(BorderFactory.createLineBorder(Color.BLUE));
        
pnButtons2.setLayout(new GridLayout(1,3));
        
pnButtons2.add(btTurnLeft);
        
pnButtons2.add(relleno2);
        
pnButtons2.add(btTurnRigth);

        
pnRotate.setLayout(new GridLayout(12));
        
JPanel pnLabels2 = new JPanel();
        
pnLabels2.setLayout(new GridLayout(1,2));
        
pnLabels2.add(lbRotate);
        
pnLabels2.add(lbGrados);
        
pnRotate.add(pnLabels2);
        
pnRotate.add(pnButtons2);    

        
// Putting all together
        
JPanel pnMot = new JPanel();
        
pnMot.setLayout(new BorderLayout());
        
pnMot.add(pnTranslate);
        
pnMot.add(pnRotateBorderLayout.SOUTH);

        
pnControl = new JPanel();
        
pnControl.setLayout(new BorderLayout());
        
pnControl.add(pnMot);
        
JPanel pnA = new JPanel();
        
pnA.add(btReset);
        
pnA.add(btZoomIn);
        
pnA.add(btZoomOut);
        
pnControl.add(pnABorderLayout.SOUTH);
    }


    public static 
void main(String[] args) {
        new 
TestMovimientos();

    }


    public class 
Lienzo extends JPanel{

        private static final 
long serialVersionUID 1L;
        
IForma forma null;
        
boolean debug true;
        
boolean updated false;

        
int LxLyOxOy;
        
int margen 20;
        
int longEjes 100;
        
int anchoPunto 4;

/*
        public void debugOn(){
            debug = true;
            System.out.println("Lienzo: Trace ON");
        }

        public void debugOff(){
            debug = false;
            System.out.println("Lienzo: Trace OFF");
        }
        */

        
public void setForma(IForma ob){
            if (
ob != null){
                
forma ob;
                
repaint();
            }
            else if (
debug){
                
System.out.println("Lienzo: Error --> setForma(null)");                
            }
        }

        
/*
        public void updateForma(){
            updated = false;
            repaint();
        }
        */

        
public Lienzo(){
            
setBorder(BorderFactory.createLineBorder(Color.GREEN));
            
setBackground(Color.white);
        }

        public 
void paintComponent(Graphics g){

            
super.paintComponent(g);

            
g.setColor(Color.DARK_GRAY);

            
// Drawing canvas edges
            
Dimension dim this.getSize();
            
Lx dim.width margen;
            
Ly dim.height margen;
            
Ox dim.width 2;
            
Oy dim.height dim.height/2;
            
g.drawLine(Ox longEjesOyOx longEjesOy);            
            
g.drawLine(OxOy longEjesOxOy longEjes);
            
//g.drawRect(10, 10, Lx, Ly);

            // Drawing rotation points
            
dibujarPosicion(P1g);
            
g.drawString("P1"Ox + (int)P1.getX() + 10Oy - (int)P1.getY() + 10);
            
dibujarPosicion(P2g);
            
g.drawString("P2"Ox + (int)P2.getX() + 10Oy - (int)P2.getY() + 10);
            
dibujarPosicion(P3g);
            
g.drawString("P3"Ox + (int)P3.getX() + 10Oy - (int)P3.getY() + 10);
            
dibujarPosicion(P4g);
            
g.drawString("P4"Ox + (int)P4.getX() + 10Oy - (int)P4.getY() + 10);

            
double x 00;
            if (
forma == null){
                return;
            }
            
forma.getX();
            
forma.getY();
            if (
forma instanceof Punto){
                
dibujarPosicion((Punto)formag);
            }
            else if (
forma instanceof IPoligonoRegular){
                
dibujarPoligono((IPoligonoRegular)formag);
            }
            else if (
forma instanceof Vector){
                
dibujarVector((Vector)formag);
            }
            
//g.drawString(toCoords(x, y), 30, 30);
            
updated true;
        }


        public 
void dibujarVector(Vector vtrGraphics g){

            
Color c g.getColor();
            
g.setColor(Color.BLUE);

            
Punto p vtr.getPuntoAplicacion();

            
int x1 = (int)p.getX();
            
int y1 = (int)p.getY();
            
            
int x2 x1 + (int)(vtr.getCompX() * 30);
            
int y2 y1 + (int)(vtr.getCompY() * 30);

            
int ax x2 - (int)(vtr.getUnitario().getCompX() * 15);
            
int ay y2 - (int)(vtr.getUnitario().getCompY() * 15);

            
double tetha vtr.getUnitario().getOrientacion() * Math.PI 180.0;
            
            
            
int bx ax - (int)(10 Math.cos((Math.PI/2) - tetha));
            
int by ay + (int)(10 Math.sin((Math.PI/2) - tetha));
            
int cx ax + (int)(10 Math.cos((Math.PI/2) - tetha));
            
int cy ay - (int)(10 Math.sin((Math.PI/2) - tetha));

            
g.drawLine(Ox x1Oy y1Ox x2Oy y2);

            
g.drawLine(Ox x2Oy y2Ox bxOy by);
            
g.drawLine(Ox x2Oy y2Ox cxOy cy);

            
g.setColor(c);            
        }


        
/**
         * Dibuja un punto
         * @param p
         * @param g
         */
        
public void dibujarPosicion(Punto pGraphics g){

            
Color c g.getColor();
            
g.setColor(Color.black);
            
g.fillOval(Ox + (int)((p.getX() - anchoPunto)), 
                    
Oy - (int)((p.getY() + anchoPunto)), 
                    
anchoPunto 2anchoPunto 2);
            
g.setColor(c);
        }

        
/**
         * Dibuja un polígono
         * @param pr
         * @param g
         */
        
public void dibujarPoligono(IPoligonoRegular prGraphics g){

            if (!(
pr instanceof IPoligonoRegular)){
                return;
            }

            
IPoligonoRegular pr1 = (IPoligonoRegularpr;

            
Color c g.getColor();
            
g.setColor(Color.red);

            
Punto pto [] = pr1.getVertices();

            
int xC [] = new int[pto.length];
            
int yC [] = new int[pto.length];

            for (
int i 0pto.lengthi++){
                
xC[i] = (int) pto[i].getX() + Ox;
                
yC[i] = Oy - (int) pto[i].getY();
            }

            
dibujarPosicion(pr.getCentro(), g);
            
dibujarVector(pr1.getUnitario(), g);
            
Polygon pol = new Polygon(xCyCxC.length);
            
g.drawPolygon(pol);
            
g.setColor(c);
        }    
    }

    private 
String toCoords(double xdouble y){
        
DecimalFormat form = new DecimalFormat();
        
form.setMaximumFractionDigits(2);
        return 
"[" form.format(x) + ", " form.format(y) + "]";
    }

"Que yo sepa, el español medio no es más honrado que los políticos que lo gobiernan" Cool
Responder


Salto de foro:


Usuarios navegando en este tema: 1 invitado(s)