import java.io.*; import java.awt.Polygon; public class PolygonPlotter { private static PolygonViewer view; private static int width = 0; private static int height = 0; private static int scale = 1; private static FileReader fileRdr; public static void main( String[] args ) { if ( args.length != 3 ) { usage(); } try { width = Integer.parseInt( args[ 0 ] ); height = Integer.parseInt( args[ 1 ] ); } catch ( NumberFormatException e ) { usage(); } view = new PolygonViewer( width, height ); readPolygons( args[ 2 ] ); view.pack(); view.setVisible( true ); } /* * Esta clase lee un archivo de definiciones de polígono de la forma: * * xcoord0 ycoord0 * xcoord1 ycoord1 * ... * xcoordN ycoordN * líneas en blanco * * Las líneas en blanco adicionales pueden preceder o seguir a una definición de polígono, * pero la primera línea en blanco finaliza el polígono actual. */ private static void readPolygons( String f ) { try { fileRdr = new FileReader( f ); BufferedReader bufRdr = new BufferedReader( fileRdr ); StreamTokenizer tokens = new StreamTokenizer( bufRdr ); tokens.eolIsSignificant( true ); try { tokens.nextToken(); while ( tokens.ttype != StreamTokenizer.TT_EOF ) { // Saltar líneas en blanco if ( tokens.ttype == StreamTokenizer.TT_EOL ) { while ( tokens.nextToken() == StreamTokenizer.TT_EOL ) ; } else if ( tokens.ttype == StreamTokenizer.TT_NUMBER ) { // el testigo actual es el primer testigo de una línea que no sea en blanco view.addPolygon( extractPolygon( tokens )); } else throw new DataFormatException(); } } catch ( DataFormatException e ) { System.err.println( "No es posible leer la descripción del polígono en la línea número " + tokens.lineno() + "." ); System.exit( 1 ); } bufRdr.close(); } catch ( IOException e ) { handleErr( e ); } } // extractpolygon() asume que el testigo actual es la // primera coordenada x de un polígono private static Polygon extractPolygon( StreamTokenizer t ) throws DataFormatException, IOException { Polygon p = new Polygon(); do { int x = ( int ) t.nval; if ( t.nextToken() != StreamTokenizer.TT_NUMBER ) throw new DataFormatException(); int y = ( int ) t.nval; // transform to awt window coordinates y = height - y - 1; if ( t.nextToken() == StreamTokenizer.TT_EOL || t.ttype == StreamTokenizer.TT_EOF ) { p.addPoint( x, y ); } else throw new DataFormatException(); } while ( t.ttype == StreamTokenizer.TT_EOL && t.nextToken() == StreamTokenizer.TT_NUMBER ); return p; } private static void usage() { System.err.println( "uso: java PolygonPlotter " ); System.exit( 1 ); } private static void handleErr( Exception e ) { System.err.println( e ); view.setVisible( false ); view.dispose(); System.exit( 1 ); } }