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

(singke) #1
ptg7068951

336 HOUR 23:Creating Java2D Graphics


The currentinstance variable is used to put each slice into its own ele-
ment of the slicearray. The lengthvariable of an array contains the num-
ber of elements the array has been defined to hold; as long as currentis
not larger than slice.length, you can continue adding slices to the panel.
The PiePanelclass handles all graphical operations in its
paintComponent()method, as you might expect. The trickiest thing about
this task is drawing the arcs that represent each slice of the pie.
This is handled in the following statements:
floatstart = 0;
for (int i = 0; i < slice.length; i++) {
floatextent = slice[i].size* 360F / totalSize;
comp2D.setColor(slice[i].color);
Arc2D.Float drawSlice = new Arc2D.Float(
xInset, yInset, width, height, start, extent,
Arc2D.Float.PIE);
start+= extent;
comp2D.fill(drawSlice);
}

The startvariable keeps track of where to start drawing an arc, and
extentkeeps track of the size of an arc. If you know the total size of all pie
slices and the size of a specific slice, you can figure out extentby multi-
plying the arc’s size by 360 and dividing that by the total of all slices.
All the arcs are drawn in a forloop: After each arc’s extentis calculated,
the arc is created and then extentis added to start. This causes each slice
to begin right next to the last one. Acall to the Graphics2Dmethod fill()
draws the arc.
To bring all this together, create a new empty Java file named PiePanel
and enter into it the full text from Listing 23.1.

LISTING 23.1 The Full Text of PiePanel.java
1: importjava.awt.*;
2: importjavax.swing.*;
3: importjava.awt.geom.*;
4:
5: public classPiePanel extendsJPanel {
6: privatePieSlice[] slice;
7: privateint current= 0;
8: privatefloattotalSize= 0;
9: privateColor background;
10:
11: publicPiePanel(int sliceCount) {
12: slice= new PieSlice[sliceCount];
Free download pdf