FileDocCategorySizeDatePackage
GraphicsSampler.javaAPI DocExample2759Sat Jun 02 02:41:36 BST 2001None

GraphicsSampler.java

// This example is from _Java Examples in a Nutshell_. (http://www.oreilly.com)
// Copyright (c) 1997 by David Flanagan
// This example is provided WITHOUT ANY WARRANTY either expressed or implied.
// You may study, use, modify, and distribute it for non-commercial purposes.
// For any commercial use, see http://www.davidflanagan.com/javaexamples

import java.applet.*;
import java.awt.*;

/**
 * An applet that demonstrates most of the graphics primitives in java.awt.Graphics.
 **/
public class GraphicsSampler extends Applet
{
  Image image;
  Image background;

  // Initialize the applet
  public void init()
  {
    this.setBackground(Color.lightGray);
    image = this.getImage(this.getDocumentBase(), "tiger.gif");
    background = this.getImage(this.getDocumentBase(), "background.gif");
  }

  // Draw the applet whenever necessary
  public void paint(Graphics g)
  {
    Color fill = new Color(200, 200, 200);
    Color outline = Color.blue;
    Color textcolor = Color.red;
    Font font = new Font("sansserif", Font.BOLD, 14);
    g.setFont(font);

    // get a background image and tile it
    tile(g, this, background);

    // Draw a line
    g.setColor(outline);
    g.drawLine(25, 10, 150, 80);
    centerText("drawLine()", null, g, textcolor, 25, 10, 150, 80);

    // Draw an arc
    g.setColor(fill);
    g.fillArc(225, 10, 150, 80, 90, 135);
    g.setColor(outline);
    g.drawArc(225, 10, 150, 80, 90, 135);
    centerText("fillArc()", "drawArc()", g, textcolor, 225, 10, 150, 80);

    // Draw a rectangle
    g.setColor(fill);
    g.fillRect(25, 110, 150, 80);
    g.setColor(outline);
    g.drawRect(25, 110, 150, 80);
    centerText("fillRect()", "drawRect()", g, textcolor, 25, 110, 150, 80);

    // Draw a rounded rectangle
    g.setColor(fill);
    g.fillRoundRect(225, 110, 150, 80, 20, 20);
    g.setColor(outline);
    g.drawRoundRect(225, 110, 150, 80, 20, 20);
    centerText("fillRoundRect()", "drawRoundRect()", g, textcolor,
               225, 110, 150, 80);

    // Draw a 3D rectangle (clear an area for it first)
    g.setColor(fill);
    g.clearRect(20, 205, 160, 90);
    g.draw3DRect(25, 210, 150, 80, true);
    g.draw3DRect(26, 211, 148, 78, true);
    g.draw3DRect(27, 212, 146, 76, true);
    centerText("draw3DRect()", "x 3", g, textcolor, 25, 210, 150, 80);

    // Draw an oval
    g.setColor(fill);
    g.fillOval(225, 210, 150, 80);
    g.setColor(outline);
    g.drawOval(225, 210, 150, 80);
    centerText("fillOval()", "drawOval()", g, textcolor, 225, 210, 150, 80);

    // Draw a polygon
    int numpoints = 9;
    int[] xpoints = new int[numpoints+1];
    int[] ypoints = new int[numpoints+1];
    for(int i=0; i