// purpose: demonstrate rendering of randomly colored boxes import java.util.*; import javax.swing.*; import java.awt.*; import java.awt.image.*; public class RandomBoxes { // RGB value base public static final int RGB_BASE = 256; // ****** desired dimensions and background public static final int PICTURE_WIDTH = 500; public static final int PICTURE_HEIGHT = 600; public static final Color BACKGROUND_COLOR = Color.BLACK; public static final int MAX_BOX_WIDTH = 100; public static final int MAX_BOX_HEIGHT = 200; public static final int NUMBER_ITERATIONS = 500000; // ****** convenience constant public static final int RGB = BufferedImage.TYPE_INT_RGB; // method main(): program starting point public static void main( String[] args ) throws Exception { // ****** set up window JFrame window = new JFrame( "Wowie-zowie" ); window.setAlwaysOnTop( true ); window.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); // ****** set up a surface for painting the image BufferedImage surface = new BufferedImage( PICTURE_WIDTH, PICTURE_HEIGHT, RGB ); // ****** get the window to put the surface on its content pane ImageIcon icon = new ImageIcon( surface ); JLabel pane = new JLabel( icon ); window.setContentPane( pane ); // ****** size and display the window window.pack(); window.setVisible( true ); // ****** get a renderer to manipulate the surface's display Graphics g = surface.getGraphics(); pane.setBackground( Color.BLACK ); // ****** paint the entire surface the background color g.setColor( BACKGROUND_COLOR ); g.fillRect( 0, 0, PICTURE_WIDTH, PICTURE_HEIGHT ); // ****** set up counter to keep track of the number of boxes int counter = 0; // ****** ready to produce the drawing while ( counter < NUMBER_ITERATIONS ) { // ****** pause for observation purposes Pause.untilReady(); // ****** get random number generator Random dice = new Random(); // get random description of a box int red = dice.nextInt( RGB_BASE ); int green = dice.nextInt( RGB_BASE ); int blue = dice.nextInt( RGB_BASE ); int x = dice.nextInt( PICTURE_WIDTH ); int y = dice.nextInt( PICTURE_HEIGHT ); int w = dice.nextInt( MAX_BOX_WIDTH ); int h = dice.nextInt( MAX_BOX_HEIGHT ); Color c = new Color( red, green, blue ); // ****** send renderer two messages; i.e., drawing commands g.setColor( c ); g.fillRect( x, y, w, h ); // ****** move counter along counter = counter + 1; // ****** pause to appreciate current box Pause.moment(); // ****** explicitly repaint the window pane pane.repaint(); } Capturer.takeSnapshot( pane ); } }