martedì 2 dicembre 2008

Poligono

import java.awt.*; /*abstract windows toolkit*/
import java.awt.event.*;
import java.applet.*;
import java.util.*;
import java.awt.geom.*;

public class RotazionePoligono extends Applet implements MouseListener, KeyListener {
private int[] xpoints= {0,-10,-7,7,10};
private int[] ypoints= {-10,-2,10,10,-2};

private Polygon poly; /*creo un nuovo poligono*/
int rotation=0;
public void init() { /*primo metodo che viene lanciato quando l'applet viene creata*/
poly=new Polygon(xpoints,ypoints,xpoints.length);
addMouseListener(this);
addKeListener(this);
}
public void paint(Graphics g) {
Graphics2D g2d= (Graphics2D) g; /*converto una variabile (oggetto) g in una variabile (oggetto) g2d [CASTING]*/
int ampiezza=getSize().width;
int altezza=getSize().height;
g2d.setColor(Color.BLACK);
g2d.fillRect(0,0,ampiezza,altezza); /*riempe il rettangolo (Rect) per le coordinate fornite che lo delimitano
0,0 = limiti di partenza da cui iniziare a riempire
ampiezza,altezza = limiti di arrivo dove finire di riempire*/

g2d.translate(ampiezza/2,altezza/2);
g2d.scale(20,20);
g2d.rotate( Math.toRadians(rotation) );
/*istruzioni per disegnare il poligono*/
g2d.setColor(Color.YELLOW);
g2d.draw(poly);
g2d.setColor(Color.PINK);
g2d.fill(poly); /*riempo (con fill) la forma poligono (instanziata prima) con il colore settato da setColor*/

}
public void mouseEntered(MouseEvent m) {}
public void mouseExited(MouseEvent m) {}
public void mouseReleased(MouseEvent m) {}
public void mouseClicked(MouseEvent m) {}
public void mousePressed (MouseEvent m) {
switch (m.getButton() ) {
case MouseEvent.BUTTON1:
rotation--;
if (rotation<0) rotation=359;
repaint();
break;
case MouseEvent.BUTTON3:
rotation++;
if (rotation>360) rotation=0;
repaint();
break;
}
}
public void keyReleased(keyEvent k){}
public void keyTiped(keyEvent k){}
public void keyPressed(keyEvent k){}

switch (k.getKeyCode() ) {
case KeyEvent .VK_LEFT:
rotation--;
if (rotation<0) rotation=359;
repaint();
break;
case MouseEvent.VK_RIGHT:
rotation++;
if (rotation>360) rotation=0;
repaint();
break;
}

Nessun commento: