/** * AppletGraphics.java * @author Robert M. Keller * * Skeleton class for building an applet, with double buffering. */ import java.applet.*; // applet classes import java.awt.*; // Abstract Window Toolkit classes /** * AppletGraphics is a skeleton applet with double buffered graphics. */ public class AppletGraphics extends Applet { String message = "A 300 x 100 box"; int boxWidth = 300; int boxHeight = 100; Color backgroundColor = Color.white; Color foregroundColor = Color.black; Font MainFont = new Font("Helvetica", Font.BOLD, 18); Image image; // image holding the graphics buffer Graphics graphics; // graphics buffer /** * Initialize the applet. */ public void init() { setBackground(backgroundColor); // size().width and size().height are deprecated and normally would // be replaced with getWidth() and getHeight(). However, the latter // do not work with some browsers. // make an off-screen graphics buffer image = createImage(size().width, size().height); graphics = image.getGraphics(); } /** * Start the applet. */ public void start() { drawBox(); } /** * An example: * Drawing a box containing a message indicating the size of the box, * with a dividing line. */ void drawBox() { // Get the dimensions of the window. int windowWidth = Integer.parseInt(getParameter("width")); int windowHeight = Integer.parseInt(getParameter("height")); // Fill the background. graphics.setColor(backgroundColor); graphics.fillRect(0, 0, windowWidth, windowHeight); // Set up for drawing. graphics.setColor(foregroundColor); // Draw a rectangle centered in the window. graphics.drawRect((windowWidth - boxWidth)/2, (windowHeight - boxHeight)/2, boxWidth, boxHeight); // Draw a horizontal line centered in the rectangle. graphics.drawLine((windowWidth-boxWidth)/2, windowHeight/2, (windowWidth+boxWidth)/2, windowHeight/2); // Draw the message. graphics.setFont(MainFont); FontMetrics metrics = graphics.getFontMetrics(); int stringWidth = metrics.stringWidth(message); int stringHeight = metrics.getHeight(); graphics.drawString(message, (windowWidth - stringWidth)/2, (windowHeight - stringHeight)/2); } /** * Update is implicitly called by repaint(). * It calls paint(Graphics). */ public void update(Graphics g) { paint(g); } /** * paint(Graphics) is called by update(Graphics). */ public void paint(Graphics g) { g.drawImage(image, 0, 0, null); } } // AppletGraphics