/////// PieChart.java /////// import java.awt.*; import java.applet.Applet; import java.util.StringTokenizer; /** This program demonstrates 1) configurable applet with PARAM parameters 2) getParameterInfo() 3) boarder and grid layouts 4) writing code that runs as an applet and an application 5) Uniform treatment of command-line and PARAM args 6) Use of Panel, Label, Canvas components */ public class PieChart extends Applet { public String[][] getParameterInfo() { String[][] info = {{"args", "item double color ...", "series of triples giving the" + "name, percentage, and color for" + "each part of the pie chart"} }; return info; } public void init() { if ( treatArgs() == false ) // sets up clr, perc, name, items return; PiePlot p = new PiePlot(items, perc, clr); setLayout(new BorderLayout()); add(p, "Center"); ColLabel labels = new ColLabel(name, clr); add(labels, "East"); } protected String[] getArgs() { String s = getParameter("args"); if ( s == null ) return null; StringTokenizer st = new StringTokenizer(s); int i = st.countTokens(); String[] args = new String[i]; for (int j=0; j < i; j++) args[j] = st.nextToken(); return args; } protected boolean treatArgs() { if ( arg == null ) arg = getArgs(); if ( arg==null || arg.length%3 != 0 ) { System.err.println("Args: Apple 0.3 red ..."); return false; } items = arg.length/3; clr = new Color[items]; perc = new double[items]; name = new String[items]; int j=0; for (int i=0; i < items; i++) { perc[i] = Double.valueOf(arg[++j]).doubleValue(); name[i] = (arg[j-1] + " " + perc[i]*100 + "%"); clr[i] = whichColor(arg[++j], (i%2==0)?Color.gray:Color.white); j++; } return true; } public static Color whichColor(String s, Color df) { if (s.equals("black")) return Color.black; if (s.equals("blue")) return Color.blue; if (s.equals("cyan")) return Color.cyan; if (s.equals("darkGray")) return Color.darkGray; if (s.equals("lightGray")) return Color.lightGray; if (s.equals("gray")) return Color.gray; if (s.equals("green")) return Color.green; if (s.equals("magenta")) return Color.magenta; if (s.equals("orange")) return Color.orange; if (s.equals("pink")) return Color.pink; if (s.equals("red")) return Color.red; if (s.equals("white")) return Color.white; if (s.equals("yellow"))return Color.yellow; Color c = Color.getColor(s); if ( c != null ) return c; return df; } protected Color[] clr; protected double[] perc; protected int items; protected String[] arg = null; // cmd-line args protected String[] name = null; // label strings // protected void setArg(String[] s) // { arg = s; } public static void main(String[] args) { if ( args.length == 0 || args.length%3 != 0 ) { System.err.println("Usage: PieChart Apple 0.3 red ..."); return; } Frame win = new Frame("PieChart"); PieChart chart = new PieChart(); chart.arg = args; chart.init(); win.add(chart, "Center"); win.setSize(300, 200); win.setVisible(true); } }