Sams Teach Yourself Java™ in 24 Hours (Covering Java 7 and Android)

(singke) #1
ptg7068951

Baking a Pie Graph 335

A new helper class, PieSlice, is used to represent each slice in the pie
graph:


importjava.awt.*;


classPieSlice {
Color color= Color.lightGray;
floatsize= 0;


PieSlice(Color pColor, floatpSize) {
color= pColor;
size= pSize;
}
}


Each slice is constructed by calling PieSlice(Color, float). The com-
bined value of all slices is stored as a private instance variable of the
PiePanelclass, totalSize. There also are instance variables for the panel’s
background color (background) and a counter used to keep track of slices
(current):


private intcurrent= 0;
private floattotalSize= 0;
privateColor background;


Now that you have a PieSliceclass to work with, you can create an array
of PieSliceobjects with another instance variable:


privatePieSlice[] slice;


When you create a PiePanelobject, none of the slices have an assigned a
color or size. The only things that you must do in the constructor are
define the size of the slicearray and save the background color of the
panel:


publicPiePanel(int sliceCount) {
slice= newPieSlice[sliceCount];
background= getBackground();
}


Use the addSlice(Color, float)method to add a slice of the pie to the
panel:


public voidaddSlice(Color sColor, floatsSize) {
if (current<= slice.length) {
slice[current] = new PieSlice(sColor, sSize);
totalSize+= sSize;
current++;
}
}

Free download pdf