import java.awt.* ; import javax.swing.* ; public class ColorGrid { private static int cellSize ; private static int nbCols ; private static int nbRows ; private static Color[][] colors ; private static JFrame frame ; private static CellPanel panel ; public static void initialize( int cellSize , int nbRows , int nbCols ) { ColorGrid.cellSize = cellSize ; ColorGrid.nbCols = nbCols ; ColorGrid.nbRows = nbRows ; colors = new Color[ nbRows ][ nbCols ] ; for( int i = 0 ; i < nbRows ; i++ ) { for( int j = 0 ; j < nbCols ; j++ ) { colors[i][j] = Color.BLACK ; } } panel = new CellPanel() ; frame = new JFrame( "ColorGrid" ) ; frame.getContentPane().add( panel ) ; frame.setSize( 10 + nbCols * cellSize , 25 + nbRows * cellSize ) ; frame.setVisible( true ) ; frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ) ; } public static void setCellColor( int r , int c , Color newColor ) { if( r < -nbRows || r > 2*nbRows ) throw new RuntimeException( "r = " + r ) ; if( c < -nbCols || c > 2*nbCols ) throw new RuntimeException( "c = " + c ) ; r = ( r + nbRows ) % nbRows ; c = ( c + nbCols ) % nbCols ; Color prevColor = colors[r][c] ; colors[r][c] = newColor ; if( !prevColor.equals( newColor ) ) { panel.drawCell( r , c ) ; } } public static Color getCellColor( int r , int c ) { if( r < -nbRows || r > 2*nbRows ) throw new RuntimeException( "r = " + r ) ; if( c < -nbCols || c > 2*nbCols ) throw new RuntimeException( "c = " + c ) ; r = ( r + nbRows ) % nbRows ; c = ( c + nbCols ) % nbCols ; return colors[r][c] ; } public static void pause( double seconds ) { try { Thread.sleep( (int)( seconds * 1000 ) ) ; } catch( Exception e ) {} } public static void stop() { frame.dispose(); } private static class CellPanel extends JPanel { void drawCell( int r , int c ) { Graphics g = getGraphics() ; g.setColor( colors[ r ][ c ] ); g.fillRect( c * cellSize , r * cellSize , cellSize , cellSize ); } public void paintComponent( Graphics g ) { if( colors == null ) return ; g.setColor( Color.BLACK ) ; g.fillRect( 0 , 0 , nbCols * cellSize , nbRows * cellSize ) ; int x = 0 ; int y = 0 ; for( int r = 0 ; r < nbRows ; r++ ) { for( int c = 0 ; c < nbCols ; c++ ) { if( !colors[r][c].equals( Color.BLACK ) ) { g.setColor( colors[r][c] ) ; g.fillRect( x , y , cellSize , cellSize ) ; } x += cellSize ; } y += cellSize; x = 0; } } } }