//******************************************************************** // BarHeights.java Author: Lewis and Loftus // // Demonstrates the use of conditionals and loops to guide drawing. //******************************************************************** import java.applet.Applet; import java.awt.*; public class BarHeights extends Applet { private final int NUM_BARS = 10; private final int BAR_WIDTH = 30; private final int MAX_HEIGHT = 300; private final int GAP = 9; //----------------------------------------------------------------- // Paints bars of varying heights, tracking the tallest and // shortest bars, which are redrawn in color at the end. //----------------------------------------------------------------- public void paint (Graphics page) { int x, height; int tallX = 0, tallest = 0, shortX = 0, shortest = MAX_HEIGHT; setBackground (Color.black); page.setColor (Color.blue); x = GAP; for (int count = 0; count < NUM_BARS; count++) { height = (int) (Math.random() * MAX_HEIGHT); page.fillRect (x, MAX_HEIGHT-height, BAR_WIDTH, height); // Keep track of the tallest and shortest bars if (height > tallest) { tallX = x; tallest = height; } if (height < shortest) { shortX = x; shortest = height; } x = x + BAR_WIDTH + GAP; } // Redraw the tallest bar in red page.setColor (Color.red); page.fillRect (tallX, MAX_HEIGHT-tallest, BAR_WIDTH, tallest); // Redraw the shortest bar in yellow page.setColor (Color.yellow); page.fillRect (shortX, MAX_HEIGHT-shortest, BAR_WIDTH, shortest); } }