// purpose: demonstrate rendering of a randomly colored box import java.util.*; import javax.swing.*; import java.awt.*; import java.awt.image.*; public class RandomBox { // RGB value base public static final int RGB_BASE = 256; // ****** desired dimensions and background public static final int PICTURE_WIDTH = 150; public static final int PICTURE_HEIGHT = 200; public static final Color BACKGROUND_COLOR = Color.BLACK; // ****** 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( "Randomly" ); 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 ); // ****** ready to produce the drawing // set description of the box int x = 35; int y = 45; int w = 80; int h = 100; // ****** get random generator for RGB values Random die = new Random(); // get color using random RGB values int red = die.nextInt( RGB_BASE ); int green = die.nextInt( RGB_BASE ); int blue = die.nextInt( RGB_BASE ); Color c = new Color( red, green, blue ); // ****** set the rendering color g.setColor( c ); // ****** draw a filled in rectangle g.fillRect( x, y, w, h ); // ****** print text representation of the color System.out.println( "color = " + c ); } }