/** * File: PetRockApplet.java * Author: Mr. Instructor * Programming: lCCC - CIS 210 * Last Modified: January 2011 * Description: This applet creates, draws, computes * the area, and flips a pet rock (a rectangle with a name) */ import java.awt.*; // go get the java "standard graphic" classes import java.applet.Applet; // go get the java "standard applet" classes import java.awt.event.*; // go get the java "standard event" classes public class PetRockApplet extends Applet implements ActionListener { private int length; // length of rectangular rock private int width; // width of rectangular rock private String name; // name of rock private Button flipButton; // declare a flip button (but don't "fill" it yet) /** * The init() method initializes/starts/creates rock */ public void init() { PetRockApplet myPetRock; // declare an empty PetRockApplet class called "myPetRock" myPetRock = new PetRockApplet(); // create (instantiate) the new PetRock flipButton = new Button("Click to see my pet rock flip!"); // create the button add(flipButton); // draw the button flipButton.addActionListener(this); // listen for a mouse click repaint(); // draw the rock on the screen } // init applet /** * The PetRockApplet() method constructs the pet rock with a given * length and width and name. */ public PetRockApplet() { name = "Mr. Instructor's Pet Rock"; length = 30; width = 70; } // PetRock constructor /** * The calculateArea() method calculates and returns * the area of the (rectangular) rock. */ public double calculateArea() { double area; return area = length * width; } // calculateArea() /** * The flip() method switches the length and width of the rock * then redraws the picture. */ public void flip() { int temp; // need the temp variable only in this method temp = width; width = length; length = temp; } // flip() /** * The paint() method draws the rock (a rectangle) as well * as the name of the rock then computes and prints the area * of the rock using the calculateArea() method. */ public void paint(Graphics g) // create a graphics object (predefined) { g.drawString(name,50,60); // draws the name at 50 over and 60 down g.setColor(Color.red); // sets the rock's color to red g.fillRect(100,150,width,length); // draws the rectangular Rock g.drawString("The length :"+length,50,75); // what does this line draw? g.drawString("The width : "+width,50,90); g.drawString("The area : "+calculateArea(),50,105); // what does this line draw? } // paint() /** * The actionPerformed() method is automatically called whenever * the flip button is clicked. */ public void actionPerformed(ActionEvent e) { flip(); // flip the length and width repaint(); // redraw the picture } // actionPerformed() } // end petRockApplet