import javax.swing.*; import java.awt.*; import java.awt.geom.*; public class NgonView extends JPanel { private int nSides = 0; private Font ngonFont; static public final Dimension PREF_SIZE = new Dimension( 600, 700 ); static public final float SCALE = 200.0F; static public final float tx = 1.5F; static public final float ty = 1.5F; static public final int warnX = 180; static public final int warnY = 600; static public final int areaX = 180; static public final int areaY = 600; public NgonView() { ngonFont = new Font( "SansSerif", Font.ITALIC, 16 ); } public void setSides ( int n ) { nSides = n; repaint(); } public Dimension getPreferredSize() { return PREF_SIZE; } public void paintComponent( Graphics g ) { Graphics2D g2 = (Graphics2D) g; float dtheta = (float) ( 2 * Math.PI ) / nSides; super.paintComponent( g ); g2.setFont( ngonFont ); g2.setPaint( Color.red ); if ( nSides < 3 ) { g2.drawString( "Elija un número de lados >= 3", warnX, warnY ); } else { g2.drawString( "Área del polígono = " + getArea(), areaX, areaY ); } g2.setStroke( new BasicStroke( 2 ) ); Shape circle = new Ellipse2D.Float( transX ( -1.0F ), transY( -1.0F ), 2.0F * SCALE, 2.0F * SCALE ); g2.setPaint( Color.yellow ); g2.fill( circle ); g2.setPaint( Color.blue ); g2.draw( circle ); g2.setPaint( Color.green ); GeneralPath ngon = new GeneralPath(); ngon.moveTo( transX( 1.0F ), transY( 0.0F ) ); for ( int i = 1; i < nSides; i++ ) { float x = transX( (float) Math.cos( i * dtheta )); float y = transY( (float) Math.sin( i * dtheta )); ngon.lineTo( x, y ); } ngon.closePath(); g2.fill( ngon ); } private double getArea() { double PIn = Math.PI / nSides; return nSides * Math.cos( PIn ) * Math.sin( PIn ); } private float transX( float x ) { return ( x + tx ) * SCALE; } private float transY( float y ) { return ( y + ty ) * SCALE; } }