//File: Surprise4.java import java.awt.*; import java.awt.event.*; import java.applet.*; public class Surprise4 extends Applet { //Exploding and imploding balloons //With Small, Medium, Large, .. added public void init() { setBackground (Color.white); } public void paint (Graphics g) { // Added array of size_labels String [] size_labels = { "Small", "Medium", "Large", "XL", "XXL" }; // Note the extra blanks on Small Dimension size = getSize(); int size_bin; // Added index for size_labels int diameter = 0, w = size.width, h = size.height, cmin = (int)Math.min(w, h); // g.setColor(Color.yellow); // was here while (diameter < cmin) { int ws, hf; // needed to position labels Font current; // note the different style FontMetrics metrics; // when we do this later g.setColor(Color.yellow); //now here g.fillOval((w-diameter)/2, (h-diameter)/2, diameter, diameter); // Note it is important to do this size_bin = (5*diameter)/cmin; // Before this diameter++; // Added code for the size labels current = getFont(); metrics = getFontMetrics (current); ws = metrics.stringWidth(size_labels[size_bin]); hf = metrics.getHeight(); g.setColor(Color.blue); g.drawString(size_labels[size_bin], (w-ws)/2, (h+hf)/2); try { Thread.sleep(10); // sleep for 10 msec } catch (InterruptedException t) { } } g.setColor(Color.yellow); //need to draw oval again //to overwrite old labels g.fillOval((w-diameter)/2, (h-diameter)/2, diameter, diameter); Font current = getFont(); FontMetrics metrics = getFontMetrics (current); int ws = metrics.stringWidth("Surprise!"); int hf = metrics.getHeight(); g.setColor(Color.red); g.drawString("Surprise!", (w-ws)/2, (h+hf)/2); try { Thread.sleep(1000); // sleep for 1 sec } catch (InterruptedException t) { } while (diameter > 1) { //The following draws circles in yellow, //pauses, then redraws them in white (the background color), //thus effectively erasing them. It then changes the color //back to yellow and repeats the process for a circle //of diameter one less than the previous one. //Note that we have to rewrite the labels in white //or medium will show behind small // int ws, hf; // already declared above // Font current; // FontMetrics metrics; g.setColor(Color.yellow); g.fillOval((w-diameter)/2, (h-diameter)/2, diameter, diameter); // Note the -1 size_bin = (5*(diameter-1))/cmin; // Added code for the size labels again current = getFont(); metrics = getFontMetrics (current); ws = metrics.stringWidth(size_labels[size_bin]); hf = metrics.getHeight(); g.setColor(Color.blue); g.drawString(size_labels[size_bin], (w-ws)/2, (h+hf)/2); try { Thread.sleep(10); // sleep for 10 msec } catch (InterruptedException t) { } g.setColor (Color.white); g.fillOval((w-diameter)/2, (h-diameter)/2, diameter, diameter); g.drawString(size_labels[size_bin], (w-ws)/2, (h+hf)/2); diameter--; } repaint(); //calls update() which CLEARS THE WINDOW, //then calls paint() } }