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

(singke) #1
ptg7068951

Baking a Pie Graph 339

43: } catch(Exception exc) {
44: // ignore error
45: }
46: }
47:
48: public static void main(String[] arguments) {
49: PieFrame pf = new PieFrame();
50: }
51: }

The PieFrameclass is a simple graphical user interface that contains one
component, a PiePanelobject created in line 24. The object’s addSlice()
method is called 10 times in lines 25–35 to add slices to the pie graph.
When you run the application, PieFramedisplays a pie graph showing the
population of the 10 most populated countries (in millions), using figures from
a July 2011 U.S. Census International Data Base report. In order, they are China
(1.337 billion), India (1.189 billion), United States (311 million), Indonesia (246
million), Brazil (203 million), Pakistan (187 million), Nigeria (166 million),
Bangladesh (159 million), Russia (139 million), and Japan (127 million).
Because Java only has a few colors defined in the Colorclass, 10 new ones are
created for use here and given descriptive names. The colors are expressed as
hexadecimal values—in Java, hexadecimal numbers are preceded by 0x—but
they also could have been specified as decimal values in each Color()con-
structor.
Figure 23.3 shows this application running.

LISTING 23.2 Continued

China

United States

India Japan
Russia
Bangladesh
Nigeria
Pakistan


Brazil
Indonesia

FIGURE 23.3
Displaying population figures in a
pie graph.

NOTE
Yo u c a n f i n d t h e c u r r e n t U. S.
Census world population figures
by visiting http://www.cadenhead.org/
census.
Free download pdf