home *** CD-ROM | disk | FTP | other *** search
/ Java Programmer's Toolkit / Java Programmer's Toolkit.iso / project / 5 / graphi~1.jav < prev   
Encoding:
Text File  |  1995-10-31  |  2.1 KB  |  82 lines

  1. import java.awt.*;
  2. import java.applet.*;
  3.  
  4. public class GraphicsApplet extends Applet {
  5.     Font   appFont;
  6.     Color appColor;
  7.     String appShape;
  8.     String appText;
  9.     Image         image;
  10.  
  11.     public void init() {
  12.     appFont = new Font("Helvetica",Font.BOLD,14);
  13.     String arg = getParameter("COLOR");
  14.     if (arg!= null) {
  15.         appColor = colorFromString(arg,Color.red);
  16.     }
  17.     appShape = getParameter("SHAPE");
  18.     if (appShape == null) {
  19.         appShape = "Line";
  20.     }
  21.     appText = getParameter("TEXT");
  22.     if (appText == null) {
  23.         appText = "Graphics";
  24.     }
  25.     arg = getParameter("IMAGE");
  26.     if (arg == null) {
  27.         arg = "images/duke.gif";
  28.     }
  29.     image = getImage(getDocumentBase(), arg);
  30.     }
  31.  
  32.     public void paint(Graphics g) {
  33.     Dimension r = size();
  34.     g.setColor(appColor);
  35.     if (appShape.equalsIgnoreCase("line")) {
  36.         g.drawLine(0, 0, r.width, r.height);
  37.     } else if (appShape.equalsIgnoreCase(
  38.         "rectangle")) {
  39.         g.drawRect(0, 0, r.width - 1, r.height - 1);
  40.     } else if (appShape.equalsIgnoreCase("image")) {
  41.         g.drawImage(image,0,0,r.width,r.height,this);
  42.     } else if(appShape.equalsIgnoreCase("string")){
  43.         g.setFont(appFont);
  44.         drawCenteredString(appText, appColor, g, r);
  45.     }
  46.     }
  47.  
  48.     public void drawCenteredString(String s,
  49.                    Color color,
  50.                    Graphics g,
  51.                    Dimension r) {
  52.     FontMetrics fm = g.getFontMetrics();
  53.     int sWidth = fm.stringWidth(s);
  54.     int sHeight = fm.getHeight();
  55.     g.setColor(color);
  56.     g.drawString(s,(r.width - sWidth)/2, (r.height - sHeight)/2);
  57.     }
  58.  
  59.     public Color colorFromString(String s, Color defaultColor) {
  60.     Integer i;
  61.     try {
  62.         i = Integer.valueOf(s, 16);
  63.         return new Color(i.intValue());
  64.     } catch (NumberFormatException e) {
  65.         if (s.equalsIgnoreCase("red")) {
  66.         return Color.red;
  67.         } else if (s.equalsIgnoreCase("green")) {
  68.         return Color.green;
  69.         } else if (s.equalsIgnoreCase("blue")) {
  70.         return Color.blue;
  71.         } else if (s.equalsIgnoreCase("black")) {
  72.         return Color.black;
  73.         } else if (s.equalsIgnoreCase("white")) {
  74.         return Color.white;
  75.         } else {
  76.         return defaultColor;
  77.         }
  78.     }
  79.     }
  80. }
  81.  
  82.