

Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!


The following is a simple applet that draws a blue rectangle on a yellow background. // **************************************************************** // RandomShapes.java // // The program will draw two filled rectangles and a // filled oval positioned randomly on the screen. // **************************************************************** import java.applet.Applet; import java.awt.*; public class RandomShapes extends Applet { public void paint (Graphics page) { // Declare size constants final int MAX_SIZE = 300; final int PAGE_WIDTH = 600; final int PAGE_HEIGHT = 400; // Declare variables int x, y; // x and y coordinates of upper left-corner of each shape int width, height; // width and height of each shape // Set the background color setBackground (Color.yellow); // Set the color for the next shape to be drawn page.setColor (Color.blue); // Assign the corner point and width and height x = 200; y = 150; width = 100; height = 70; // Draw the rectangle page.fillRect(x, y, width, height); } }
***** The program imports java.applet.Applet because this is an applet, and it imports java.awt.* because it uses graphics. ***** There is no main method -- instead there is a paint method. The paint method is automatically invoked when an applet is displayed, just as the main method is automatically invoked when an application is executed.
***** Most of the methods that draw shapes (see the list in Figure 2. in your textbook) require parameters that specify the upper left-hand corner of the shape (using the coordinate system described in textbook Section 1.6) and the width and height of the shape. You can see this in the calls to fillRect, which draws a rectangle filled with the current foreground color. ***** This applet will be drawn assuming the window for drawing (the Graphics object - named "page" here) is 600 pixels wide and 400 pixels high. These numbers are defined in constants at the beginning of the program. (They currently have no use but you will use them later). The width and height of the applet are actually specified in an HTML file that tells how to run the applet (remember applets are often executed by Web browsers and Web browsers get their instructions from HTML documents -- note that the code executed by the browser is the bytecode for the program, the RandomShapes.class file). The code in an HTML document would be as follows: Save the files RandomShapes.java and RandomShapes.html (save RandomShapes.html by right clicking on your mouse then clicking on Save tartget As ...). Notice if the html file was saved as .html or .htm.