The JFree Chart Class Library Developer Guide V1 0 9

User Manual:

Open the PDF directly: View PDF PDF.
Page Count: 805

DownloadThe JFree Chart Class Library Developer Guide V1 0 9
Open PDF In BrowserView PDF
The JFreeChart Class Library
Version 1.0.9

Developer Guide
Written by David Gilbert
January 7, 2008
c 2000-2008, Object Refinery Limited. All rights reserved.

IMPORTANT NOTICE:
We work hard to make this document as accurate and informative as we can, but
cannot guarantee that it is error-free.

Contents
1 Introduction
1.1 What is JFreeChart? . . . .
1.2 This Document . . . . . . .
1.3 Acknowledgements . . . . .
1.4 Comments and Suggestions

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

16
16
18
18
18

2 Sample Charts
2.1 Introduction . . . . . . . . . . .
2.2 Pie Charts . . . . . . . . . . . .
2.3 Bar Charts . . . . . . . . . . .
2.4 Line Chart . . . . . . . . . . .
2.5 XY Plots . . . . . . . . . . . .
2.6 Time Series Charts . . . . . . .
2.7 Histograms . . . . . . . . . . .
2.8 Area Charts . . . . . . . . . . .
2.9 Difference Chart . . . . . . . .
2.10 Step Chart . . . . . . . . . . .
2.11 Gantt Chart . . . . . . . . . . .
2.12 Multiple Axis Charts . . . . . .
2.13 Combined and Overlaid Charts
2.14 Future Development . . . . . .

.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.

19
19
19
21
23
24
25
26
27
27
29
30
31
32
33

3 Downloading and Installing JFreeChart
3.1 Introduction . . . . . . . . . . . . . . . . .
3.2 Download . . . . . . . . . . . . . . . . . .
3.3 Unpacking the Files . . . . . . . . . . . .
3.4 Running the Demonstration Applications
3.5 Configuring JFreeChart for use in IDEs .
3.6 Compiling the Source . . . . . . . . . . .
3.7 Generating the Javadoc Documentation .

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

34
34
34
34
35
36
36
36

.
.
.
.

4 Using JFreeChart
37
4.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
4.2 Creating Your First Chart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
5 Pie
5.1
5.2
5.3
5.4
5.5
5.6
5.7

Charts
Introduction . . . . . . . . . . .
Creating a Simple Pie Chart . .
Section Colours . . . . . . . . .
Section Outlines . . . . . . . .
Null, Zero and Negative Values
Section and Legend Labels . . .
Exploded Sections . . . . . . .

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

1

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

40
40
40
40
41
41
42
42

CONTENTS

5.8
5.9
6 Bar
6.1
6.2
6.3
6.4
6.5

2

3D Pie Charts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Multiple Pie Charts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

43
43

Charts
Introduction . . . . . . . . .
A Bar Chart . . . . . . . .
The ChartFactory Class . .
Simple Chart Customisation
Customising the Renderer .

45
45
45
48
48
49

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

7 Line Charts
51
7.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
7.2 A Line Chart Based On A Category Dataset . . . . . . . . . . . . . . . . . . . . . . 51
7.3 A Line Chart Based On An XYDataset . . . . . . . . . . . . . . . . . . . . . . . . . 56
8 Time Series Charts
61
8.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
8.2 Time Series Charts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
9 Customising Charts
9.1 Introduction . . .
9.2 Chart Attributes
9.3 Plot Attributes .
9.4 Axis Attributes .

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

67
67
67
69
70

10 Dynamic Charts
72
10.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
10.2 Background . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
10.3 The Demo Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
11 Tooltips
11.1 Overview . . . . . . .
11.2 Generating Tool Tips .
11.3 Collecting Tool Tips .
11.4 Displaying Tool Tips .
11.5 Disabling Tool Tips .
11.6 Customising Tool Tips

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

77
77
77
78
78
78
78

12 Item Labels
12.1 Introduction . . . . . . . . . . . . . . .
12.2 Displaying Item Labels . . . . . . . . .
12.3 Item Label Appearance . . . . . . . .
12.4 Item Label Positioning . . . . . . . . .
12.5 Customising the Item Label Text . . .
12.6 Example 1 - Values Above a Threshold
12.7 Example 2 - Displaying Percentages .

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

79
79
80
81
82
83
84
87

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

13 Multiple Axes and Datasets
91
13.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
13.2 An Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
13.3 Hints and Tips . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93

CONTENTS

3

14 Combined Charts
14.1 Introduction . . . . . . . . . . . .
14.2 Combined Domain Category Plot
14.3 Combined Range Category Plot .
14.4 Combined Domain XY Plot . . .
14.5 Combined Range XY Plot . . . .

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

15 Datasets and JDBC
15.1 Introduction . . . . . . .
15.2 About JDBC . . . . . .
15.3 Sample Data . . . . . .
15.4 PostgreSQL . . . . . . .
15.5 The JDBC Driver . . .
15.6 The Demo Applications

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

99
. 99
. 99
. 99
. 100
. 101
. 102

PDF
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

16 Exporting Charts to Acrobat
16.1 Introduction . . . . . . . . .
16.2 What is Acrobat PDF? . .
16.3 iText . . . . . . . . . . . . .
16.4 Graphics2D . . . . . . . . .
16.5 Getting Started . . . . . . .
16.6 The Application . . . . . .
16.7 Viewing the PDF File . . .
16.8 Unicode Characters . . . . .
17 Exporting Charts to SVG
17.1 Introduction . . . . . . .
17.2 Background . . . . . . .
17.3 A Sample Application .

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

94
94
94
95
96
97

103
103
103
103
103
104
104
108
108

Format
111
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111

18 Applets
114
18.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114
18.2 Issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114
18.3 A Sample Applet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
19 Servlets
19.1 Introduction . . . . . . . . . . . . .
19.2 A Simple Servlet . . . . . . . . . .
19.3 Compiling the Servlet . . . . . . .
19.4 Deploying the Servlet . . . . . . .
19.5 Embedding Charts in HTML Pages
19.6 Supporting Files . . . . . . . . . .
19.7 Deploying Servlets . . . . . . . . .

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

118
118
118
120
121
121
126
127

20 Miscellaneous
20.1 Introduction . . . . .
20.2 X11 / Headless Java
20.3 Java Server Pages . .
20.4 Loading Images . . .

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

129
129
129
129
129

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

21 Packages
130
21.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130

CONTENTS

22 Package: org.jfree.chart
22.1 Overview . . . . . . .
22.2 ChartColor . . . . . .
22.3 ChartFactory . . . . .
22.4 ChartFrame . . . . . .
22.5 ChartMouseEvent . .
22.6 ChartMouseListener .
22.7 ChartPanel . . . . . .
22.8 ChartRenderingInfo .
22.9 ChartUtilities . . . . .
22.10ClipPath . . . . . . . .
22.11DrawableLegendItem .
22.12Effect3D . . . . . . . .
22.13HashUtilities . . . . .
22.14JFreeChart . . . . . .
22.15LegendItem . . . . . .
22.16LegendItemCollection
22.17LegendItemSource . .
22.18LegendRenderingOrder
22.19PolarChartPanel . . .

4

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

131
131
131
131
134
135
136
136
141
142
144
144
144
145
145
150
152
153
154
154

23 Package: org.jfree.chart.annotations
23.1 Overview . . . . . . . . . . . . . . .
23.2 AbstractXYAnnotation . . . . . . .
23.3 CategoryAnnotation . . . . . . . . .
23.4 CategoryLineAnnotation . . . . . . .
23.5 CategoryPointerAnnotation . . . . .
23.6 CategoryTextAnnotation . . . . . . .
23.7 TextAnnotation . . . . . . . . . . . .
23.8 XYAnnotation . . . . . . . . . . . .
23.9 XYBoxAnnotation . . . . . . . . . .
23.10XYDrawableAnnotation . . . . . . .
23.11XYImageAnnotation . . . . . . . . .
23.12XYLineAnnotation . . . . . . . . . .
23.13XYPointerAnnotation . . . . . . . .
23.14XYPolygonAnnotation . . . . . . . .
23.15XYShapeAnnotation . . . . . . . . .
23.16XYTextAnnotation . . . . . . . . . .

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

155
155
155
157
157
159
161
162
164
165
166
167
168
169
171
173
174

24 Package: org.jfree.chart.axis
24.1 Overview . . . . . . . . . .
24.2 Axis . . . . . . . . . . . . .
24.3 AxisCollection . . . . . . .
24.4 AxisLocation . . . . . . . .
24.5 AxisSpace . . . . . . . . . .
24.6 AxisState . . . . . . . . . .
24.7 CategoryAnchor . . . . . .
24.8 CategoryAxis . . . . . . . .
24.9 CategoryAxis3D . . . . . .
24.10CategoryLabelPosition . . .
24.11CategoryLabelPositions . .
24.12CategoryLabelWidthType .
24.13CategoryTick . . . . . . . .
24.14ColorBar . . . . . . . . . .
24.15CompassFormat . . . . . . .

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

177
177
177
182
182
183
183
184
184
189
190
191
191
192
192
192

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

CONTENTS

24.16CyclicNumberAxis . . .
24.17DateAxis . . . . . . . .
24.18DateTickMarkPosition .
24.19DateTick . . . . . . . .
24.20DateTickUnit . . . . . .
24.21ExtendedCategoryAxis .
24.22LogAxis . . . . . . . . .
24.23LogarithmicAxis . . . .
24.24MarkerAxisBand . . . .
24.25ModuloAxis . . . . . . .
24.26MonthDateFormat . . .
24.27NumberAxis . . . . . . .
24.28NumberAxis3D . . . . .
24.29NumberTick . . . . . . .
24.30NumberTickUnit . . . .
24.31PeriodAxis . . . . . . .
24.32PeriodAxisLabelInfo . .
24.33QuarterDateFormat . .
24.34SegmentedTimeline . . .
24.35StandardTickUnitSource
24.36SubCategoryAxis . . . .
24.37SymbolAxis . . . . . . .
24.38Tick . . . . . . . . . . .
24.39TickType . . . . . . . .
24.40TickUnit . . . . . . . . .
24.41TickUnits . . . . . . . .
24.42TickUnitSource . . . . .
24.43Timeline . . . . . . . . .
24.44ValueAxis . . . . . . . .
24.45ValueTick . . . . . . . .

5

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

193
194
198
198
199
200
200
203
204
205
206
207
211
212
213
214
216
218
218
219
220
221
223
223
223
224
225
225
226
229

25 Package: org.jfree.chart.block
25.1 Introduction . . . . . . . . . .
25.2 AbstractBlock . . . . . . . . .
25.3 Arrangement . . . . . . . . .
25.4 Block . . . . . . . . . . . . .
25.5 BlockBorder . . . . . . . . . .
25.6 BlockContainer . . . . . . . .
25.7 BlockFrame . . . . . . . . . .
25.8 BlockParams . . . . . . . . .
25.9 BlockResult . . . . . . . . . .
25.10BorderArrangement . . . . .
25.11CenterArrangement . . . . .
25.12ColorBlock . . . . . . . . . .
25.13ColumnArrangement . . . . .
25.14EmptyBlock . . . . . . . . . .
25.15EntityBlockParams . . . . . .
25.16EntityBlockResult . . . . . .
25.17FlowArrangement . . . . . . .
25.18GridArrangement . . . . . . .
25.19LabelBlock . . . . . . . . . .
25.20LengthConstraintType . . . .
25.21LineBorder . . . . . . . . . .
25.22RectangleConstraint . . . . .

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

231
231
231
233
234
234
235
237
237
237
238
238
238
239
240
240
240
240
241
241
243
243
244

CONTENTS

26 Package: org.jfree.chart.editor
26.1 Introduction . . . . . . . . . .
26.2 ChartEditor . . . . . . . . . .
26.3 ChartEditorFactory . . . . .
26.4 ChartEditorManager . . . . .
26.5 DefaultAxisEditor . . . . . .
26.6 DefaultChartEditor . . . . . .
26.7 DefaultChartEditorFactory .
26.8 DefaultColorBarEditor . . . .
26.9 DefaultNumberAxisEditor . .
26.10DefaultPlotEditor . . . . . .
26.11DefaultTitleEditor . . . . . .
26.12PaletteChooserPanel . . . . .
26.13PaletteSample . . . . . . . . .

6

.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.

246
246
246
246
247
247
247
248
248
249
249
249
249
250

27 Package: org.jfree.chart.encoders
27.1 Introduction . . . . . . . . . . . .
27.2 EncoderUtil . . . . . . . . . . . .
27.3 ImageEncoderFactory . . . . . .
27.4 ImageEncoder . . . . . . . . . . .
27.5 ImageFormat . . . . . . . . . . .
27.6 KeyPointPNGEncoderAdapter .
27.7 SunJPEGEncoderAdapter . . . .
27.8 SunPNGEncoderAdapter . . . .

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

251
251
251
252
253
253
253
254
255

28 Package: org.jfree.chart.entity
28.1 Introduction . . . . . . . . . .
28.2 Background . . . . . . . . . .
28.3 CategoryItemEntity . . . . .
28.4 ChartEntity . . . . . . . . . .
28.5 ContourEntity . . . . . . . .
28.6 EntityCollection . . . . . . .
28.7 LegendItemEntity . . . . . .
28.8 PieSectionEntity . . . . . . .
28.9 StandardEntityCollection . .
28.10TickLabelEntity . . . . . . .
28.11XYAnnotationEntity . . . . .
28.12XYItemEntity . . . . . . . . .

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

256
256
256
256
258
258
259
259
260
260
261
262
262

29 Package: org.jfree.chart.event
29.1 Introduction . . . . . . . . . .
29.2 AxisChangeEvent . . . . . . .
29.3 AxisChangeListener . . . . .
29.4 ChartChangeEvent . . . . . .
29.5 ChartChangeEventType . . .
29.6 ChartChangeListener . . . . .
29.7 ChartProgressEvent . . . . .
29.8 ChartProgressListener . . . .
29.9 MarkerChangeEvent . . . . .
29.10MarkerChangeListener . . . .
29.11PlotChangeEvent . . . . . . .
29.12PlotChangeListener . . . . .
29.13RendererChangeEvent . . . .
29.14RendererChangeListener . . .
29.15TitleChangeEvent . . . . . .

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

263
263
263
263
264
264
265
265
266
266
267
267
268
268
268
269

.
.
.
.
.
.
.
.
.
.
.
.
.

CONTENTS

7

29.16TitleChangeListener . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 269
30 Package: org.jfree.chart.imagemap
30.1 Overview . . . . . . . . . . . . . . . . . . . .
30.2 DynamicDriveToolTipTagFragmentGenerator
30.3 ImageMapUtilities . . . . . . . . . . . . . . .
30.4 OverLIBToolTipTagFragmentGenerator . . .
30.5 StandardToolTipTagFragmentGenerator . . .
30.6 StandardURLTagFragmentGenerator . . . . .
30.7 ToolTipTagFragmentGenerator . . . . . . . .
30.8 URLTagFragmentGenerator . . . . . . . . . .

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

270
270
270
270
271
271
272
272
273

31 Package: org.jfree.chart.labels
31.1 Introduction . . . . . . . . . . . . . . . .
31.2 AbstractCategoryItemLabelGenerator .
31.3 AbstractPieItemLabelGenerator . . . . .
31.4 AbstractXYItemLabelGenerator . . . .
31.5 BoxAndWhiskerToolTipGenerator . . .
31.6 BoxAndWhiskerXYToolTipGenerator .
31.7 CategoryItemLabelGenerator . . . . . .
31.8 CategorySeriesLabelGenerator . . . . .
31.9 CategoryToolTipGenerator . . . . . . .
31.10ContourToolTipGenerator . . . . . . . .
31.11CustomXYToolTipGenerator . . . . . .
31.12HighLowItemLabelGenerator . . . . . .
31.13IntervalCategoryItemLabelGenerator . .
31.14IntervalCategoryToolTipGenerator . . .
31.15ItemLabelAnchor . . . . . . . . . . . . .
31.16ItemLabelPosition . . . . . . . . . . . .
31.17MultipleXYSeriesLabelGenerator . . . .
31.18PieSectionLabelGenerator . . . . . . . .
31.19PieToolTipGenerator . . . . . . . . . . .
31.20StandardCategoryItemLabelGenerator .
31.21StandardCategorySeriesLabelGenerator
31.22StandardCategoryToolTipGenerator . .
31.23StandardContourToolTipGenerator . . .
31.24StandardPieSectionLabelGenerator . . .
31.25StandardPieToolTipGenerator . . . . . .
31.26StandardXYItemLabelGenerator . . . .
31.27StandardXYSeriesLabelGenerator . . . .
31.28StandardXYToolTipGenerator . . . . .
31.29StandardXYZToolTipGenerator . . . . .
31.30SymbolicXYItemLabelGenerator . . . .
31.31XYItemLabelGenerator . . . . . . . . .
31.32XYSeriesLabelGenerator . . . . . . . . .
31.33XYToolTipGenerator . . . . . . . . . . .
31.34XYZToolTipGenerator . . . . . . . . . .

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

274
274
274
275
276
278
278
278
279
279
280
280
280
281
282
282
283
284
285
286
286
287
288
289
289
291
292
293
294
295
296
296
296
297
297

32 Package: org.jfree.chart.needle
32.1 Overview . . . . . . . . . . .
32.2 ArrowNeedle . . . . . . . . .
32.3 LineNeedle . . . . . . . . . .
32.4 LongNeedle . . . . . . . . . .
32.5 MeterNeedle . . . . . . . . . .
32.6 PinNeedle . . . . . . . . . . .

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

299
299
299
300
300
300
301

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

CONTENTS

32.7 PlumNeedle .
32.8 PointerNeedle
32.9 ShipNeedle .
32.10WindNeedle .

8

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

301
302
302
302

33 Package: org.jfree.chart.plot
33.1 Overview . . . . . . . . . . . .
33.2 CategoryMarker . . . . . . . .
33.3 CategoryPlot . . . . . . . . . .
33.4 ColorPalette . . . . . . . . . . .
33.5 CombinedDomainCategoryPlot
33.6 CombinedDomainXYPlot . . .
33.7 CombinedRangeCategoryPlot .
33.8 CombinedRangeXYPlot . . . .
33.9 CompassPlot . . . . . . . . . .
33.10ContourPlot . . . . . . . . . . .
33.11ContourPlotUtilities . . . . . .
33.12ContourValuePlot . . . . . . .
33.13CrosshairState . . . . . . . . .
33.14DatasetRenderingOrder . . . .
33.15DefaultDrawingSupplier . . . .
33.16DialShape . . . . . . . . . . . .
33.17DrawingSupplier . . . . . . . .
33.18FastScatterPlot . . . . . . . . .
33.19GreyPalette . . . . . . . . . . .
33.20IntervalMarker . . . . . . . . .
33.21Marker . . . . . . . . . . . . . .
33.22MeterInterval . . . . . . . . . .
33.23MeterPlot . . . . . . . . . . . .
33.24MultiplePiePlot . . . . . . . . .
33.25PieLabelDistributor . . . . . .
33.26PieLabelRecord . . . . . . . . .
33.27PiePlot . . . . . . . . . . . . .
33.28PiePlot3D . . . . . . . . . . . .
33.29PiePlotState . . . . . . . . . . .
33.30Plot . . . . . . . . . . . . . . .
33.31PlotOrientation . . . . . . . . .
33.32PlotRenderingInfo . . . . . . .
33.33PlotState . . . . . . . . . . . .
33.34PlotUtilities . . . . . . . . . . .
33.35PolarPlot . . . . . . . . . . . .
33.36RainbowPalette . . . . . . . . .
33.37RingPlot . . . . . . . . . . . . .
33.38SeriesRenderingOrder . . . . .
33.39SpiderWebPlot . . . . . . . . .
33.40ThermometerPlot . . . . . . . .
33.41ValueAxisPlot . . . . . . . . . .
33.42ValueMarker . . . . . . . . . .
33.43WaferMapPlot . . . . . . . . .
33.44XYPlot . . . . . . . . . . . . .
33.45Zoomable . . . . . . . . . . . .

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

304
304
304
306
311
312
313
315
316
317
320
321
321
321
321
322
323
324
325
328
328
330
334
335
339
342
342
342
354
356
356
361
361
363
363
363
368
368
370
370
375
382
382
383
383
393

CONTENTS

9

34 Package: org.jfree.chart.plot.dial
34.1 Overview . . . . . . . . . . . . .
34.2 AbstractDialLayer . . . . . . . .
34.3 ArcDialFrame . . . . . . . . . . .
34.4 DialBackground . . . . . . . . . .
34.5 DialCap . . . . . . . . . . . . . .
34.6 DialFrame . . . . . . . . . . . . .
34.7 DialLayer . . . . . . . . . . . . .
34.8 DialLayerChangeEvent . . . . . .
34.9 DialLayerChangeListener . . . .
34.10DialPlot . . . . . . . . . . . . . .
34.11DialPointer . . . . . . . . . . . .
34.12DialPointer.Pin . . . . . . . . . .
34.13DialPointer.Pointer . . . . . . . .
34.14DialScale . . . . . . . . . . . . .
34.15DialTextAnnotation . . . . . . .
34.16DialValueIndicator . . . . . . . .
34.17SimpleDialFrame . . . . . . . . .
34.18StandardDialRange . . . . . . . .
34.19StandardDialScale . . . . . . . .

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

395
395
395
397
398
399
401
401
402
403
403
406
407
408
409
410
411
414
415
417

35 Package: org.jfree.chart.renderer
35.1 Overview . . . . . . . . . . . . .
35.2 AbstractRenderer . . . . . . . . .
35.3 AreaRendererEndType . . . . . .
35.4 DefaultPolarItemRenderer . . . .
35.5 GrayPaintScale . . . . . . . . . .
35.6 LookupPaintScale . . . . . . . . .
35.7 NotOutlierException . . . . . . .
35.8 Outlier . . . . . . . . . . . . . . .
35.9 OutlierList . . . . . . . . . . . .
35.10OutlierListCollection . . . . . . .
35.11PaintScale . . . . . . . . . . . . .
35.12PolarItemRenderer . . . . . . . .
35.13RendererState . . . . . . . . . . .
35.14WaferMapRenderer . . . . . . . .

.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.

421
421
421
440
440
441
442
443
443
444
444
444
445
446
446

36 Package: org.jfree.chart.renderer.category
36.1 Overview . . . . . . . . . . . . . . . . . . .
36.2 AbstractCategoryItemRenderer . . . . . . .
36.3 AreaRenderer . . . . . . . . . . . . . . . . .
36.4 BarRenderer . . . . . . . . . . . . . . . . .
36.5 BarRenderer3D . . . . . . . . . . . . . . . .
36.6 BoxAndWhiskerRenderer . . . . . . . . . .
36.7 CategoryItemRenderer . . . . . . . . . . . .
36.8 CategoryItemRendererState . . . . . . . . .
36.9 CategoryStepRenderer . . . . . . . . . . . .
36.10DefaultCategoryItemRenderer . . . . . . . .
36.11GanttRenderer . . . . . . . . . . . . . . . .
36.12GroupedStackedBarRenderer . . . . . . . .
36.13IntervalBarRenderer . . . . . . . . . . . . .
36.14LayeredBarRenderer . . . . . . . . . . . . .
36.15LevelRenderer . . . . . . . . . . . . . . . . .
36.16LineAndShapeRenderer . . . . . . . . . . .
36.17LineRenderer3D . . . . . . . . . . . . . . .

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

447
447
447
451
452
457
459
460
470
471
473
473
474
475
476
477
479
483

CONTENTS

10

36.18MinMaxCategoryRenderer . . . .
36.19ScatterRenderer . . . . . . . . . .
36.20StackedAreaRenderer . . . . . . .
36.21StackedBarRenderer . . . . . . .
36.22StackedBarRenderer3D . . . . . .
36.23StatisticalBarRenderer . . . . . .
36.24StatisticalLineAndShapeRenderer
36.25WaterfallBarRenderer . . . . . .

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

485
487
490
490
492
494
495
497

37 Package: org.jfree.chart.renderer.xy
37.1 Overview . . . . . . . . . . . . . . .
37.2 AbstractXYItemRenderer . . . . . .
37.3 CandlestickRenderer . . . . . . . . .
37.4 ClusteredXYBarRenderer . . . . . .
37.5 CyclicXYItemRenderer . . . . . . . .
37.6 DefaultXYItemRenderer . . . . . . .
37.7 DeviationRenderer . . . . . . . . . .
37.8 HighLowRenderer . . . . . . . . . .
37.9 StackedXYAreaRenderer . . . . . . .
37.10StackedXYAreaRenderer2 . . . . . .
37.11StackedXYBarRenderer . . . . . . .
37.12StandardXYItemRenderer . . . . . .
37.13VectorRenderer . . . . . . . . . . . .
37.14WindItemRenderer . . . . . . . . . .
37.15XYAreaRenderer . . . . . . . . . . .
37.16XYBarRenderer . . . . . . . . . . . .
37.17XYBlockRenderer . . . . . . . . . .
37.18XYBoxAndWhiskerRenderer . . . .
37.19XYBubbleRenderer . . . . . . . . . .
37.20XYDifferenceRenderer . . . . . . . .
37.21XYDotRenderer . . . . . . . . . . .
37.22XYErrorRenderer . . . . . . . . . . .
37.23XYItemRenderer . . . . . . . . . . .
37.24XYItemRendererState . . . . . . . .
37.25XYLineAndShapeRenderer . . . . .
37.26XYSplineRenderer . . . . . . . . . .
37.27XYStepRenderer . . . . . . . . . . .
37.28XYStepAreaRenderer . . . . . . . .
37.29YIntervalRenderer . . . . . . . . . .

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

500
500
500
505
508
509
510
510
512
513
515
516
518
521
523
523
525
527
529
530
532
534
535
537
547
548
554
556
557
558

38 Package: org.jfree.chart.servlet
38.1 Overview . . . . . . . . . . . .
38.2 ChartDeleter . . . . . . . . . .
38.3 DisplayChart . . . . . . . . . .
38.4 ServletUtilities . . . . . . . . .

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

560
560
560
560
560

39 Package: org.jfree.chart.title
39.1 Overview . . . . . . . . . .
39.2 Events . . . . . . . . . . . .
39.3 CompositeTitle . . . . . . .
39.4 DateTitle . . . . . . . . . .
39.5 ImageTitle . . . . . . . . . .
39.6 LegendGraphic . . . . . . .
39.7 LegendItemBlockContainer
39.8 LegendTitle . . . . . . . . .

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

562
562
562
562
563
564
564
566
567

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

CONTENTS

11

39.9 PaintScaleLegend . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 570
39.10TextTitle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 572
39.11Title . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 574
40 Package: org.jfree.chart.urls
40.1 Overview . . . . . . . . . . . . .
40.2 CategoryURLGenerator . . . . .
40.3 CustomPieURLGenerator . . . .
40.4 CustomXYURLGenerator . . . .
40.5 PieURLGenerator . . . . . . . .
40.6 StandardCategoryURLGenerator
40.7 StandardPieURLGenerator . . .
40.8 StandardXYURLGenerator . . .
40.9 StandardXYZURLGenerator . .
40.10TimeSeriesURLGenerator . . . .
40.11URLUtilities . . . . . . . . . . .
40.12XYURLGenerator . . . . . . . .
40.13XYZURLGenerator . . . . . . . .

.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.

577
577
577
578
579
579
579
581
582
583
583
583
583
584

41 Package: org.jfree.chart.util
585
41.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 585
41.2 RelativeDateFormat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 585
42 Package: org.jfree.data
42.1 Introduction . . . . . . . . . .
42.2 ComparableObjectItem . . .
42.3 ComparableObjectSeries . . .
42.4 DataUtilities . . . . . . . . .
42.5 DefaultKeyedValue . . . . . .
42.6 DefaultKeyedValues . . . . .
42.7 DefaultKeyedValues2D . . . .
42.8 DomainInfo . . . . . . . . . .
42.9 DomainOrder . . . . . . . . .
42.10KeyedObject . . . . . . . . .
42.11KeyedObjects . . . . . . . . .
42.12KeyedObjects2D . . . . . . .
42.13KeyedValue . . . . . . . . . .
42.14KeyedValueComparator . . .
42.15KeyedValueComparatorType
42.16KeyedValues . . . . . . . . .
42.17KeyedValues2D . . . . . . . .
42.18KeyToGroupMap . . . . . . .
42.19Range . . . . . . . . . . . . .
42.20RangeInfo . . . . . . . . . . .
42.21RangeType . . . . . . . . . .
42.22UnknownKeyException . . .
42.23Value . . . . . . . . . . . . .
42.24Values . . . . . . . . . . . . .
42.25Values2D . . . . . . . . . . .

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

588
588
588
589
590
591
592
594
596
596
597
597
599
601
601
601
602
602
603
604
606
606
607
607
607
608

CONTENTS

12

43 Package: org.jfree.data.category
43.1 Introduction . . . . . . . . . . .
43.2 CategoryDataset . . . . . . . .
43.3 CategoryToPieDataset . . . . .
43.4 DefaultCategoryDataset . . . .
43.5 DefaultIntervalCategoryDataset
43.6 IntervalCategoryDataset . . . .

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

609
609
609
609
611
613
616

44 Package: org.jfree.data.contour
44.1 Introduction . . . . . . . . . . .
44.2 ContourDataset . . . . . . . . .
44.3 DefaultContourDataset . . . .
44.4 NonGridContourDataset . . . .

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

617
617
617
618
618

45 Package: org.jfree.data.function
45.1 Introduction . . . . . . . . . . .
45.2 Function2D . . . . . . . . . . .
45.3 LineFunction2D . . . . . . . . .
45.4 NormalDistributionFunction2D
45.5 PowerFunction2D . . . . . . . .

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

619
619
619
619
620
621

46 Package: org.jfree.data.gantt
46.1 Introduction . . . . . . . . .
46.2 GanttCategoryDataset . . .
46.3 Task . . . . . . . . . . . . .
46.4 TaskSeries . . . . . . . . . .
46.5 TaskSeriesCollection . . . .

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

622
622
622
623
624
625

47 Package: org.jfree.data.general
47.1 Introduction . . . . . . . . . . .
47.2 AbstractDataset . . . . . . . .
47.3 AbstractSeriesDataset . . . . .
47.4 CombinationDataset . . . . . .
47.5 CombinedDataset . . . . . . . .
47.6 Dataset . . . . . . . . . . . . .
47.7 DatasetChangeEvent . . . . . .
47.8 DatasetChangeListener . . . . .
47.9 DatasetGroup . . . . . . . . . .
47.10DatasetUtilities . . . . . . . . .
47.11DefaultKeyedValueDataset . .
47.12DefaultKeyedValuesDataset . .
47.13DefaultKeyedValues2DDataset
47.14DefaultPieDataset . . . . . . .
47.15DefaultValueDataset . . . . . .
47.16KeyedValueDataset . . . . . . .
47.17KeyedValuesDataset . . . . . .
47.18KeyedValues2DDataset . . . .
47.19PieDataset . . . . . . . . . . .
47.20Series . . . . . . . . . . . . . .
47.21SeriesChangeEvent . . . . . . .
47.22SeriesChangeListener . . . . . .
47.23SeriesDataset . . . . . . . . . .
47.24SeriesException . . . . . . . . .
47.25SubSeriesDataset . . . . . . . .
47.26ValueDataset . . . . . . . . . .

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

628
628
628
629
630
630
630
631
631
631
632
636
636
636
636
638
638
639
639
639
640
642
642
642
643
643
643

.
.
.
.
.

CONTENTS

13

47.27WaferMapDataset . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 644
48 Package: org.jfree.data.io
645
48.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 645
48.2 CSV . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 645
49 Package: org.jfree.data.jdbc
49.1 Introduction . . . . . . . . .
49.2 JDBCCategoryDataset . . .
49.3 JDBCPieDataset . . . . . .
49.4 JDBCXYDataset . . . . . .

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

646
646
646
647
647

50 Package: org.jfree.data.statistics
50.1 Introduction . . . . . . . . . . . . . . . .
50.2 BoxAndWhiskerCalculator . . . . . . . .
50.3 BoxAndWhiskerCategoryDataset . . . .
50.4 BoxAndWhiskerItem . . . . . . . . . . .
50.5 BoxAndWhiskerXYDataset . . . . . . .
50.6 DefaultBoxAndWhiskerCategoryDataset
50.7 DefaultBoxAndWhiskerXYDataset . . .
50.8 DefaultMultiValueCategoryDataset . . .
50.9 DefaultStatisticalCategoryDataset . . .
50.10HistogramBin . . . . . . . . . . . . . . .
50.11HistogramDataset . . . . . . . . . . . .
50.12HistogramType . . . . . . . . . . . . . .
50.13MeanAndStandardDeviation . . . . . . .
50.14MultiValueCategoryDataset . . . . . . .
50.15Regression . . . . . . . . . . . . . . . . .
50.16SimpleHistogramBin . . . . . . . . . . .
50.17SimpleHistogramDataset . . . . . . . . .
50.18StatisticalCategoryDataset . . . . . . . .
50.19Statistics . . . . . . . . . . . . . . . . .

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

649
649
649
650
651
652
653
656
658
660
662
663
665
666
666
667
668
669
671
671

51 Package: org.jfree.data.time
51.1 Introduction . . . . . . . . . .
51.2 DateRange . . . . . . . . . .
51.3 Day . . . . . . . . . . . . . .
51.4 DynamicTimeSeriesCollection
51.5 FixedMillisecond . . . . . . .
51.6 Hour . . . . . . . . . . . . . .
51.7 Millisecond . . . . . . . . . .
51.8 Minute . . . . . . . . . . . . .
51.9 Month . . . . . . . . . . . . .
51.10MovingAverage . . . . . . . .
51.11Quarter . . . . . . . . . . . .
51.12RegularTimePeriod . . . . . .
51.13Second . . . . . . . . . . . . .
51.14SimpleTimePeriod . . . . . .
51.15TimePeriod . . . . . . . . . .
51.16TimePeriodAnchor . . . . . .
51.17TimePeriodFormatException
51.18TimePeriodValue . . . . . . .
51.19TimePeriodValues . . . . . .
51.20TimePeriodValuesCollection .
51.21TimeSeries . . . . . . . . . .

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

674
674
674
674
676
678
678
679
680
681
682
683
684
686
687
687
688
688
688
689
691
693

.
.
.
.

.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

CONTENTS

51.22TimeSeriesCollection .
51.23TimeSeriesDataItem .
51.24TimeSeriesTableModel
51.25TimeTableXYDataset
51.26Week . . . . . . . . . .
51.27Year . . . . . . . . . .

14

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

698
701
702
702
704
705

52 Package: org.jfree.data.time.ohlc
52.1 Introduction . . . . . . . . . . . .
52.2 OHLC . . . . . . . . . . . . . . .
52.3 OHLCItem . . . . . . . . . . . .
52.4 OHLCSeries . . . . . . . . . . . .
52.5 OHLCSeriesCollection . . . . . .

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

707
707
707
708
709
709

53 Package: org.jfree.data.xml
53.1 Introduction . . . . . . . .
53.2 Usage . . . . . . . . . . .
53.3 CategoryDatasetHandler .
53.4 CategorySeriesHandler . .
53.5 DatasetReader . . . . . .
53.6 DatasetTags . . . . . . . .
53.7 ItemHandler . . . . . . . .
53.8 KeyHandler . . . . . . . .
53.9 PieDatasetHandler . . . .
53.10RootHandler . . . . . . .
53.11ValueHandler . . . . . . .

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

712
712
712
712
713
713
713
714
714
714
715
715

54 Package: org.jfree.data.xy
54.1 Introduction . . . . . . . . .
54.2 AbstractIntervalXYDataset
54.3 AbstractXYDataset . . . .
54.4 AbstractXYZDataset . . . .
54.5 CategoryTableXYDataset .
54.6 DefaultHighLowDataset . .
54.7 DefaultIntervalXYDataset .
54.8 DefaultOHLCDataset . . .
54.9 DefaultTableXYDataset . .
54.10DefaultWindDataset . . . .
54.11DefaultXYDataset . . . . .
54.12DefaultXYZDataset . . . .
54.13IntervalXYDataset . . . . .
54.14IntervalXYDelegate . . . . .
54.15IntervalXYZDataset . . . .
54.16MatrixSeries . . . . . . . . .
54.17MatrixSeriesCollection . . .
54.18NormalizedMatrixSeries . .
54.19OHLCDataItem . . . . . . .
54.20OHLCDataset . . . . . . . .
54.21TableXYDataset . . . . . .
54.22Vector . . . . . . . . . . . .
54.23VectorDataItem . . . . . . .
54.24VectorSeries . . . . . . . . .
54.25VectorSeriesCollection . . .
54.26VectorXYDataset . . . . . .
54.27WindDataset . . . . . . . .

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

716
716
716
716
717
717
719
720
723
724
726
728
730
732
733
734
734
735
736
737
738
739
739
740
741
742
744
744

CONTENTS

15

54.28XisSymbolic . . . . . . . . .
54.29XYBarDataset . . . . . . .
54.30XYCoordinate . . . . . . .
54.31XYDataItem . . . . . . . .
54.32XYDataset . . . . . . . . .
54.33XYDatasetTableModel . . .
54.34XYInterval . . . . . . . . .
54.35XYIntervalDataItem . . . .
54.36XYIntervalSeries . . . . . .
54.37XYIntervalSeriesCollection
54.38XYSeries . . . . . . . . . .
54.39XYSeriesCollection . . . . .
54.40XYZDataset . . . . . . . . .
54.41YInterval . . . . . . . . . .
54.42YIntervalDataItem . . . . .
54.43YIntervalSeries . . . . . . .
54.44YIntervalSeriesCollection .
54.45YisSymbolic . . . . . . . . .

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

745
745
747
748
748
750
751
752
753
754
756
759
761
761
762
763
764
765

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

767
767
767
768
768
769
770
771
772
773
773
774

B JCommon
B.1 Introduction . . . . . . . . . . . . .
B.2 Align . . . . . . . . . . . . . . . . .
B.3 GradientPaintTransformer . . . . .
B.4 GradientPaintTransformType . . .
B.5 PublicCloneable . . . . . . . . . . .
B.6 RectangleAnchor . . . . . . . . . .
B.7 RectangleEdge . . . . . . . . . . .
B.8 RectangleInsets . . . . . . . . . . .
B.9 StandardGradientPaintTransformer
B.10 TextAnchor . . . . . . . . . . . . .
B.11 UnitType . . . . . . . . . . . . . .

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

775
775
775
776
776
776
777
777
777
779
781
781

A Migration
A.1 Introduction .
A.2 1.0.8 to 1.0.9
A.3 1.0.7 to 1.0.8
A.4 1.0.6 to 1.0.7
A.5 1.0.5 to 1.0.6
A.6 1.0.4 to 1.0.5
A.7 1.0.3 to 1.0.4
A.8 1.0.2 to 1.0.3
A.9 1.0.1 to 1.0.2
A.10 1.0.0 to 1.0.1
A.11 0.9.x to 1.0.0

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

C Configuring IDEs for JFreeChart
783
C.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 783
C.2 Eclipse . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 783
C.3 NetBeans . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 787
D The
D.1
D.2
D.3

GNU Lesser General Public Licence
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
The Licence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Frequently Asked Questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

790
790
790
796

Chapter 1

Introduction
1.1
1.1.1

What is JFreeChart?
Overview

JFreeChart is a free chart library for the Java(tm) platform. It is designed for use in applications,
applets, servlets and JSP. JFreeChart is distributed with complete source code subject to the terms
of the GNU Lesser General Public Licence, which permits JFreeChart to be used in proprietary or
free software applications (see Appendix D for details).
Dual Axis Chart
80
8.0

75

7.5

70

7.0

65

6.5

60

6.0

55

5.5

Value

45

4.5
4.0

40

3.5

35

3.0

30

2.5

25

2.0

20

1.5

15

1.0

10

0.5

5

0.0

0

Secondary

50

5.0

C

C

C

C

C

C

C

C

at

at

at

at

at

at

at

at

eg

eg

eg

eg

eg

eg

eg

eg

or

or

or

y

y

y

y

y

or

or

y

y

or

y

or

or

8

7

6

5

4

3

2

1

Category
S1

S2

S3

S4

Figure 1.1: A sample chart
Figure 1.1 shows a typical chart created using JFreeChart. Many more examples are shown in later
sections of this document.

1.1.2

Features

JFreeChart can generate pie charts, bar charts (regular and stacked, with an optional 3D-effect),
line charts, scatter plots, time series charts (including moving averages, high-low-open-close charts
and candlestick plots), Gantt charts, meter charts (dial, compass and thermometer), symbol charts,
wind plots, combination charts and more.
Additional features include:
16

CHAPTER 1. INTRODUCTION

17

• data is accessible from any implementation of the defined interfaces;
• export to PNG and JPEG image file formats (or you can use Java’s ImageIO library to export
to any format supported by ImageIO);
• export to any format with a Graphics2D implementation including:
– PDF via iText (http://www.lowagie.com/iText/);
– SVG via Batik (http://xml.apache.org/batik/);
• tool tips;
• interactive zooming;
• chart mouse events (these can be used for drill-down charts or information pop-ups);
• annotations;
• HTML image map generation;
• works in applications, servlets, JSP (thanks to the Cewolf project1 ) and applets;
• distributed with complete source code subject to the terms of the GNU Lesser General Public
License (LGPL);
JFreeChart is written entirely in Java, and should run on any implementation of the Java 2 platform
(JDK 1.3.1 or later). It will also work quite well with free runtimes based on GNU Classpath 0.92
or later.2

1.1.3

Home Page

The JFreeChart home page can be found at:
http://www.jfree.org/jfreechart/

Here you will find all the latest information about JFreeChart, including sample charts, download
links, Javadocs, a discussion forum and more.

1 See
2 See

http://cewolf.sourceforge.net for details.
http://www.gnu.org/software/classpath/ for details.

CHAPTER 1. INTRODUCTION

1.2

18

This Document

1.2.1

Versions

Two versions of this document are available:
• a free version, the “JFreeChart Installation Guide”, is available from the JFreeChart home
page, and contains chapters up to and including the instructions for installing JFreeChart and
running the demo;
• a premium version, the “JFreeChart Developer Guide”, is available only to those that have
paid for it, and includes additional tutorial chapters and reference documentation for the
JFreeChart classes.
If you wish to purchase the latter version, please visit the following site:
http://www.object-refinery.com/jfreechart/guide.html

We’d like to thank everyone that has supported JFreeChart in the past by purchasing the JFreeChart
Developer Guide!

1.2.2

Disclaimer

Please note that I have put in considerable effort to ensure that the information in this document
is up-to-date and accurate, but I cannot guarantee that it does not contain errors. You must use
this document at your own risk or not use it at all.

1.3

Acknowledgements

JFreeChart contains code and ideas from many people. At the risk of missing someone out, I would
like to thank the following people for contributing to the project:
Eric Alexander, Richard Atkinson, David Basten, David Berry, Chris Boek, Zoheb
Borbora, Anthony Boulestreau, Jeremy Bowman, Daniel Bridenbecker, Nicolas Brodu,
Jody Brownell, David Browning, Søren Caspersen, Chuanhao Chiu, Brian Cole, Pascal Collet, Martin Cordova, Paolo Cova, Michael Duffy, Don Elliott, Rune Fausk,
Jonathan Gabbai, Serge V. Grachov, Daniel Gredler, Hans-Jurgen Greiner, Joao Guilherme Del Valle, Nick Guenther, Aiman Han, Cameron Hayne, Jon Iles, Wolfgang Irler,
Sergei Ivanov, Adrian Joubert, Darren Jung, Xun Kang, Bill Kelemen, Norbert Kiesel,
Gideon Krause, Pierre-Marie Le Biot, Arnaud Lelievre, Wolfgang Lenhard, David Li,
Yan Liu, Tin Luu, Craig MacFarlane, Achilleus Mantzios, Thomas Meier, Aaron Metzger, Jim Moore, Jonathan Nash, Barak Naveh, David M. O’Donnell, Krzysztof Paz,
Tomer Peretz, Xavier Poinsard, Andrzej Porebski, Luke Quinane, Viktor Rajewski, Eduardo Ramalho, Michael Rauch, Cameron Riley, Klaus Rheinwald, Dan Rivett, Scott
Sams, Michel Santos, Thierry Saura, Andreas Schneider, Jean-Luc Schwab, Bryan Scott,
Tobias Self, Mofeed Shahin, Pady Srinivasan, Greg Steckman, Roger Studner, Gerald
Struck, Irv Thomae, Eric Thomas, Rich Unger, Daniel van Enckevort, Laurence Vanhelsuwé, Sylvain Vieujot, Jelai Wang, Mark Watson, Alex Weber, Richard West, Matthew
Wright, Benoit Xhenseval, Christian W. Zuckschwerdt, Hari and Sam (oldman).

1.4

Comments and Suggestions

If you have any comments or suggestions regarding this document, please send e-mail to:
david.gilbert@object-refinery.com

Chapter 2

Sample Charts
2.1

Introduction

This section shows some sample charts created using JFreeChart. It is intended to give a reasonable
overview of the types of charts that JFreeChart can generate. For other examples, please run the
demo application included in the JFreeChart distribution:
java -jar jfreechart-1.0.9-demo.jar

The complete source code for the demo application is available to purchasers of the JFreeChart
Developer Guide.1

2.2

Pie Charts

JFreeChart can create pie charts using any data that conforms to the PieDataset interface. Figure
2.1 shows a simple pie chart.
Pie Chart Demo 1

Six

One
Five

Four

Two
Three

One

Two

Three

Four

Five

Six

Figure 2.1: A simple pie chart (see PieChartDemo1.java)

1 See

http://www.object-refinery.com/jfreechart/guide.html for details.

19

CHAPTER 2. SAMPLE CHARTS

20

Individual pie sections can be “exploded”, as shown in figure 2.2.
Pie Chart Demo 2

Six (15% percent)

One (34% percent)
Five (9% percent)

Four (14% percent)

Two (8% percent)

Three (21% percent)

One

Two

Three

Four

Five

Six

Figure 2.2: A pie chart with an “exploded” section (see PieChartDemo2.java)

You can also display pie charts with a 3D effect, as shown in figure 2.3.
Pie Chart 3D Demo 1
C/C++

Visual Basic

PHP
Java
Perl

Java

Visual Basic

C/C++

PHP

Perl

Figure 2.3: A pie chart drawn with a 3D effect (see PieChart3DDemo1.java)

At the current time it is not possible to explode sections of the 3D pie chart.

CHAPTER 2. SAMPLE CHARTS

2.3

21

Bar Charts

A range of bar charts can be created with JFreeChart, using any data that conforms to the
CategoryDataset interface. Figure 2.4 shows a bar chart with a vertical orientation.
Bar Chart Demo 1
8
7
6

Value

5
4
3
2
1
0

Ca

teg

ory

1
Ca

teg

ory

2
Ca

teg

ory

3
Ca

teg

ory

4
Ca

teg

ory

5

Category
First

Second

Third

Figure 2.4: A vertical bar chart (see BarChartDemo1.java)

Bar charts can be displayed with a 3D effect as shown in figure 2.5.
3D Bar Chart Demo
17.5
15.0
12.5
10.0

Value

7.5
5.0
2.5
0.0
-2.5
-5.0
-7.5
-10.0
-12.5

Ca

teg

ory

1
Ca

teg

ory

2
Ca

teg

ory

3
Ca

teg

ory

4

Category
Series 1

Series 2

Series 3

Series 4

Series 5

Series 6

Series 7

Series 8

Series 9

Figure 2.5: A bar chart with 3D effect (see BarChart3DDemo1.java)

CHAPTER 2. SAMPLE CHARTS

22

Another variation, the waterfall chart, is shown in figure 2.6.
Product Cost Breakdown
$3.51

30
$4.71

Cost Per Unit

25

$8.66

20

$32.64
15

10
$15.76
5

0
Labour

Administration

Marketing

Distribution

Total Expense

Expense Category

Figure 2.6: A waterfall chart (see WaterfallChartDemo1.java)

Bar charts can also be generated from time series data—for example, see figure 2.7:
State Executions - USA
Source: http://www.amnestyusa.org/abolish/listbyyear.do
100
90

Number of People

80
70
60
50
40
30
20
10
0
1976 1978 1980 1982 1984 1986 1988 1990 1992 1994 1996 1998 2000 2002 2004

Year
Executions

Figure 2.7: An XY bar chart (see XYBarChartDemo1.java)

CHAPTER 2. SAMPLE CHARTS

2.4

23

Line Chart

The line chart can be generated using the same CategoryDataset that is used for the bar charts—
figure 2.8 shows an example.
Java Standard Class Library
Number of Classes By Release
3000
2800
2600
2400

Class Count

2200
2000
1800
1600
1400
1200
1000
800
600
400
200
0
JDK 1.0

JDK 1.1

SDK 1.2

SDK 1.3

SDK 1.4

Release
Source: Java In A Nutshell (4th Edition) by David Flanagan (O'Reilly)

Figure 2.8: A line chart (see LineChartDemo1.java)

CHAPTER 2. SAMPLE CHARTS

2.5

24

XY Plots

A third type of dataset, the XYDataset, is used to generate a range of chart types.
The standard XY plot has numerical x and y axes. By default, lines are drawn between each data
point—see figure 2.9.
Line Chart Demo 4
2.00
1.75
1.50
1.25
1.00
0.75
0.50

Y

0.25
0.00
-0.25
-0.50
-0.75
-1.00
-1.25
-1.50
-1.75
-2.00
-10

-9

-8

-7

-6

-5

-4

-3

-2

-1

0

1

2

3

4

5

6

7

8

9

X
y = cosine(x)

y = 2*sine(x)

Figure 2.9: A line chart (see LineChartDemo4.java)

Scatter plots can be drawn by drawing a shape at each data point, rather than connecting the
points with lines—an example is shown in figure 2.10.
Scatter Plot Demo 1
900
800
700
600
500
400
300
200

Y

100
0
-100
-200
-300
-400
-500
-600
-700
-800
-100

-75

-50

-25

0

25

50

75

X
Sample 0

Sample 1

Sample 2

Sample 3

Figure 2.10: A scatter plot (see ScatterPlotDemo1.java)

100

CHAPTER 2. SAMPLE CHARTS

2.6

25

Time Series Charts

JFreeChart supports time series charts, as shown in figure 2.11.
Legal & General Unit Trust Prices
185
180
175
170
165
160

Price Per Unit

155
150
145
140
135
130
125
120
115
110
105
100
Mar-2001 May-2001

Jul-2001

Sep-2001

Nov-2001

Jan-2002

Mar-2002 May-2002

Jul-2002

Date
L&G European Index Trust

L&G UK Index Trust

Figure 2.11: A time series chart (see TimeSeriesDemo1.java)

It is straightforward to add a moving average line to a time series chart—see figure 2.12 for an
example.
Time Series Demo 8
1.68
1.67
1.66
1.65
1.64

Value

1.63
1.62
1.61
1.60
1.59
1.58
1.57
1.56
Jan-2001

Mar-2001

May-2001

Jul-2001

Sep-2001

Nov-2001

Date
EUR/GBP

30 day moving average

Figure 2.12: A time series chart with a moving average (see TimeSeriesDemo8.java)

CHAPTER 2. SAMPLE CHARTS

26

Using an OHLCDataset (an extension of XYDataset) you can display high-low-open-close data, see
figure 2.13 for an example.
OHLC Demo 2
65
60
55
50
45

Value

40
35
30
25
20
15
10
5
0
7-Jan

14-Jan

21-Jan

28-Jan

4-Feb

11-Feb

18-Feb

Time
Series 1

Series 1-MAVG

Figure 2.13: A high-low-open-close chart (see HighLowChartDemo2.java)

2.7

Histograms

Histograms can be generated using an IntervalXYDataset (another extension of XYDataset), see
figure 2.14 for an example.
Histogram Demo
32.5
30.0
27.5
25.0
22.5
20.0
17.5
15.0
12.5
10.0
7.5
5.0
2.5
0.0
2.0

2.5

3.0

3.5

4.0

4.5

5.0

5.5

H1

6.0

6.5

7.0

7.5

8.0

8.5

9.0

9.5

H2

Figure 2.14: A histogram (see HistogramDemo1.java)

10.0

CHAPTER 2. SAMPLE CHARTS

2.8

27

Area Charts

You can generate an area chart for data in a CategoryDataset or an XYDataset. Figure 2.15 shows
an example.
XY Area Chart Demo
800
700
600
500
400
300

Range (Y)

200
100
0
-100
-200
-300
-400
-500
-600

Test

-700
-800
1.0

1.5

2.0

2.5

3.0

3.5

4.0

4.5

5.0

5.5

6.0

6.5

7.0

7.5

8.0

Domain (X)
Random 1

Random 2

Figure 2.15: An area chart (see XYAreaChartDemo1.java)

JFreeChart also supports the creation of stacked area charts as shown in figure 2.16.
Stacked XY Area Chart Demo 1
32.5
30.0
27.5
25.0
22.5

Y Value

20.0
17.5
15.0
12.5
10.0
7.5
5.0
2.5
0.0
5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

X Value
Series 1

Series 2

Figure 2.16: A stacked area chart (see StackedXYAreaChartDemo1.java)

2.9

Difference Chart

A difference chart highlights the difference between two series (see figure 2.17).
A second example, shown in figure 2.18 shows how a date axis can be used for the range values.

CHAPTER 2. SAMPLE CHARTS

28

Difference Chart Demo 1
3.0
2.5
2.0
1.5

Value

1.0
0.5
0.0
-0.5
-1.0
-1.5
-2.0
-2.5

Aug-2006

Sep-2006

Oct-2006

Nov-2006

Dec-2006

Jan-2007

Feb-2007

Time
Random 1

Random 2

Figure 2.17: A difference chart (see DifferenceChartDemo1.java)

Daylight Hours - London, UK
Data source: http://www.sunrisesunset.com/

22:00
20:00
18:00

Time

16:00
14:00
12:00
10:00
08:00
06:00
04:00
British Summer Time
Feb-2004

Apr-2004

Jun-2004

Aug-2004

Oct-2004

Dec-2004

Time
Sunrise

Sunset

Figure 2.18: A difference chart with times on the range axis (see DifferenceChartDemo2.java)

CHAPTER 2. SAMPLE CHARTS

2.10

29

Step Chart

A step chart displays numerical data as a sequence of “steps”—an example is shown in figure 2.19.
XYStepRenderer Demo 1
9.0
8.5
8.0
7.5
7.0
6.5
6.0

Y

5.5
5.0
4.5
4.0
3.5
3.0
2.5
2.0
1.5
1.0
0.5
0.0
1.0

1.5

2.0

2.5

3.0

3.5

4.0

4.5

5.0

5.5

X
Series 1

Series 2

Figure 2.19: A step chart (see XYStepRendererDemo1.java)

Step charts are generated from data in an XYDataset.

6.0

CHAPTER 2. SAMPLE CHARTS

2.11

30

Gantt Chart

Gantt charts can be generated using data from an IntervalCategoryDataset, as shown in figure
2.20.
Gantt Chart Demo
Date
May-2001

Jul-2001

Sep-2001

Nov-2001

Write Proposal
Obtain Approval
Requirements Analysis
Design Phase

Task

Design Signoff
Alpha Implementation
Design Review
Revised Design Signoff
Beta Implementation
Testing
Final Implementation
Signoff

Scheduled

Actual

Figure 2.20: A Gantt chart (see GanttChartDemo1.java)

Another example, showing subtasks and progress indicators, is shown in figure 2.21.
Gantt Chart Demo
Date
May-2001

Jul-2001

Sep-2001

Nov-2001

Write Proposal
Obtain Approval
Requirements Analysis
Design Phase

Task

Design Signoff
Alpha Implementation
Design Review
Revised Design Signoff
Beta Implementation
Testing
Final Implementation
Signoff

Scheduled

Figure 2.21: A Gantt chart with progress indicators (see GanttChartDemo2.java)

CHAPTER 2. SAMPLE CHARTS

2.12

31

Multiple Axis Charts

JFreeChart has support for charts with multiple axes. Figure 2.22 shows a price-volume chart that
demonstrates this feature.
Eurodollar Futures Contract (MAR03)
750,000

98.50
98.25

700,000

98.00

650,000

97.75

600,000

97.50

550,000

97.25
500,000

96.75

450,000

96.50

400,000

96.25

350,000

96.00

Volume

Price

97.00

300,000

95.75

250,000

95.50
95.25

200,000

95.00

150,000

94.75

100,000

94.50

50,000

94.25
Jan-2002

Mar-2002

May-2002

Jul-2002

Sep-2002

0
Nov-2002

Date
Price

Volume

Figure 2.22: A price-volume chart (see PriceVolumeDemo1.java)

This feature is supported by the CategoryPlot and XYPlot classes. Figure 2.23 shows an example
with four range axes.
Multiple Axis Demo 1
Four datasets and four range axes.
110

1,300

Range Axis 2

1,000
950

27.5

100

11,000

25.0

95

10,000

22.5

9,000

90

8,000
85

7,000

80

6,000

75

5,000

900

70

850

65

800

60

4,000
3,000

11:00

11:30

12:00

12:30

13:00

13:30

20.0
17.5
15.0
12.5

Range Axis 4

1,050

30.0

12,000

Range Axis 3

1,100

Primary Range Axis

1,200
1,150

13,000
105

1,250

10.0
7.5

2,000

5.0

1,000

2.5

0

0.0

14:00

Time of Day
Series 1

Series 2

Series 3

Series 4

Figure 2.23: A chart with multiple axes (see MultipleAxisDemo1.java)

CHAPTER 2. SAMPLE CHARTS

2.13

32

Combined and Overlaid Charts

JFreeChart supports combined and overlaid charts. Figure 2.24 shows a line chart overlaid on top
of a bar chart.
Freshmeat Software Projects
By Programming Language
As at 5 March 2003
5000

100%

4500

90%

4000

80%
70%

SQL

Unix Shell

PHP

C#

10%

0

Ruby

20%

500
Python

30%

1000

Java

40%

1500

C++

50%

2000

Perl

60%

2500

C

3000

Percent

Projects

3500

0%

Language
Languages

Cumulative

Figure 2.24: An overlaid chart (see ParetoChartDemo1.java)

It is possible to combine several charts that share a common domain axis, as shown in figure 2.25.
Combined Domain Category Plot Demo
8
7

Value

6
5
4
3
2
1
0

Value

15
10
5
0
Type 1

Type 2

Type 3

Type 4

Type 5

Type 6

Type 7

Type 8

Category
First

Second

Third

Fourth

Figure 2.25: A chart with a combined domain (see CombinedCategoryPlotDemo1.java)

In a similar way, JFreeChart can combine several charts that share a common range axis, see figure
2.26.

CHAPTER 2. SAMPLE CHARTS

33

Combined (Range) XY Plot
18,000
17,000
16,000
15,000
14,000
13,000
12,000

Value

11,000
10,000
9,000
8,000
7,000
6,000
5,000
4,000
3,000
2,000
1,000
0
7-Mar

14-Mar

7-Mar

Date

14-Mar

Date
Series 1

Series 2

Figure 2.26: A chart with a combined range (see CombinedXYPlotDemo2.java)

2.14

Future Development

JFreeChart is free software,2 so anyone can extend it and add new features to it. Already, more than
80 developers from around the world have contributed code back to the JFreeChart project. It is
likely that many more chart types will be developed in the future as developers modify JFreeChart
to meet their requirements. Check the JFreeChart home page regularly for announcements and
other updates:
http://www.jfree.org/jfreechart/

And if you would like to contribute code to the project, please join in...

2 See

http://www.fsf.org

Chapter 3

Downloading and Installing
JFreeChart
3.1

Introduction

This section contains instructions for downloading, unpacking, and (optionally) recompiling JFreeChart. Also included are instructions for running the JFreeChart demonstration application, and
generating the Javadoc HTML files from the JFreeChart source code.

3.2

Download

You can download the latest version of JFreeChart from:
http://www.jfree.org/jfreechart/download/

There are two versions of the JFreeChart download:
File:

Description:

jfreechart-1.0.9.tar.gz
jfreechart-1.0.9.zip

JFreeChart for Linux/Unix.
JFreeChart for Windows.

The two files contain the same source code. The main difference is that all the text files in the zip
download have been recoded to have both carriage return and line-feed characters at the end of
each line.
JFreeChart uses the JCommon class library (currently version 1.0.12). The JCommon runtime jar
file is included in the JFreeChart download, but if you require the source code (recommended) then
you should also download JCommon from:
http://www.jfree.org/jcommon/

3.3

Unpacking the Files

After downloading JFreeChart, you need to unpack the files. You should move the download file to
a convenient directory—when you unpack JFreeChart, a new subdirectory (jfreechart-1.0.9) will
be created in the same location as the zip or tar.gz archive file.

3.3.1

Unpacking on Linux/Unix

To extract the files from the download on Linux/Unix, enter the following command:

34

CHAPTER 3. DOWNLOADING AND INSTALLING JFREECHART

35

tar xvzf jfreechart-1.0.9.tar.gz

This will extract all the source, run-time and documentation files for JFreeChart into a new directory
called jfreechart-1.0.9.

3.3.2

Unpacking on Windows

To extract the files from the download on Windows, you can use the jar utility. Enter the following
command:
jar -xvf jfreechart-1.0.9.zip

This will extract all the source, run-time and documentation files for JFreeChart into a new directory
called jfreechart-1.0.9.

3.3.3

The Files

The top-level directory (jfreechart-1.0.9) contains the files and directories listed in the following
table:
File/Directory:

Description:

README.txt
NEWS
ChangeLog
ant

Important information - read this first!
Project news.
A detailed log of changes made to JFreeChart.
A directory containing an Ant build.xml script. You can use
this script to rebuild JFreeChart from the source code included
in the distribution.
A directory containing several Checkstyle property files.
These define the coding conventions used in the JFreeChart
source code.
A directory containing source files for classes that are not part
of the standard JFreeChart API (yet). We would appreciate
feedback on this code. Please note that the API for these
classes is subject to change.
A directory containing the JFreeChart jar file, and other libraries used by JFreeChart.
A directory containing the source code for JFreeChart.
A directory containing the source code for the experimental
SWT code. Please note that the API for these classes is subject to change.
A directory containing the source code for the JFreeChart unit
tests.
A runnable jar file containing demo applications.
The JFreeChart licence (GNU LGPL).

checkstyle

experimental

lib
source
swt

tests
jfreechart-1.0.9-demo.jar
licence-LGPL.txt

You should spend some time familiarising yourself with the files included in the download. In
particular, you should always read the README.txt file.

3.4

Running the Demonstration Applications

A demonstration application is included in the distribution that shows a wide range of charts that
can be generated with JFreeChart . To run the demo, type the following command:
java -jar jfreechart-1.0.9-demo.jar

The source code for the demo application is not included in the JFreeChart distribution, but is
available to download separately when you purchase the JFreeChart Developer Guide.1
1 If you have purchased the guide and you want to download the demo source code, look for the file
jfreechart-1.0.9-demos.zip on the download page for the JFreeChart Developer Guide.

CHAPTER 3. DOWNLOADING AND INSTALLING JFREECHART

3.5

36

Configuring JFreeChart for use in IDEs

If, like most developers, you use an integrated development environment (IDE) such as Eclipse or
NetBeans for your Java development work, you’ll want to configure JFreeChart within that IDE.
The procedure for this is IDE-specific—refer to Appendix C for more details.

3.6

Compiling the Source

To recompile the JFreeChart classes, you can use the Ant build.xml file included in the distribution.
Change to the ant directory and type:
ant compile

This will recompile all the necessary source files and recreate the JFreeChart run-time jar file.
To run the script requires that you have Ant 1.5.1 (or later) installed on your system, to find out
more about Ant visit:
http://ant.apache.org/

It is possible to recompile JFreeChart without using Ant, but there are one or two “gotchas” that
you have to take special care to avoid:
• some JFreeChart classes (particularly resource bundles) are not referenced directly in the code,
and some compilers omit to compile them—this results in runtime errors or problems due to
missing class files;
• if you create your own JFreeChart jar file, you need to be sure to include the non-Java files
(resource bundle .properties files, gorilla.jpg, etc.).
In the end, it’s simpler to learn Ant and use the script included in the JFreeChart distribution.

3.7

Generating the Javadoc Documentation

The JFreeChart source code contains extensive Javadoc comments. You can use the javadoc tool
to generate HTML documentation files directly from the source code.
To generate the documentation, use the javadoc target in the Ant build.xml script:
ant javadoc

This will create a javadoc directory containing all the Javadoc HTML files, inside the main jfreechart-1.0.9
directory.

Chapter 4

Using JFreeChart
4.1

Overview

This section presents a simple introduction to JFreeChart, intended for new users of JFreeChart.

4.2
4.2.1

Creating Your First Chart
Overview

Creating charts with JFreeChart is a three step process. You need to:
• create a dataset containing the data to be displayed in the chart;
• create a JFreeChart object that will be responsible for drawing the chart;
• draw the chart to some output target (often, but not always, a panel on the screen);
To illustrate the process, we describe a sample application (First.java) that produces the pie chart
shown in figure 4.1.

Figure 4.1: A pie chart created using First.java
Each of the three steps outlined above is described, along with sample code, in the following sections.

4.2.2

The Data

Step one requires us to create a dataset for our chart. This can be done easily using the DefaultPieDataset
class, as follows:
37

CHAPTER 4. USING JFREECHART

38

// create a dataset...
DefaultPieDataset dataset = new DefaultPieDataset();
dataset.setValue("Category 1", 43.2);
dataset.setValue("Category 2", 27.9);
dataset.setValue("Category 3", 79.5);

Note that JFreeChart can create pie charts using data from any class that implements the PieDataset
interface. The DefaultPieDataset class (used above) provides a convenient implementation of this
interface, but you are free to develop an alternative dataset implementation if you want to.1

4.2.3

Creating a Pie Chart

Step two concerns how we will present the dataset created in the previous section. We need to
create a JFreeChart object that can draw a chart using the data from our pie dataset. We will use
the ChartFactory class, as follows:
// create a chart...
JFreeChart chart = ChartFactory.createPieChart(
"Sample Pie Chart",
dataset,
true,
// legend?
true,
// tooltips?
false
// URLs?
);

Notice how we have passed a reference to the dataset to the factory method. JFreeChart keeps a
reference to this dataset so that it can obtain data later on when it is drawing the chart.
The chart that we have created uses default settings for most attributes. There are many ways
to customise the appearance of charts created with JFreeChart, but in this example we will just
accept the defaults.

4.2.4

Displaying the Chart

The final step is to display the chart somewhere. JFreeChart is very flexible about where it draws
charts, thanks to its use of the Graphics2D class.
For now, let’s display the chart in a frame on the screen. The ChartFrame class contains the
machinery (a ChartPanel) required to display charts:
// create and display a frame...
ChartFrame frame = new ChartFrame("Test", chart);
frame.pack();
frame.setVisible(true);

And that’s all there is to it...

4.2.5

The Complete Program

Here is the complete program, so that you can see which packages you need to import and the order
of the code fragments given in the preceding sections:
import
import
import
import

org.jfree.chart.ChartFactory;
org.jfree.chart.ChartFrame;
org.jfree.chart.JFreeChart;
org.jfree.data.general.DefaultPieDataset;

public class First {
/**
* The starting point for the demo.
*
* @param args ignored.
*/
public static void main(String[] args) {
1 This is similar in concept to the way that Swing’s JTable class obtains data via the TableModel interface. In
fact, this was the inspiration for using interfaces to define the datasets for JFreeChart.

CHAPTER 4. USING JFREECHART

39

// create a dataset...
DefaultPieDataset dataset = new DefaultPieDataset();
dataset.setValue("Category 1", 43.2);
dataset.setValue("Category 2", 27.9);
dataset.setValue("Category 3", 79.5);
// create a chart...
JFreeChart chart = ChartFactory.createPieChart(
"Sample Pie Chart",
dataset,
true,
// legend?
true,
// tooltips?
false
// URLs?
);
// create and display a frame...
ChartFrame frame = new ChartFrame("First", chart);
frame.pack();
frame.setVisible(true);
}
}

Hopefully this has convinced you that it is not difficult to create and display charts with JFreeChart.
Of course, there is much more to learn...

Chapter 5

Pie Charts
5.1

Introduction

This chapter provides information about using some of the standard features of the pie charts in
JFreeChart, including:
• controlling the color and outline of pie sections;
• handling of null and zero values;
• pie section labels (customising the text, altering the space allocated);
• “exploded” sections;
• multiple pie charts.
• displaying charts with a 3D effect;
In addition to this chapter, you should refer to the PiePlot reference documentation in section
33.27.

5.2

Creating a Simple Pie Chart

A step-by-step guide to creating a simple pie chart is included in the previous chapter 4.

5.3

Section Colours

Default fill colours for the pie sections are allocated automatically1 the first time a plot is rendered. If
you don’t like the default colours, you can set them yourself using the setSectionPaint(Comparable,
Paint) method. For example:
PiePlot plot = (PiePlot) chart.getPlot();
plot.setSectionPaint("Section A", new Color(200, 255, 255));
plot.setSectionPaint("Section B", new Color(200, 200, 255));

A demo that uses custom colours (PieChartDemo2.java) is included in the JFreeChart demo collection.
In addition to the per-series section colour attributes, there is also a base or default setting—for
more information, refer to the documentation for the PiePlot class (section 33.27).
1 Inside

the lookupSectionPaint(Comparable, boolean) method of the PiePlot class.

40

CHAPTER 5. PIE CHARTS

5.4

41

Section Outlines

Section outlines are drawn, by default, as a thin grey line around each pie section. The PiePlot
class provides options to:
• switch off the outlines completely;
• change the outlines for all sections by changing the default values;
• control the outline for particular pie sections independently;

5.4.1

Outline Visibility

To switch off the section outlines completely, use the following code:
PiePlot plot = (PiePlot) chart.getPlot();
plot.setSectionOutlinesVisible(false);

At any time, you can make the outlines visible again using:
plot.setSectionOutlinesVisible(true);

Calls to this method trigger a PlotChangeEvent, which will cause the chart to be repainted immediately if it is displayed in a ChartPanel.

5.4.2

Outline Appearance

When outlines are visible, you can change the colour and style of the outline for all pie sections
(using the base settings) or individual pie sections (using the per series settings).
At the base layer, a default setting is defined—this is used when no higher level settings have been
made. You can change the base settings with these methods in the PiePlot class:
public void setBaseSectionOutlinePaint(Paint paint);
public void setBaseSectionOutlineStroke(Stroke stroke);

Sometimes, you may prefer to set the outline paint and stroke on a “per series” basis, perhaps to
highlight a particular section in the chart. For this, you can use the series layer settings, defined
via these methods:
public void setSectionOutlinePaint(Comparable key, Paint paint);
public void setSectionOutlineStroke(Comparable key, Stroke stroke);

The first argument for each method is the section key from the dataset. If you set the value for a
section to null, the base layer setting will be used instead.

5.5

Null, Zero and Negative Values

A PieDataset can contain null, zero or negative values which are awkward or impossible to display
in a pie chart. Some special handling is built into the PiePlot class for these.
If a zero value is found in the dataset, the PiePlot class, by default, will place a label at the position
where the pie section would be displayed if it had a positive value and will also add an item to the
chart’s legend. If you prefer zero values to be ignored, you can set a flag for this, as follows:
PiePlot plot = (PiePlot) chart.getPlot();
plot.setIgnoreZeroValues(true);

A similar approach is taken for null values, which represent a missing or unknown value in the
dataset. The default handling is the same as for zero values, and if you prefer null values to be
ignored, you can set a flag as follows:
PiePlot plot = (PiePlot) chart.getPlot();
plot.setIgnoreNullValues(true);

There does not seem to be a sensible way to represent negative values in a pie chart, and JFreeChart
will always ignore them.

CHAPTER 5. PIE CHARTS

5.6

42

Section and Legend Labels

The text used for the section labels, both on the chart and in the chart’s legend, is fully customisable.
Default label generators are installed automatically, but if you need to you can change these with
the following methods:
public void setLabelGenerator(PieSectionLabelGenerator generator);
public void setLegendLabelGenerator(PieSectionLabelGenerator generator);

The StandardPieSectionLabelGenerator class is typically used as the generator, and provides enough
flexibility to handle most custom labelling requirements (but if not, you are free two write your
own class that implements the PieSectionLabelGenerator interface). The generator works by using
Java’s MessageFormat class to construct labels by substituting values that are derived from the
dataset—see table 5.1 for the available substitutions.
Key:

Value:

{0}
{1}
{2}

The section key as a String.
The section value.
The section value as a percentage of the total of all values in the dataset.

Figure 5.1: StandardPieSectionLabelGenerator substitutions
By way of example, suppose you have a PieDataset containing the following values:
Section Key:

Section Value:

S1
S2
S3
S4

3.0
5.0
null
2.0

Figure 5.2: A sample dataset
...then the following format strings would generate the labels shown:
Format String:

Section:

Generated Label:

{0}
{0} has value {1}
{0} ({2} percent)
{0} = {1}

0
1
0
2

S1
S2 has value 5.0
S1 (30 percent)
S3 = null

Figure 5.3: Format string examples
The PieChartDemo2.java application (included in the JFreeChart demo collection) shows a custom
label generator in use.

5.7

Exploded Sections

The PiePlot class supports the display of “exploded” sections, in which a pie section is offset from
the centre of the chart to highlight it. For example, the PieChartDemo2.java application creates the
chart shown in figure 5.6.
The amount by which a section is offset from the chart is specified as a percentage of the radius of
the pie chart, for example 0.30 (30 percent) is used in the example.
PiePlot plot = (PiePlot) chart.getPlot();
plot.setExplodePercent("Section A", 0.30);

To make space for the sections that are offset from the centre of the pie chart, the radius of the
main pie is reduced, so a pie chart with exploded sections will appear smaller than a pie chart with
no exploded sections.

CHAPTER 5. PIE CHARTS

43

Figure 5.4: A pie chart with an “exploded” section

5.8

3D Pie Charts

JFreeChart includes a PiePlot3D class that adds a pseudo-3D effect to pie charts—for example, see
figure 5.5. PiePlot3D is a subclass of PiePlot, so you can just substitute it when you create your
pie chart. Or if you construct your pie charts using the ChartFactory class, it is sufficient to call
the createPieChart3D() method instead of the createPieChart() method.

Figure 5.5: A 3D pie chart

There are some limitations with this class:
• exploded sections are not supported;
• it is not possible to set the angle of “rotation” for the 3D effect—if the plot is wider than it
is tall, the chart usually looks good, but if the plot is taller than it is wide, the 3D effect is a
little distorted.
Some demo applications (PieChart3DDemo1-3.java) are included in the JFreeChart demo collection.

5.9

Multiple Pie Charts

As a convenience, the MultiplePiePlot class enables you to create a single chart that displays
multiple pie plots using data from a CategoryDataset. An example is shown in figure 5.6.
The individual pie charts are created by “rubber stamping” a single pie chart multiple times. For
each rendering of the pie chart, a new PieDataset is extracted from the next row (or column) of the
CategoryDataset.

CHAPTER 5. PIE CHARTS

44

Figure 5.6: A chart using MultiplePiePlot

A number of demos (MultiplePieChartDemo1-4.java) are included in the JFreeChart demo collection.

Chapter 6

Bar Charts
6.1

Introduction

This chapter provides an introduction to creating bar charts with JFreeChart. We begin with a
very simple bar chart, then go on to describe some of the many options that JFreeChart provides
for customising the charts. After covering the standard bar chart and its options, we’ll move on to
some more complex bar chart variants:
• stacked bar charts;
• bar charts for time series data;
• histograms.
By the end of this chapter, you should have a good overview of the features that JFreeChart supports
for bar chart creation.

6.2
6.2.1

A Bar Chart
Overview

Bar charts are used to provide a visual representation of tabular data. For example, consider the
following table, which contains a simple set of data in two rows and three columns:

Row 1:
Row 2:

Column 1:

Column 2:

Column 3:

1.0
2.0

5.0
3.0

3.0
2.0

Figure 6.1: Sample data
In JFreeChart, this table is referred to as a dataset, each column heading is a category, and each
row in the table is a series. Each row heading is a series name (or series key). A bar chart that
presents this data is shown in figure 6.2.
You can see in the sample chart that JFreeChart groups the items from each column (category)
together, and uses colours to highlight the data from each row (series). The chart’s legend provides
the link between the bar colours and the series name/key.

6.2.2

Creating a Dataset

The first step in creating a bar chart is to create an appropriate dataset. The set of methods that
JFreeChart uses to access the tabular data for a bar chart is defined by the CategoryDataset interface.
45

CHAPTER 6. BAR CHARTS

46

Figure 6.2: A bar chart (see BarExample1.java)

This interface defines a read-only interface to the dataset, because that is all that JFreeChart
requires to draw charts. A dataset can, but is not required to, provide methods to update the
dataset.
A convenient class that implements this interface is the DefaultCategoryDataset class. Here is how
you might create a dataset for the values given in table 6.1:
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
dataset.addValue(1.0, "Row 1", "Column 1");
dataset.addValue(5.0, "Row 1", "Column 2");
dataset.addValue(3.0, "Row 1", "Column 3");
dataset.addValue(2.0, "Row 2", "Column 1");
dataset.addValue(3.0, "Row 2", "Column 2");
dataset.addValue(2.0, "Row 2", "Column 3");

6.2.3

Creating a Bar Chart

The next step is to create a JFreeChart instance that draws a bar chart for this example dataset.
Taking a short-cut, we use the ChartFactory class to create the JFreeChart instance:
JFreeChart chart = ChartFactory.createBarChart(
"Bar Chart Demo", // chart title
"Category", // domain axis label
"Value", // range axis label
dataset, // data
PlotOrientation.VERTICAL, // orientation
true, // include legend
true, // tooltips?
false // URLs?
);

Most of the arguments to the createBarChart() method are obvious, but a few of them demand
further explanation:
• the plot orientation can be either horizontal or vertical (for bar charts, this corresponds to
the way the bars are drawn, horizontally or vertically);
• the tooltips flag controls whether or not a tool tip generator is added to the chart—in this
example, we’ve set this flag to true so that we’ll see tool tips when we display the chart in a
Swing application;

CHAPTER 6. BAR CHARTS

47

• the URLs flag is only relevant when creating drill-down reports using HTML image maps, so
we set it to cffalse here.
After we’ve completed this first bar chart example, we’ll come back and take a closer look at what
the ChartFactory class is doing “behind the scenes” here.

6.2.4

Displaying the Chart

To complete our first bar chart example, we pass the JFreeChart instance to a ChartPanel and
display it in a simple Swing application. The full source code for this example is listed here:
/* ---------------* BarExample1.java
* ---------------* (C) Copyright 2006, by Object Refinery Limited.
*
*/
package tutorial;
import java.awt.Dimension;
/**
* A simple demonstration application showing how to create a bar chart.
*/
public class BarExample1 extends ApplicationFrame {
/**
* Creates a new demo instance.
*
* @param title the frame title.
*/
public BarExample1(String title) {
super(title);
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
dataset.addValue(1.0, "Row 1", "Column 1");
dataset.addValue(5.0, "Row 1", "Column 2");
dataset.addValue(3.0, "Row 1", "Column 3");
dataset.addValue(2.0, "Row 2", "Column 1");
dataset.addValue(3.0, "Row 2", "Column 2");
dataset.addValue(2.0, "Row 2", "Column 3");
JFreeChart chart = ChartFactory.createBarChart(
"Bar Chart Demo",
// chart title
"Category",
// domain axis label
"Value",
// range axis label
dataset,
// data
PlotOrientation.VERTICAL, // orientation
true,
// include legend
true,
// tooltips?
false
// URLs?
);
ChartPanel chartPanel = new ChartPanel(chart, false);
chartPanel.setPreferredSize(new Dimension(500, 270));
setContentPane(chartPanel);
}
/**
* Starting point for the demonstration application.
*
* @param args ignored.
*/
public static void main(String[] args) {
BarExample1 demo = new BarExample1("Bar Demo 1");
demo.pack();
RefineryUtilities.centerFrameOnScreen(demo);
demo.setVisible(true);
}

CHAPTER 6. BAR CHARTS

48

}

If you compile and run this example, you should see a frame containing the chart in figure 6.2.

6.3

The ChartFactory Class

In our first example, the ChartFactory class is used to piece together a JFreeChart instance that
renders a bar chart. Here we take a closer look at how this is done, so we can see a little more of the
underlying structure of our bar chart. Understanding this structure is key to being able customise
the appearance of the chart.
Here are the important parts of the code from the createBarChart() method in the ChartFactory
class:
1

CategoryAxis categoryAxis = new CategoryAxis(categoryAxisLabel);

2
3

ValueAxis valueAxis = new NumberAxis(valueAxisLabel);
BarRenderer renderer = new BarRenderer();
[snip...]

4

CategoryPlot plot = new CategoryPlot(dataset, categoryAxis, valueAxis,
renderer);

5

plot.setOrientation(orientation);

6

JFreeChart chart = new JFreeChart(title, JFreeChart.DEFAULT TITLE FONT,
plot, legend);

Here’s what this code is doing:
• Our bar chart has two axes, one that displays categories from the dataset (a CategoryAxis),
and another that provides the numerical scale against which the data values are plotted (a
NumberAxis). You can see these axes being constructed in lines 1 and 2 above, using the axis
labels that we passed to the createBarChart() method.
• At line 3, a BarRenderer is created—this is the class that is used to draw the bar for each
data item. The renderer handles most of the drawing work, and you’ll see later that you can
substitute another type of renderer to change the overall appearance of the chart.
• The dataset, axes and renderer are all managed by a CategoryPlot, which coordinates most
of the interaction between these components. When you customise charts, you’ll often need
to get a reference to the chart’s plot, which in turn can give you access to the axes, renderer
and dataset. At line 4, the plot is created, and the other components are assigned to it.
• Finally, the plot is wrapped in a JFreeChart instance, with the specified title. The JFreeChart
class provides the top-level access to a chart, but most of the “guts” of a chart is defined
at the plot level (or in the objects managed by the plot, such as the axes, dataset(s) and
renderer(s)).
Armed with this knowledge of the internal structure of our chart, in the following sections, we’ll
slowly customise our bar chart.

6.4

Simple Chart Customisation

Some simple modifications to the appearance of a bar chart can be made by calling methods in the
JFreeChart and CategoryPlot classes. For example, to change the background colours for the chart

and plot:

CHAPTER 6. BAR CHARTS

49

chart.setBackgroundPaint(Color.white);
CategoryPlot plot = (CategoryPlot) chart.getPlot();
plot.setBackgroundPaint(Color.lightGray);
plot.setRangeGridlinePaint(Color.white);

This code fragment (from BarExample2.java) changes the background colour for the chart, then
obtains a reference to the chart’s plot and modifies it as well—see figure 6.3.

Figure 6.3: A bar chart (see BarExample2.java)

A cast of the plot reference (to CategoryPlot) is required—it is safe to make this cast, because we
know that a CategoryPlot is used for this chart type. JFreeChart uses other plot types (PiePlot,
XYPlot, and so on) for different kinds of charts. You almost always need to cast the plot reference to
one of these types, because the base class (Plot) only defines a few common attributes and methods.
As you become more familiar with JFreeChart, you’ll learn which Plot subclass is used for each
type of chart.
In our example, we also use the plot reference to change the colour of the grid lines for the range
axis. Take a look through the API documentation for the CategoryPlot class, to see what else you
could modify here.

6.5

Customising the Renderer

Recall from section 6.3 that the CategoryPlot manages a renderer which, in the case of a regular
bar chart, is an instance of BarRenderer. If we obtain a reference to this renderer, a large number
of customisation options become available.

6.5.1

Bar Colours

To change the colours used for each series in the chart:
BarRenderer renderer = (BarRenderer) plot.getRenderer();
renderer.setSeriesPaint(0, Color.gray);
renderer.setSeriesPaint(1, Color.orange);
renderer.setDrawBarOutline(false);

This results in the chart shown in figure 6.4. Note that the setSeriesPaint() method is defined in
the AbstractRenderer base class—you can use this for all types of renderer.

CHAPTER 6. BAR CHARTS

50

Figure 6.4: A bar chart (see BarExample3.java)

6.5.2

Bar Spacing Within Categories

Among other things, the renderer controls the spacing of bars within each category.1 So we could
remove all the space between bars in the same category, as follows:
renderer.setItemMargin(0.0);

This results in the chart shown in figure 6.5. Notice how the bars have grown a little wider—this
is because JFreeChart is now allocating less of the overall space to provide gaps between the bars,
so the bars themselves resize a little bigger.

Figure 6.5: A bar chart (see BarExample4.java)

1 The

spacing between categories is controlled by the CategoryAxis. That will be covered later.

Chapter 7

Line Charts
7.1

Introduction

This section describes the line charts that can be created with JFreeChart. It is possible to create
line charts using data from either the CategoryDataset interface or the XYDataset interface.

7.2

A Line Chart Based On A Category Dataset

7.2.1

Overview

A line chart based on a CategoryDataset simply connects each (category, value) data item using
straight lines. This section presents a sample application that generates the following chart shown
in figure 7.1.

Figure 7.1: A sample line chart

The full source code for this demo (LineChartDemo1.java) is available for download with the JFreeChart
Developer Guide.

7.2.2

The Dataset

The first step in generating the chart is, as always, to create a dataset. In the example, the
DefaultCategoryDataset class is used:
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
dataset.addValue(212, "Classes", "JDK 1.0");
dataset.addValue(504, "Classes", "JDK 1.1");
dataset.addValue(1520, "Classes", "SDK 1.2");

51

CHAPTER 7. LINE CHARTS

52

dataset.addValue(1842, "Classes", "SDK 1.3");
dataset.addValue(2991, "Classes", "SDK 1.4");

Note that you can use any implementation of the CategoryDataset interface as your dataset.

7.2.3

Constructing the Chart

The createLineChart() method in the ChartFactory class provides a convenient way to create the
chart. Here is the code:
// create the chart...
JFreeChart chart = ChartFactory.createLineChart(
"Java Standard Class Library", // chart title
"Release", // domain axis label
"Class Count", // range axis label
dataset, // data
PlotOrientation.VERTICAL, // orientation
false, // include legend
true, // tooltips
false // urls
);

This method constructs a JFreeChart object with a title, no legend, and plot with appropriate axes,
renderer and tooltip generator. The dataset is the one created in the previous section.

7.2.4

Customising the Chart

The chart will be initialised using default settings for most attributes. You are, of course, free to
modify any of the settings to change the appearance of your chart. In this example, we customise
the chart in the following ways:
• two subtitles are added to the chart;
• the chart background color is set to white;
• the plot background color is set to light gray;
• the gridline color is changed to white;
• the range axis is modified to display integer values only;
• the renderer is modified to fill shapes with white.
The first subtitle is added at the default position (below the main title):
chart.addSubtitle(new TextTitle("Number of Classes By Release"));

The next subtitle takes a little extra code, to change the font, place it at the bottom of the chart,
and align it to the right side:
TextTitle source = new TextTitle(
"Source: Java In A Nutshell (4th Edition) "
+ "by David Flanagan (O’Reilly)"
);
source.setFont(new Font("SansSerif", Font.PLAIN, 10));
source.setPosition(RectangleEdge.BOTTOM);
source.setHorizontalAlignment(HorizontalAlignment.RIGHT);
chart.addSubtitle(source);

Changing the chart’s background color is simple, because this is an attribute maintained by the
JFreeChart class:
chart.setBackgroundPaint(Color.white);

To change other attributes, we first need to obtain a reference to the CategoryPlot object used by
the chart:

CHAPTER 7. LINE CHARTS

53

CategoryPlot plot = (CategoryPlot) chart.getPlot();

To set the background color for the plot, and change the gridline color:
plot.setBackgroundPaint(Color.lightGray);
plot.setRangeGridlinePaint(Color.white);

The plot is responsible for drawing the data and axes on the chart. Some of this work is delegated
to a renderer, which you can access via the getRenderer() method. The renderer maintains most
of the attributes that relate to the appearance of the data items within the chart.
LineAndShapeRenderer renderer = (LineAndShapeRenderer) plot.getRenderer(); renderer.setShapesVisible(true);
renderer.setDrawOutlines(true); renderer.setUseFillPaint(true);

The plot also manages the chart’s axes. In the example, the range axis is modified so that it only
displays integer values for the tick labels:
// change the auto tick unit selection to integer units only...
NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());

There are many other ways to customise the chart. Please refer to the reference section of this
document, the API documentation and the source code for details of the methods available.

7.2.5

The Complete Program

The code for the demonstration application is presented in full, complete with the import statements. The source code is available for download from the same location as the JFreeChart Developer Guide.
/* ------------------* LineChartDemo1.java
* ------------------* (C) Copyright 2002-2005, by Object Refinery Limited.
*
*/
package demo;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import javax.swing.JPanel;
import
import
import
import
import
import
import
import
import
import
import
import
import
import

org.jfree.chart.ChartFactory;
org.jfree.chart.ChartPanel;
org.jfree.chart.JFreeChart;
org.jfree.chart.axis.NumberAxis;
org.jfree.chart.plot.CategoryPlot;
org.jfree.chart.plot.PlotOrientation;
org.jfree.chart.renderer.category.LineAndShapeRenderer;
org.jfree.chart.title.TextTitle;
org.jfree.data.category.CategoryDataset;
org.jfree.data.category.DefaultCategoryDataset;
org.jfree.ui.ApplicationFrame;
org.jfree.ui.HorizontalAlignment;
org.jfree.ui.RectangleEdge;
org.jfree.ui.RefineryUtilities;

/**
* A simple demonstration application showing how to create a line chart using
* data from a {@link CategoryDataset}.
*/
public class LineChartDemo1 extends ApplicationFrame {
/**
* Creates a new demo.
*
* @param title the frame title.
*/
public LineChartDemo1(String title) {
super(title);

CHAPTER 7. LINE CHARTS

CategoryDataset dataset = createDataset();
JFreeChart chart = createChart(dataset);
ChartPanel chartPanel = new ChartPanel(chart);
chartPanel.setPreferredSize(new Dimension(500, 270));
setContentPane(chartPanel);
}
/**
* Creates a sample dataset.
*
* @return The dataset.
*/
private static CategoryDataset createDataset() {
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
dataset.addValue(212, "Classes", "JDK 1.0");
dataset.addValue(504, "Classes", "JDK 1.1");
dataset.addValue(1520, "Classes", "SDK 1.2");
dataset.addValue(1842, "Classes", "SDK 1.3");
dataset.addValue(2991, "Classes", "SDK 1.4");
return dataset;
}
/**
* Creates a sample chart.
*
* @param dataset a dataset.
*
* @return The chart.
*/
private static JFreeChart createChart(CategoryDataset dataset) {
// create the chart...
JFreeChart chart = ChartFactory.createLineChart(
"Java Standard Class Library",
// chart title
"Release",
// domain axis label
"Class Count",
// range axis label
dataset,
// data
PlotOrientation.VERTICAL,
// orientation
false,
// include legend
true,
// tooltips
false
// urls
);
chart.addSubtitle(new TextTitle("Number of Classes By Release"));
TextTitle source = new TextTitle(
"Source: Java In A Nutshell (4th Edition) "
+ "by David Flanagan (O’Reilly)"
);
source.setFont(new Font("SansSerif", Font.PLAIN, 10));
source.setPosition(RectangleEdge.BOTTOM);
source.setHorizontalAlignment(HorizontalAlignment.RIGHT);
chart.addSubtitle(source);
chart.setBackgroundPaint(Color.white);
CategoryPlot plot = (CategoryPlot) chart.getPlot();
plot.setBackgroundPaint(Color.lightGray);
plot.setRangeGridlinePaint(Color.white);
// customise the range axis...
NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
// customise the renderer...
LineAndShapeRenderer renderer
= (LineAndShapeRenderer) plot.getRenderer();
renderer.setShapesVisible(true);
renderer.setDrawOutlines(true);
renderer.setUseFillPaint(true);
renderer.setFillPaint(Color.white);
return chart;
}
/**
* Creates a panel for the demo (used by SuperDemo.java).
*
* @return A panel.
*/
public static JPanel createDemoPanel() {
JFreeChart chart = createChart(createDataset());

54

CHAPTER 7. LINE CHARTS

return new ChartPanel(chart);
}
/**
* Starting point for the demonstration application.
*
* @param args ignored.
*/
public static void main(String[] args) {
LineChartDemo1 demo = new LineChartDemo1("Line Chart Demo");
demo.pack();
RefineryUtilities.centerFrameOnScreen(demo);
demo.setVisible(true);
}
}

55

CHAPTER 7. LINE CHARTS

7.3

56

A Line Chart Based On An XYDataset

7.3.1

Overview

A line chart based on an XYDataset connects each (x, y) point with a straight line. This section
presents a sample application that generates the chart shown in figure 7.2.

Figure 7.2: A sample line chart using an XYPlot
The complete source code (LineChartDemo2.java) is available to download with the JFreeChart
Developer Guide.

7.3.2

The Dataset

For this chart, an XYSeriesCollection is used as the dataset (you can use any implementation of
the XYDataset interface). For the purposes of the self-contained demo, we create this dataset in
code, as follows:
XYSeries series1
series1.add(1.0,
series1.add(2.0,
series1.add(3.0,
series1.add(4.0,
series1.add(5.0,
series1.add(6.0,
series1.add(7.0,
series1.add(8.0,

= new XYSeries("First");
1.0);
4.0);
3.0);
5.0);
5.0);
7.0);
7.0);
8.0);

XYSeries series2
series2.add(1.0,
series2.add(2.0,
series2.add(3.0,
series2.add(4.0,
series2.add(5.0,
series2.add(6.0,
series2.add(7.0,
series2.add(8.0,

= new XYSeries("Second");
5.0);
7.0);
6.0);
8.0);
4.0);
4.0);
2.0);
1.0);

XYSeries series3 = new XYSeries("Third");
series3.add(3.0, 4.0);
series3.add(4.0, 3.0);
series3.add(5.0, 2.0);
series3.add(6.0, 3.0);
series3.add(7.0, 6.0);
series3.add(8.0, 3.0);
series3.add(9.0, 4.0);
series3.add(10.0, 3.0);
XYSeriesCollection dataset = new XYSeriesCollection();
dataset.addSeries(series1);
dataset.addSeries(series2);
dataset.addSeries(series3);
return dataset;

CHAPTER 7. LINE CHARTS

57

Notice how each series has x-values (not just y-values) that are independent from the other series.
The dataset will also accept null in place of a y-value. When a null value is encountered, no
connecting line is drawn, resulting in a discontinuous line for the series.

7.3.3

Constructing the Chart

The createXYLineChart() method in the ChartFactory class provides a convenient way to create the
chart:
JFreeChart chart = ChartFactory.createXYLineChart(
"Line Chart Demo 2",
// chart title
"X",
// x axis label
"Y",
// y axis label
dataset,
// data
PlotOrientation.VERTICAL,
true,
// include legend
true,
// tooltips
false
// urls
);

This method constructs a JFreeChart object with a title, legend and plot with appropriate axes
and renderer. The dataset is the one created in the previous section. The chart is created with a
legend, and tooltips are enabled (URLs are disabled—these are only used in the creation of HTML
image maps).

7.3.4

Customising the Chart

The chart will be initialised using default settings for most attributes. You are, of course, free
to modify any of the settings to change the appearance of your chart. In this example, several
attributes are modified:
• the chart background color;
• the plot background color;
• the axis offsets;
• the color of the domain and range gridlines;
• the renderer is modified to draw shapes as well as lines;
• the tick unit collection for the range axis, so that the tick values always display integer values;
Changing the chart’s background color is simple:
// set the background color for the chart...
chart.setBackgroundPaint(Color.white);

Changing the plot background color, the axis offsets, and the color of the gridlines, requires a
reference to the plot. The cast to XYPlot is required so that we can access methods specific to this
type of plot:
// get a reference to the plot for further customisation...
XYPlot plot = (XYPlot) chart.getPlot();
plot.setBackgroundPaint(Color.lightGray);
plot.setAxisOffset(new RectangleInsets(5.0, 5.0, 5.0, 5.0));
plot.setDomainGridlinePaint(Color.white);
plot.setRangeGridlinePaint(Color.white);

The renderer is modified to display filled shapes in addition to the default lines:
XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) plot.getRenderer();
renderer.setShapesVisible(true);
renderer.setShapesFilled(true);

CHAPTER 7. LINE CHARTS

58

The final modification is a change to the range axis. We change the default collection of tick units
(which allow fractional values) to an integer-only collection:
// change the auto tick unit selection to integer units only...
NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());

Refer to the source code, Javadoc API documentation or elsewhere in this document for details of
the other customisations that you can make to an XYPlot.

7.3.5

The Complete Program

The code for the demonstration application is presented here in full, complete with the import
statements:
/* ------------------* LineChartDemo2.java
* ------------------* (C) Copyright 2002-2005, by Object Refinery Limited.
*
*/
package demo;
import java.awt.Color;
import javax.swing.JPanel;
import
import
import
import
import
import
import
import
import
import
import
import
import

org.jfree.chart.ChartFactory;
org.jfree.chart.ChartPanel;
org.jfree.chart.JFreeChart;
org.jfree.chart.axis.NumberAxis;
org.jfree.chart.plot.PlotOrientation;
org.jfree.chart.plot.XYPlot;
org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
org.jfree.data.xy.XYDataset;
org.jfree.data.xy.XYSeries;
org.jfree.data.xy.XYSeriesCollection;
org.jfree.ui.ApplicationFrame;
org.jfree.ui.RectangleInsets;
org.jfree.ui.RefineryUtilities;

/**
* A simple demonstration application showing how to create a line chart using
* data from an {@link XYDataset}.
* 

* IMPORTANT NOTE: THIS DEMO IS DOCUMENTED IN THE JFREECHART DEVELOPER GUIDE. * DO NOT MAKE CHANGES WITHOUT UPDATING THE GUIDE ALSO!! */ public class LineChartDemo2 extends ApplicationFrame { /** * Creates a new demo. * * @param title the frame title. */ public LineChartDemo2(String title) { super(title); XYDataset dataset = createDataset(); JFreeChart chart = createChart(dataset); ChartPanel chartPanel = new ChartPanel(chart); chartPanel.setPreferredSize(new java.awt.Dimension(500, 270)); setContentPane(chartPanel); } /** * Creates a sample dataset. * * @return a sample dataset. */ private static XYDataset createDataset() { XYSeries series1 = new XYSeries("First"); series1.add(1.0, 1.0); series1.add(2.0, 4.0); CHAPTER 7. LINE CHARTS series1.add(3.0, series1.add(4.0, series1.add(5.0, series1.add(6.0, series1.add(7.0, series1.add(8.0, 3.0); 5.0); 5.0); 7.0); 7.0); 8.0); XYSeries series2 series2.add(1.0, series2.add(2.0, series2.add(3.0, series2.add(4.0, series2.add(5.0, series2.add(6.0, series2.add(7.0, series2.add(8.0, = new XYSeries("Second"); 5.0); 7.0); 6.0); 8.0); 4.0); 4.0); 2.0); 1.0); XYSeries series3 = new XYSeries("Third"); series3.add(3.0, 4.0); series3.add(4.0, 3.0); series3.add(5.0, 2.0); series3.add(6.0, 3.0); series3.add(7.0, 6.0); series3.add(8.0, 3.0); series3.add(9.0, 4.0); series3.add(10.0, 3.0); XYSeriesCollection dataset = new XYSeriesCollection(); dataset.addSeries(series1); dataset.addSeries(series2); dataset.addSeries(series3); return dataset; } /** * Creates a chart. * * @param dataset the data for the chart. * * @return a chart. */ private static JFreeChart createChart(XYDataset dataset) { // create the chart... JFreeChart chart = ChartFactory.createXYLineChart( "Line Chart Demo 2", // chart title "X", // x axis label "Y", // y axis label dataset, // data PlotOrientation.VERTICAL, true, // include legend true, // tooltips false // urls ); // NOW DO SOME OPTIONAL CUSTOMISATION OF THE CHART... chart.setBackgroundPaint(Color.white); // get a reference to the plot for further customisation... XYPlot plot = (XYPlot) chart.getPlot(); plot.setBackgroundPaint(Color.lightGray); plot.setAxisOffset(new RectangleInsets(5.0, 5.0, 5.0, 5.0)); plot.setDomainGridlinePaint(Color.white); plot.setRangeGridlinePaint(Color.white); XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) plot.getRenderer(); renderer.setShapesVisible(true); renderer.setShapesFilled(true); // change the auto tick unit selection to integer units only... NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis(); rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits()); // OPTIONAL CUSTOMISATION COMPLETED. return chart; } 59 CHAPTER 7. LINE CHARTS /** * Creates a panel for the demo (used by SuperDemo.java). * * @return A panel. */ public static JPanel createDemoPanel() { JFreeChart chart = createChart(createDataset()); return new ChartPanel(chart); } /** * Starting point for the demonstration application. * * @param args ignored. */ public static void main(String[] args) { LineChartDemo2 demo = new LineChartDemo2("Line Chart Demo 2"); demo.pack(); RefineryUtilities.centerFrameOnScreen(demo); demo.setVisible(true); } } 60 Chapter 8 Time Series Charts 8.1 Introduction Time series charts are very similar to line charts, except that the values on the domain axis are dates rather than numbers. This section describes how to create time series charts with JFreeChart. 8.2 8.2.1 Time Series Charts Overview A time series chart is really just a line chart using data obtained via the XYDataset interface (see the example in the previous section). The difference is that the x-values are displayed as dates on the domain axis. This section presents a sample application that generates the chart shown in figure 8.1. Figure 8.1: A time series chart The complete source code (TimeSeriesDemo1.java) for this example is available for download with the JFreeChart Developer Guide. 8.2.2 Dates or Numbers? Time series charts are created using data from an XYDataset. This interface doesn’t have any methods that return dates, so how does JFreeChart create time series charts? The x-values returned by the dataset are double primitives, but the values are interpreted in a special way—they are assumed to represent the number of milliseconds since midnight, 1 January 61 CHAPTER 8. TIME SERIES CHARTS 62 1970 (the encoding used by the java.util.Date class). A special axis class (DateAxis) converts from milliseconds to dates and back again as necessary, allowing the axis to display tick labels formatted as dates. 8.2.3 The Dataset For the demo chart, a TimeSeriesCollection is used as the dataset (you can use any implementation of the XYDataset interface): TimeSeries s1.add(new s1.add(new s1.add(new s1.add(new s1.add(new s1.add(new s1.add(new s1.add(new s1.add(new s1.add(new s1.add(new s1.add(new s1.add(new s1.add(new s1.add(new s1.add(new s1.add(new s1.add(new s1 = new TimeSeries("L&G European Index Trust", Month.class); Month(2, 2001), 181.8); Month(3, 2001), 167.3); Month(4, 2001), 153.8); Month(5, 2001), 167.6); Month(6, 2001), 158.8); Month(7, 2001), 148.3); Month(8, 2001), 153.9); Month(9, 2001), 142.7); Month(10, 2001), 123.2); Month(11, 2001), 131.8); Month(12, 2001), 139.6); Month(1, 2002), 142.9); Month(2, 2002), 138.7); Month(3, 2002), 137.3); Month(4, 2002), 143.9); Month(5, 2002), 139.8); Month(6, 2002), 137.0); Month(7, 2002), 132.8); TimeSeries s2.add(new s2.add(new s2.add(new s2.add(new s2.add(new s2.add(new s2.add(new s2.add(new s2.add(new s2.add(new s2.add(new s2.add(new s2.add(new s2.add(new s2.add(new s2.add(new s2.add(new s2.add(new s2 = new TimeSeries("L&G UK Index Trust", Month.class); Month(2, 2001), 129.6); Month(3, 2001), 123.2); Month(4, 2001), 117.2); Month(5, 2001), 124.1); Month(6, 2001), 122.6); Month(7, 2001), 119.2); Month(8, 2001), 116.5); Month(9, 2001), 112.7); Month(10, 2001), 101.5); Month(11, 2001), 106.1); Month(12, 2001), 110.3); Month(1, 2002), 111.7); Month(2, 2002), 111.0); Month(3, 2002), 109.6); Month(4, 2002), 113.2); Month(5, 2002), 111.6); Month(6, 2002), 108.8); Month(7, 2002), 101.6); TimeSeriesCollection dataset = new TimeSeriesCollection(); dataset.addSeries(s1); dataset.addSeries(s2); In the example, the series contain monthly data. However, the TimeSeries class can be used to represent values observed at other intervals (annual, daily, hourly etc). 8.2.4 Constructing the Chart The createTimeSeriesChart() method in the ChartFactory class provides a convenient way to create the chart: JFreeChart chart = ChartFactory.createTimeSeriesChart( "Legal & General Unit Trust Prices", // title "Date", // x-axis label "Price Per Unit", // y-axis label dataset, // data true, // create legend? true, // generate tooltips? false // generate URLs? ); This method constructs a JFreeChart object with a title, legend and plot with appropriate axes and renderer. The dataset is the one created in the previous section. CHAPTER 8. TIME SERIES CHARTS 8.2.5 63 Customising the Chart The chart will be initialised using default settings for most attributes. You are, of course, free to modify any of the settings to change the appearance of your chart. In this example, several attributes are modified: • the renderer is changed to display series shapes at each data point, in addition to the lines between data points; • a date format override is set for the domain axis; Modifying the renderer requires a couple of steps to obtain a reference to the renderer and then cast it to a XYLineAndShapeRenderer: XYItemRenderer r = plot.getRenderer(); if (r instanceof XYLineAndShapeRenderer) { XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) r; renderer.setBaseShapesVisible(true); renderer.setBaseShapesFilled(true); } In the final customisation, a date format override is set for the domain axis. DateAxis axis = (DateAxis) plot.getDomainAxis(); axis.setDateFormatOverride(new SimpleDateFormat("MMM-yyyy")); When this is set, the axis will continue to “auto-select” a DateTickUnit from the collection of standard tick units, but it will ignore the formatting from the tick unit and use the override format instead. 8.2.6 The Complete Program The code for the demonstration application is presented in full, complete with the import statements: /* ------------------* TimeSeriesDemo.java * ------------------* (C) Copyright 2002-2005, by Object Refinery Limited. * */ package demo; import java.awt.Color; import java.text.SimpleDateFormat; import javax.swing.JPanel; import import import import import import import import import import import import import import org.jfree.chart.ChartFactory; org.jfree.chart.ChartPanel; org.jfree.chart.JFreeChart; org.jfree.chart.axis.DateAxis; org.jfree.chart.plot.XYPlot; org.jfree.chart.renderer.xy.XYItemRenderer; org.jfree.chart.renderer.xy.XYLineAndShapeRenderer; org.jfree.data.time.Month; org.jfree.data.time.TimeSeries; org.jfree.data.time.TimeSeriesCollection; org.jfree.data.xy.XYDataset; org.jfree.ui.ApplicationFrame; org.jfree.ui.RectangleInsets; org.jfree.ui.RefineryUtilities; /** * An example of a time series chart. For the most part, default settings are CHAPTER 8. TIME SERIES CHARTS * used, except that the renderer is modified to show filled shapes (as well as * lines) at each data point. *

* IMPORTANT NOTE: THIS DEMO IS DOCUMENTED IN THE JFREECHART DEVELOPER GUIDE. * DO NOT MAKE CHANGES WITHOUT UPDATING THE GUIDE ALSO!! */ public class TimeSeriesDemo1 extends ApplicationFrame { /** * A demonstration application showing how to create a simple time series * chart. This example uses monthly data. * * @param title the frame title. */ public TimeSeriesDemo1(String title) { super(title); XYDataset dataset = createDataset(); JFreeChart chart = createChart(dataset); ChartPanel chartPanel = new ChartPanel(chart); chartPanel.setPreferredSize(new java.awt.Dimension(500, 270)); chartPanel.setMouseZoomable(true, false); setContentPane(chartPanel); } /** * Creates a chart. * * @param dataset a dataset. * * @return A chart. */ private static JFreeChart createChart(XYDataset dataset) { JFreeChart chart = ChartFactory.createTimeSeriesChart( "Legal & General Unit Trust Prices", // title "Date", // x-axis label "Price Per Unit", // y-axis label dataset, // data true, // create legend? true, // generate tooltips? false // generate URLs? ); chart.setBackgroundPaint(Color.white); XYPlot plot = (XYPlot) chart.getPlot(); plot.setBackgroundPaint(Color.lightGray); plot.setDomainGridlinePaint(Color.white); plot.setRangeGridlinePaint(Color.white); plot.setAxisOffset(new RectangleInsets(5.0, 5.0, 5.0, 5.0)); plot.setDomainCrosshairVisible(true); plot.setRangeCrosshairVisible(true); XYItemRenderer r = plot.getRenderer(); if (r instanceof XYLineAndShapeRenderer) { XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) r; renderer.setBaseShapesVisible(true); renderer.setBaseShapesFilled(true); } DateAxis axis = (DateAxis) plot.getDomainAxis(); axis.setDateFormatOverride(new SimpleDateFormat("MMM-yyyy")); return chart; } /** 64 CHAPTER 8. TIME SERIES CHARTS * Creates a dataset, consisting of two series of monthly data. * * @return the dataset. */ private static XYDataset createDataset() { TimeSeries s1.add(new s1.add(new s1.add(new s1.add(new s1.add(new s1.add(new s1.add(new s1.add(new s1.add(new s1.add(new s1.add(new s1.add(new s1.add(new s1.add(new s1.add(new s1.add(new s1.add(new s1.add(new s1 = new TimeSeries("L&G European Index Trust", Month.class); Month(2, 2001), 181.8); Month(3, 2001), 167.3); Month(4, 2001), 153.8); Month(5, 2001), 167.6); Month(6, 2001), 158.8); Month(7, 2001), 148.3); Month(8, 2001), 153.9); Month(9, 2001), 142.7); Month(10, 2001), 123.2); Month(11, 2001), 131.8); Month(12, 2001), 139.6); Month(1, 2002), 142.9); Month(2, 2002), 138.7); Month(3, 2002), 137.3); Month(4, 2002), 143.9); Month(5, 2002), 139.8); Month(6, 2002), 137.0); Month(7, 2002), 132.8); TimeSeries s2.add(new s2.add(new s2.add(new s2.add(new s2.add(new s2.add(new s2.add(new s2.add(new s2.add(new s2.add(new s2.add(new s2.add(new s2.add(new s2.add(new s2.add(new s2.add(new s2.add(new s2.add(new s2 = new TimeSeries("L&G UK Index Trust", Month.class); Month(2, 2001), 129.6); Month(3, 2001), 123.2); Month(4, 2001), 117.2); Month(5, 2001), 124.1); Month(6, 2001), 122.6); Month(7, 2001), 119.2); Month(8, 2001), 116.5); Month(9, 2001), 112.7); Month(10, 2001), 101.5); Month(11, 2001), 106.1); Month(12, 2001), 110.3); Month(1, 2002), 111.7); Month(2, 2002), 111.0); Month(3, 2002), 109.6); Month(4, 2002), 113.2); Month(5, 2002), 111.6); Month(6, 2002), 108.8); Month(7, 2002), 101.6); TimeSeriesCollection dataset = new TimeSeriesCollection(); dataset.addSeries(s1); dataset.addSeries(s2); dataset.setDomainIsPointsInTime(true); return dataset; } /** * Creates a panel for the demo (used by SuperDemo.java). * * @return A panel. */ public static JPanel createDemoPanel() { JFreeChart chart = createChart(createDataset()); return new ChartPanel(chart); } /** * Starting point for the demonstration application. 65 CHAPTER 8. TIME SERIES CHARTS * * @param args ignored. */ public static void main(String[] args) { TimeSeriesDemo1 demo = new TimeSeriesDemo1("Time Series Demo 1"); demo.pack(); RefineryUtilities.centerFrameOnScreen(demo); demo.setVisible(true); } } 66 Chapter 9 Customising Charts 9.1 Introduction JFreeChart has been designed to be highly customisable. There are many attributes that you can set to change the default appearance of your charts. In this section, some common techniques for customising charts are presented. 9.2 Chart Attributes 9.2.1 Overview At the highest level, you can customise the appearance of your charts using methods in the JFreeChart class. This allows you to control: • the chart border; • the chart title and sub-titles; • the background color and/or image; • the rendering hints that are used to draw the chart, including whether or not anti-aliasing is used; These items are described in the following sections. 9.2.2 The Chart Border JFreeChart can draw a border around the outside of a chart. By default, no border is drawn, but you can change this using the setBorderVisible() method. The color and line-style for the border are controlled by the setBorderPaint() and setBorderStroke() methods. Note: if you are displaying your chart inside a ChartPanel, then you might prefer to use the border facilities provided by Swing. 9.2.3 The Chart Title A chart has one title that can appear at the top, bottom, left or right of the chart (you can also add subtitles—see the next section). The title is an instance of TextTitle. You can obtain a reference to the title using the getTitle() method: TextTitle title = chart.getTitle(); To modify the title text (without changing the font or position): 67 CHAPTER 9. CUSTOMISING CHARTS 68 chart.setTitle("A Chart Title"); The placement of the title at the top, bottom, left or right of the chart is controlled by a property of the title itself. To move the title to the bottom of the chart: chart.getTitle().setPosition(RectangleEdge.BOTTOM); If you prefer to have no title on your chart, you can set the title to null. 9.2.4 Subtitles A chart can have any number of subtitles. To add a sub-title to a chart, create a subtitle (any subclass of Title) and add it to the chart. For example: TextTitle subtitle1 = new TextTitle("A Subtitle"); chart.addSubtitle(subtitle1); You can add as many sub-titles as you like to a chart, but keep in mind that as you add more sub-titles there will be less and less space available for drawing the chart. To modify an existing sub-title, you need to get a reference to the sub-title. For example: Title subtitle = chart.getSubtitle(0); You will need to cast the Title reference to an appropriate subclass before you can change its properties. You can check the number of sub-titles using the getSubtitleCount() method. 9.2.5 Setting the Background Color You can use the setBackgroundPaint() method to set the background color for a chart.1 For example: chart.setBackgroundPaint(Color.blue); You can use any implementation of the Paint interface, including the Java classes Color, GradientPaint and TexturePaint. For example: Paint p = new GradientPaint(0, 0, Color.white, 1000, 0, Color.green)); chart.setBackgroundPaint(p); You can also set the background paint to null, which is recommended if you have specified a background image for your chart. 9.2.6 Using a Background Image You can use the setBackgroundImage() method to set a background image for a chart. chart.setBackgroundImage(JFreeChart.INFO.getLogo()); By default, the image will be scaled to fit the area that the chart is being drawn into, but you can change this using the setBackgroundImageAlignment() method. chart.setBackgroundImageAlignment(Align.TOP LEFT); Using the setBackgroundImageAlpha() method, you can control the alpha-transparency for the image. If you want an image to fill only the data area of your chart (that is, the area inside the axes), then you need to add a background image to the chart’s Plot (described later). 1 You can also set the background color for the chart’s plot area, which has a slightly different effect—refer to the Plot class for details. CHAPTER 9. CUSTOMISING CHARTS 9.2.7 69 Rendering Hints JFreeChart uses the Java2D API to draw charts. Within this API, you can specify rendering hints to fine tune aspects of the way that the rendering engine works. JFreeChart allows you to specify the rendering hints to be passed to the Java2D API when charts are drawn—use the setRenderingHints() method. As a convenience, a method is provided to turn anti-aliasing on or off. With anti-aliasing on, charts appear to be smoother but they take longer to draw: // turn on antialiasing... chart.setAntiAlias(true); By default, charts are drawn with anti-aliasing turned on. 9.3 Plot Attributes 9.3.1 Overview The JFreeChart class delegates a lot of the work in drawing a chart to the Plot class (or, rather, to a specific subclass of Plot). The getPlot() method in the JFreeChart class returns a reference to the plot being used by the chart. Plot plot = chart.getPlot(); You may need to cast this reference to a specific subclass of Plot, for example: CategoryPlot plot = chart.getCategoryPlot(); ...or: XYPlot plot = chart.getXYPlot(); Note that these methods will throw a ClassCastException if the plot is not an appropriate class. 9.3.2 Which Plot Subclass? How do you know which subclass of Plot is being used by a chart? As you gain experience with JFreeChart, it will become clear which charts use CategoryPlot and which charts use XYPlot. If in doubt, take a look in the ChartFactory class source code to see how each chart type is put together. 9.3.3 Setting the Background Paint You can use the setBackgroundPaint() method to set the background color for a plot. For example: Plot plot = chart.getPlot(); plot.setBackgroundPaint(Color.white); You can use any implementation of the Paint interface, including the Java classes Color, GradientPaint and TexturePaint. You can also set the background paint to null. 9.3.4 Using a Background Image You can use the setBackgroundImage() method to set a background image for a plot: Plot plot = chart.getPlot(); plot.setBackgroundImage(JFreeChart.INFO.getLogo()); By default, the image will be scaled to fit the area that the plot is being drawn into. You can change this using the setBackgroundImageAlignment() method: plot.setBackgroundImageAlignment(Align.BOTTOM RIGHT); Use the setBackgroundAlpha() method to control the alpha-transparency used for the image. If you prefer your image to fill the entire chart area, then you need to add a background image to the JFreeChart object (described previously). CHAPTER 9. CUSTOMISING CHARTS 9.4 70 Axis Attributes 9.4.1 Overview The majority of charts created with JFreeChart have two axes, a domain axis and a range axis. Of course, there are some charts (for example, pie charts) that don’t have axes at all. For charts where axes are used, the Axis objects are managed by the plot. 9.4.2 Obtaining an Axis Reference Before you can change the properties of an axis, you need to obtain a reference to the axis. The plot classes CategoryPlot and XYPlot both have methods getDomainAxis() and getRangeAxis(). These methods return a reference to a ValueAxis, except in the case of the CategoryPlot, where the domain axis is an instance of CategoryAxis. // get an axis reference... CategoryPlot plot = chart.getCategoryPlot(); CategoryAxis domainAxis = plot.getDomainAxis(); // change axis properties... domainAxis.setLabel("Categories"); domainAxis.setLabelFont(someFont); There are many different subclasses of the CategoryAxis and ValueAxis classes. Sometimes you will need to cast your axis reference to a more specific subclass, in order to access some of its attributes. For example, if you know that your range axis is a NumberAxis (and the range axis almost always is), then you can do the following: XYPlot plot = chart.getXYPlot(); NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis(); rangeAxis.setAutoRange(false); 9.4.3 Setting the Axis Label You can use the setLabel() method to change the axis label. If you would prefer not to have a label for your axis, just set it to null. You can change the font, color and insets (the space around the outside of the label) with the methods setLabelFont(), setLabelPaint(), and setLabelInsets(), defined in the Axis class. 9.4.4 Rotating Axis Labels When an axis is drawn at the left or right of a plot (a “vertical” axis), the label is automatically rotated by 90 degrees to minimise the space required. If you prefer to have the label drawn horizontally, you can change the label angle: XYPlot plot = chart.getXYPlot(); ValueAxis axis = plot.getRangeAxis(); axis.setLabelAngle(Math.PI / 2.0); Note that the angle is specified in radians (Math.PI = 180 degrees). 9.4.5 Hiding Tick Labels To hide the tick labels for an axis: CategoryPlot plot = chart.getCategoryPlot(); ValueAxis axis = plot.getRangeAxis(); axis.setTickLabelsVisible(false); For a CategoryAxis, setTickLabelsVisible(false) will hide the category labels. CHAPTER 9. CUSTOMISING CHARTS 9.4.6 71 Hiding Tick Marks To hide the tick marks for an axis: XYPlot plot = chart.getXYPlot(); Axis axis = plot.getDomainAxis(); axis.setTickMarksVisible(false); Category axes do not have tick marks. 9.4.7 Setting the Tick Size By default, numerical and date axes automatically select a tick size so that the tick labels will not overlap. You can override this by setting your own tick unit using the setTickUnit() method. Alternatively, for a NumberAxis or a DateAxis you can specify your own set of tick units from which the axis will automatically select an appropriate tick size. This is described in the following sections. 9.4.8 Specifying “Standard” Number Tick Units In the NumberAxis class, there is a method setStandardTickUnits() that allows you to supply your own set of tick units for the “auto tick unit selection” mechanism. One common application is where you have a number axis that should only display integers. In this case, you don’t want tick units of (say) 0.5 or 0.25. There is a (static) method in the NumberAxis class that returns a set of standard integer tick units: XYPlot plot = chart.getXYPlot(); NumberAxis axis = (NumberAxis) plot.getRangeAxis(); TickUnitSource units = NumberAxis.createIntegerTickUnits(); axis.setStandardTickUnits(units); You are free to create your own TickUnits collection, if you want greater control over the standard tick units. 9.4.9 Specifying “Standard” Date Tick Units Similar to the case in the previous section, the DateAxis class has a method setStandardTickUnits() that allows you to supply your own set of tick units for the “auto tick unit selection” mechanism. The createStandardDateTickUnits() method returns the default collection for a DateAxis, but you are free to create your own TickUnits collection if you want greater control over the standard tick units. Chapter 10 Dynamic Charts 10.1 Overview To illustrate the use of JFreeChart for creating “dynamic” charts, this section presents a sample application that displays a frequently updating chart of JVM memory usage and availability. Figure 10.1: A dynamic chart demo 10.2 Background 10.2.1 Event notification JFreeChart uses an event notification mechanism that allows it to respond to changes to any component of the chart. For example, whenever a dataset is updated, a DatasetChangeEvent is sent to all listeners that are registered with the dataset. This triggers the following sequence of events: • the plot (which registers itself with the dataset as a DatasetChangeListener) receives notification of the dataset change. It updates the axis ranges (if necessary) then passes on a PlotChangeEvent to all its registered listeners; • the chart receives notification of the plot change event, and passes on a ChartChangeEvent to all its registered listeners; • finally, for charts that are displayed in a ChartPanel, the panel will receive the chart change event. It responds by redrawing the chart—a complete redraw, not just the updated data. A similar sequence of events happens for all changes to a chart or its subcomponents. 72 CHAPTER 10. DYNAMIC CHARTS 10.2.2 73 Performance Regarding performance, you need to be aware that JFreeChart wasn’t designed specifically for generating real-time charts. Each time a dataset is updated, the ChartPanel reacts by redrawing the entire chart. Optimisations, such as only drawing the most recently added data point, are difficult to implement in the general case, even more so given the Graphics2D abstraction (in the Java2D API) employed by JFreeChart. This limits the number of “frames per second” you will be able to achieve with JFreeChart. Whether this will be an issue for you depends on your data, the requirements of your application, and your operating environment. 10.3 The Demo Application 10.3.1 Overview The MemoryUsageDemo.java demonstration is included in the JFreeChart demo collection (source code available to purchasers of this guide). You can obtain this from: http://www.object-refinery.com/jfreechart/premium/index.html You will need to enter the username and password supplied with your original purchase of the JFreeChart Developer Guide. 10.3.2 Creating the Dataset The dataset is created using two TimeSeries objects (one for the total memory and the other for the free memory) that are added to a single time series collection: // create two series that automatically discard data > 30 seconds old... this.total = new TimeSeries("Total", Millisecond.class); this.total.setMaximumItemAge(30000); this.free = new TimeSeries("Free", Millisecond.class); this.free.setMaximumItemAge(30000); TimeSeriesCollection dataset = new TimeSeriesCollection(); dataset.addSeries(this.total); dataset.addSeries(this.free); The maximumItemAge attribute for each time series is set to 30,000 milliseconds (or 30 seconds) so that whenever new data is added to the series, any observations that are older that 30 seconds are automatically discarded. 10.3.3 Creating the Chart The chart creation (and customisation) follows the standard pattern for all charts. No special steps are required to create a dynamic chart, except that you should ensure that the axes have their autoRange attribute set to true. It also helps to retain a reference to the dataset used in the chart. 10.3.4 Updating the Dataset In the demo, the dataset is updated by adding data to the two time series from a separate thread, managed by the following timer: class DataGenerator extends Timer implements ActionListener { DataGenerator(int interval) { super(interval, null); addActionListener(this); } public void actionPerformed(ActionEvent event) { long f = Runtime.getRuntime().freeMemory(); long t = Runtime.getRuntime().totalMemory(); addTotalObservation(t); addFreeObservation(f); CHAPTER 10. DYNAMIC CHARTS 74 } } Note that JFreeChart does not yet use thread synchronisation between the chart drawing code and the dataset update code, so this approach is a little unsafe. One other point to note, at one point while investigating reports of a memory leak in JFreeChart, I left this demo running on a test machine for about six days. As the chart updates, you can see the effect of the garbage collector. Over the six day period, the total memory used remained constant while the free memory decreased as JFreeChart discarded temporary objects (garbage), and increased at the points where the garbage collector did its work. 10.3.5 Source Code For reference, here is the complete source code for the example: /* -------------------* MemoryUsageDemo.java * -------------------* (C) Copyright 2002-2006, by Object Refinery Limited. */ package demo; import import import import import import import import java.awt.BasicStroke; java.awt.BorderLayout; java.awt.Color; java.awt.Font; java.awt.event.ActionEvent; java.awt.event.ActionListener; java.awt.event.WindowAdapter; java.awt.event.WindowEvent; import import import import javax.swing.BorderFactory; javax.swing.JFrame; javax.swing.JPanel; javax.swing.Timer; import import import import import import import import import import import org.jfree.chart.ChartPanel; org.jfree.chart.JFreeChart; org.jfree.chart.axis.DateAxis; org.jfree.chart.axis.NumberAxis; org.jfree.chart.plot.XYPlot; org.jfree.chart.renderer.xy.XYItemRenderer; org.jfree.chart.renderer.xy.XYLineAndShapeRenderer; org.jfree.data.time.Millisecond; org.jfree.data.time.TimeSeries; org.jfree.data.time.TimeSeriesCollection; org.jfree.ui.RectangleInsets; /** * A demo application showing a dynamically * current JVM memory usage. *

* IMPORTANT NOTE: THIS DEMO IS DOCUMENTED * DO NOT MAKE CHANGES WITHOUT UPDATING THE */ public class MemoryUsageDemo extends JPanel updated chart that displays the IN THE JFREECHART DEVELOPER GUIDE. GUIDE ALSO!! { /** Time series for total memory used. */ private TimeSeries total; /** Time series for free memory. */ private TimeSeries free; /** * Creates a new application. * * @param maxAge the maximum age (in milliseconds). */ public MemoryUsageDemo(int maxAge) { super(new BorderLayout()); // create two series that automatically discard data more than 30 CHAPTER 10. DYNAMIC CHARTS // seconds old... this.total = new TimeSeries("Total Memory", Millisecond.class); this.total.setMaximumItemAge(maxAge); this.free = new TimeSeries("Free Memory", Millisecond.class); this.free.setMaximumItemAge(maxAge); TimeSeriesCollection dataset = new TimeSeriesCollection(); dataset.addSeries(this.total); dataset.addSeries(this.free); DateAxis domain = new DateAxis("Time"); NumberAxis range = new NumberAxis("Memory"); domain.setTickLabelFont(new Font("SansSerif", Font.PLAIN, 12)); range.setTickLabelFont(new Font("SansSerif", Font.PLAIN, 12)); domain.setLabelFont(new Font("SansSerif", Font.PLAIN, 14)); range.setLabelFont(new Font("SansSerif", Font.PLAIN, 14)); XYItemRenderer renderer = new XYLineAndShapeRenderer(true, false); renderer.setSeriesPaint(0, Color.red); renderer.setSeriesPaint(1, Color.green); renderer.setStroke(new BasicStroke(3f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL)); XYPlot plot = new XYPlot(dataset, domain, range, renderer); plot.setBackgroundPaint(Color.lightGray); plot.setDomainGridlinePaint(Color.white); plot.setRangeGridlinePaint(Color.white); plot.setAxisOffset(new RectangleInsets(5.0, 5.0, 5.0, 5.0)); domain.setAutoRange(true); domain.setLowerMargin(0.0); domain.setUpperMargin(0.0); domain.setTickLabelsVisible(true); range.setStandardTickUnits(NumberAxis.createIntegerTickUnits()); JFreeChart chart = new JFreeChart("JVM Memory Usage", new Font("SansSerif", Font.BOLD, 24), plot, true); chart.setBackgroundPaint(Color.white); ChartPanel chartPanel = new ChartPanel(chart); chartPanel.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createEmptyBorder(4, 4, 4, 4), BorderFactory.createLineBorder(Color.black))); add(chartPanel); } /** * Adds an observation to the ’total memory’ time series. * * @param y the total memory used. */ private void addTotalObservation(double y) { this.total.add(new Millisecond(), y); } /** * Adds an observation to the ’free memory’ time series. * * @param y the free memory. */ private void addFreeObservation(double y) { this.free.add(new Millisecond(), y); } /** * The data generator. */ class DataGenerator extends Timer implements ActionListener { /** * Constructor. * * @param interval the interval (in milliseconds) */ DataGenerator(int interval) { super(interval, null); addActionListener(this); } /** * Adds a new free/total memory reading to the dataset. * * @param event the action event. 75 CHAPTER 10. DYNAMIC CHARTS */ public void actionPerformed(ActionEvent event) { long f = Runtime.getRuntime().freeMemory(); long t = Runtime.getRuntime().totalMemory(); addTotalObservation(t); addFreeObservation(f); } } /** * Entry point for the sample application. * * @param args ignored. */ public static void main(String[] args) { JFrame frame = new JFrame("Memory Usage Demo"); MemoryUsageDemo panel = new MemoryUsageDemo(30000); frame.getContentPane().add(panel, BorderLayout.CENTER); frame.setBounds(200, 120, 600, 280); frame.setVisible(true); panel.new DataGenerator(100).start(); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); } } 76 Chapter 11 Tooltips 11.1 Overview JFreeChart includes mechanisms for generating, collecting and displaying tool tips for individual components of a chart. In this section, I describe: • how to generate tool tips (including customisation of tool tips); • how tool tips are collected; • how to display tool tips; • how to disable tool tips if you don’t need them; 11.2 Generating Tool Tips If you want to use tool tips, you need to make sure they are generated as your chart is being drawn. You do this by setting a tool tip generator for your plot or, in many cases, the plot’s item renderer. In the sub-sections that follow, I describe how to set a tool tip generator for the common chart types. 11.2.1 Pie Charts The PiePlot class generates tool tips using the PieToolTipGenerator interface. A standard implementation (StandardPieToolTipGenerator) is provided, and you are free to create your own implementations. To set the tool tip generator, use the following method in the PiePlot class: å public void setToolTipGenerator(PieToolTipGenerator generator); Sets the tool tip generator for the pie chart. If you set this to null, no tool tips will be generated. 11.2.2 Category Charts Category charts—including most of the bar charts generated by JFreeChart—are based on the CategoryPlot class and use a CategoryItemRenderer to draw each data item. The CategoryToolTipGenerator interface specifies the method via which the renderer will obtain tool tips (if required). To set the tool tip generator for a category plot’s item renderer, use the following method (defined in the AbstractCategoryItemRenderer class): 77 CHAPTER 11. TOOLTIPS 78 å public void setToolTipGenerator(CategoryToolTipGenerator generator); Sets the tool tip generator for the renderer. If you set this to null, no tool tips will be generated. 11.2.3 XY Charts XY charts—including scatter plots and all the time series charts generated by JFreeChart—are based on the XYPlot class and use an XYItemRenderer to draw each data item. The renderer generates tool tips (if required) using an XYToolTipGenerator. To set the tool tip generator for an XY plot’s item renderer, use the following method (defined in the AbstractXYItemRenderer class): å public void setToolTipGenerator(XYToolTipGenerator generator); Sets the tool tip generator for the renderer. If you set this to null, no tool tips will be generated. 11.3 Collecting Tool Tips Tool tips are collected, along with other chart entity information, using the ChartRenderingInfo class. You need to supply an instance of this class to JFreeChart’s draw() method, otherwise no tool tip information will be recorded (even if a generator has been registered with the plot or the plot’s item renderer, as described in the previous sections). Fortunately, the ChartPanel class takes care of this automatically, so if you are displaying your charts using the ChartPanel class you do not need to worry about how tool tips are collected—it is done for you. 11.4 Displaying Tool Tips Tool tips are automatically displayed by the ChartPanel class, provided that you have set up a tool tip generator for the plot (or the plot’s renderer). You can also enable or disable the display of tool tips in the ChartPanel class, using this method: å public void setDisplayToolTips(boolean flag); Switches the display of tool tips on or off. 11.5 Disabling Tool Tips The most effective way to disable tool tips is to set the tool tip generator to null. This ensures that no tool tip information is even generated, which can save memory and processing time (particularly for charts with large datasets). You can also disable the display of tool tips in the ChartPanel class, using the method given in the previous section. 11.6 Customising Tool Tips You can take full control of the text generated for each tool tip by providing your own implementation of the appropriate tool tip generator interface. Chapter 12 Item Labels 12.1 Introduction 12.1.1 Overview For many chart types, JFreeChart will allow you to display item labels in, on or near to each data item in a chart. For example, you can display the actual value represented by the bars in a bar chart—see figure 12.1. Figure 12.1: A bar chart with item labels This chapter covers how to: • make item labels visible (for the chart types that support item labels); • change the appearance (font and color) of item labels; • specify the location of item labels; • customise the item label text. A word of advice: use this feature sparingly. Charts are supposed to summarise your data—if you feel it is necessary to display the actual data values all over your chart, then perhaps your data is better presented in a table format. 79 CHAPTER 12. ITEM LABELS 12.1.2 80 Limitations There are some limitations with respect to the item labels in the current release of JFreeChart: • some renderers do not support item labels; • axis ranges are not automatically adjusted to take into account the item labels—some labels may disappear off the chart if sufficient margins are not set (use the setUpperMargin() and/or setLowerMargin() methods in the relevant axis to adjust this). In future releases of JFreeChart, some or all of these limitations will be addressed. 12.2 Displaying Item Labels 12.2.1 Overview Item labels are not visible by default, so you need to configure the renderer to create and display them. This involves two steps: • assign a CategoryItemLabelGenerator or XYItemLabelGenerator to the renderer—this is an object that assumes responsibility for creating the labels; • set a flag in the renderer to make the labels visible, either for all series or, if you prefer, on a per series basis. In addition, you have the option to customise the position, font and color of the item labels. These steps are detailed in the following sections. 12.2.2 Assigning a Label Generator Item labels are created by a label generator that is assigned to a renderer (the same mechanism is also used for tooltips). To assign a generator to a CategoryItemRenderer, use the following code: CategoryItemRenderer renderer = plot.getRenderer(); CategoryItemLabelGenerator generator = new StandardCategoryItemLabelGenerator( "{2}", new DecimalFormat("0.00")); renderer.setLabelGenerator(generator); Similarly, to assign a generator to an XYItemRenderer, use the following code: XYItemRenderer renderer = plot.getRenderer(); XYItemLabelGenerator generator = new StandardXYItemLabelGenerator( "{2}", new DecimalFormat("0.00")); renderer.setLabelGenerator(generator); You can customise the behaviour of the standard generator via settings that you can apply in the constructor, or you can create your own generator as described in section 12.5.2. 12.2.3 Making Labels Visible For All Series The setItemLabelsVisible() method sets a flag that controls whether or not the item labels are displayed (note that a label generator must be assigned to the renderer, or there will be no labels to display). For a CategoryItemRenderer: CategoryItemRenderer renderer = plot.getRenderer(); renderer.setItemLabelsVisible(true); Similarly, for a XYItemRenderer: XYItemRenderer renderer = plot.getRenderer(); renderer.setItemLabelsVisible(true); Once set, this flag takes precedence over any per series settings you may have made elsewhere. In order for the per series settings to apply, you need to set this flag to null (see section 12.2.4). CHAPTER 12. ITEM LABELS 12.2.4 81 Making Labels Visible For Selected Series If you prefer, you can set flags that control the visibility of the item labels on a per series basis. For example, item labels are displayed only for the first series in figure 12.2. Figure 12.2: Item labels for selected series only You can use code similar to the following: CategoryItemRenderer renderer = plot.getRenderer(); renderer.setItemLabelsVisible(null); // clears the ALL series flag renderer.setSeriesItemLabelsVisible(0, true); renderer.setSeriesItemLabelsVisible(1, false); Notice that the flag for “all series” has been set to null—this is important, because the “all series” flag takes precedence over the “per series” flags. 12.2.5 Troubleshooting If, after following the steps outlined in the previous sections, you still can’t see any labels on your chart, there are a couple of things to consider: • the renderer must have a label generator assigned to it—this is an object that creates the text items that are used for each label. • some renderers don’t yet support the display of item labels (refer to the documentation for the renderer you are using). 12.3 Item Label Appearance 12.3.1 Overview You can change the appearance of the item labels by changing the font and/or the color used to display the labels. As for most other renderer attributes, the settings can be made once for all series, or on a per series basis. In the current release of JFreeChart, labels are drawn with a transparent background. You cannot set a background color for the labels, nor can you specify that a border be drawn around the labels. This may change in the future. CHAPTER 12. ITEM LABELS 12.3.2 82 Changing the Label Font To change the font for the item labels in all series, you can use code similar to the following: CategoryItemRenderer renderer = plot.getRenderer(); renderer.setItemLabelFont(new Font("SansSerif", Font.PLAIN, 10)); Similarly, to set the font for individual series: CategoryItemRenderer renderer = plot.getRenderer(); // clear the settings for ALL series... renderer.setItemLabelFont(null); // add settings for individual series... renderer.setSeriesItemLabelFont(0, new Font("SansSerif", Font.PLAIN, 10)); renderer.setSeruesItemLabelFont(1, new Font("SansSerif", Font.BOLD, 10)); Notice how the font for all series has be set to null to prevent it from overriding the per series settings. 12.3.3 Changing the Label Color To change the color for the item labels in all series, you can use code similar to the following: CategoryItemRenderer renderer = plot.getRenderer(); renderer.setItemLabelPaint(Color.red); Similarly, to set the color for individual series: CategoryItemRenderer renderer = plot.getRenderer(); // clear the settings for ALL series... renderer.setItemLabelPaint(null); // add settings for individual series... renderer.setSeriesItemLabelPaint(0, Color.red); renderer.setSeriesItemLabelPaint(1, Color.blue); Once again, notice how the paint for all series has been set to null to prevent it from overriding the per series settings. 12.4 Item Label Positioning 12.4.1 Overview The positioning of item labels is controlled by four attributes that are combined into an ItemLabelPosition object. You can define label positions for items with positive and negative values independently, via the following methods in the CategoryItemRenderer interface: public void setPositiveItemLabelPosition(ItemLabelPosition position); public void setNegativeItemLabelPosition(ItemLabelPosition position); Understanding how these attributes impact the final position of individual labels is key to getting good results from the item label features in JFreeChart. There are four attributes: • the item label anchor - determines the base location for the item label; • the text anchor - determines the point on the label that is aligned to the base location; • the rotation anchor - this is the point on the label text about which the rotation (if any) is applied; • the rotation angle - the angle through which the label is rotated. These are described in the following sections. CHAPTER 12. ITEM LABELS 12.4.2 83 The Item Label Anchor The purpose of the item label anchor setting is to determine an (x, y) location on the chart that is near to the data item that is being labelled. The label is then aligned to this anchor point when it is being drawn. Refer to the ItemLabelAnchor documentation for more information. 12.4.3 The Text Anchor The text anchor determines which point on the label should be aligned with the anchor point described in the previous section. It is possible to align the center of the label with the anchor point, or the top-right of the label, or the bottom-left, and so on...refer to the TextAnchor documentation for all the options. Running the DrawStringDemo application in the org.jfree.demo package (included in the JCommon distribution) is a good way to gain an understanding of how the text anchor is used to align labels to a point on the screen. 12.4.4 The Rotation Anchor The rotation anchor defines a point on the label about which the rotation (if any) will be applied to the label. The DrawStringDemo class also demonstrates this feature. 12.4.5 The Rotation Angle The rotation angle defines the angle through which the label is rotated. The angle is specified in radians, and the rotation point is defined by the rotation anchor described in the previous section. 12.5 Customising the Item Label Text 12.5.1 Overview Up to this point, we’ve relied on the label generator built in to JFreeChart to create the text for the item labels. If you want to have complete control over the label text, you can write your own class that implements the CategoryItemLabelGenerator interface. In this section I provide a brief overview of the technique for implementing a custom label generator, then present two examples to illustrate the type of results you can achieve with this technique. 12.5.2 Implementing a Custom Item Label Generator To develop a custom label generator, you simply need to write a class that implements the method defined in the CategoryItemLabelGenerator interface: public String generateLabel(CategoryDataset dataset, int series, int category); The renderer will call this method at the point that it requires a String use for a label, and will pass in the CategoryDataset and the series and category indices for the current item. This means that you have full access to the entire dataset (not just the current item) for the creation of the label. The method can return an arbitrary String value, so you can apply any formatting you want to the result. It is also valid to return null if you prefer no label to be displayed. All this is best illustrated by way of examples, which are provided in the following sections. CHAPTER 12. ITEM LABELS 12.6 Example 1 - Values Above a Threshold 12.6.1 Overview 84 In this first example, the goal is to display labels for the items that have a value greater than some predefined threshold value (see figure 12.3). Figure 12.3: Item labels above a threshold It isn’t all that difficult to achieve, we simply need to: • write a class that implements the CategoryItemLabelGenerator interface, and implement the generateItemLabel() method in such a way that it returns null for any item where the value is less than the threshold; • create an instance of this new class, and assign it to the renderer using the setLabelGenerator() method. 12.6.2 Source Code The complete source code is presented below. /* ------------------* ItemLabelDemo1.java * ------------------* (C) Copyright 2004, 2005, by Object Refinery Limited. * */ package demo; import import import import java.awt.Color; java.awt.Dimension; java.awt.Font; java.text.NumberFormat; import javax.swing.JPanel; import import import import import import import import import import import org.jfree.chart.ChartFactory; org.jfree.chart.ChartPanel; org.jfree.chart.JFreeChart; org.jfree.chart.axis.NumberAxis; org.jfree.chart.labels.AbstractCategoryItemLabelGenerator; org.jfree.chart.labels.CategoryItemLabelGenerator; org.jfree.chart.plot.CategoryPlot; org.jfree.chart.plot.PlotOrientation; org.jfree.chart.renderer.category.CategoryItemRenderer; org.jfree.data.category.CategoryDataset; org.jfree.data.category.DefaultCategoryDataset; CHAPTER 12. ITEM LABELS import org.jfree.ui.ApplicationFrame; import org.jfree.ui.RefineryUtilities; /** * A simple demo showing a label generator that only displays labels for items * with a value that is greater than some threshold. */ public class ItemLabelDemo1 extends ApplicationFrame { /** * A custom label generator. */ static class LabelGenerator extends AbstractCategoryItemLabelGenerator implements CategoryItemLabelGenerator { /** The threshold. */ private double threshold; /** * Creates a new generator that only displays labels that are greater * than or equal to the threshold value. * * @param threshold the threshold value. */ public LabelGenerator(double threshold) { super("", NumberFormat.getInstance()); this.threshold = threshold; } /** * Generates a label for the specified item. The label is typically a * formatted version of the data value, but any text can be used. * * @param dataset the dataset (null not permitted). * @param series the series index (zero-based). * @param category the category index (zero-based). * * @return the label (possibly null). */ public String generateLabel(CategoryDataset dataset, int series, int category) { String result = null; Number value = dataset.getValue(series, category); if (value != null) { double v = value.doubleValue(); if (v > this.threshold) { result = value.toString(); // could apply formatting here } } return result; } } /** * Creates a new demo instance. * * @param title the frame title. */ public ItemLabelDemo1(String title) { super(title); CategoryDataset dataset = createDataset(); JFreeChart chart = createChart(dataset); ChartPanel chartPanel = new ChartPanel(chart); chartPanel.setPreferredSize(new Dimension(500, 270)); setContentPane(chartPanel); } /** * Returns a sample dataset. * * @return The dataset. */ private static CategoryDataset createDataset() { DefaultCategoryDataset dataset = new DefaultCategoryDataset(); 85 CHAPTER 12. ITEM LABELS dataset.addValue(11.0, dataset.addValue(44.3, dataset.addValue(93.0, dataset.addValue(35.6, dataset.addValue(75.1, return dataset; "S1", "S1", "S1", "S1", "S1", "C1"); "C2"); "C3"); "C4"); "C5"); } /** * Creates a sample chart. * * @param dataset the dataset. * * @return the chart. */ private static JFreeChart createChart(CategoryDataset dataset) { // create the chart... JFreeChart chart = ChartFactory.createBarChart( "Item Label Demo 1", // chart title "Category", // domain axis label "Value", // range axis label dataset, // data PlotOrientation.VERTICAL, // orientation false, // include legend true, // tooltips? false // URLs? ); chart.setBackgroundPaint(Color.white); CategoryPlot plot = chart.getCategoryPlot(); plot.setBackgroundPaint(Color.lightGray); plot.setDomainGridlinePaint(Color.white); plot.setRangeGridlinePaint(Color.white); NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis(); rangeAxis.setUpperMargin(0.15); CategoryItemRenderer renderer = plot.getRenderer(); renderer.setItemLabelGenerator(new LabelGenerator(50.0)); renderer.setItemLabelFont(new Font("Serif", Font.PLAIN, 20)); renderer.setItemLabelsVisible(true); return chart; } /** * Creates a panel for the demo (used by SuperDemo.java). * * @return A panel. */ public static JPanel createDemoPanel() { JFreeChart chart = createChart(createDataset()); return new ChartPanel(chart); } /** * Starting point for the demonstration application. * * @param args ignored. */ public static void main(String[] args) { ItemLabelDemo1 demo = new ItemLabelDemo1("Item Label Demo 1"); demo.pack(); RefineryUtilities.centerFrameOnScreen(demo); demo.setVisible(true); } } 86 CHAPTER 12. ITEM LABELS 12.7 Example 2 - Displaying Percentages 12.7.1 Overview 87 In this example, the requirement is to display a bar chart where each bar is labelled with the value represented by the bar and also a percentage (where the percentage is calculated relative to a particular bar within the series OR the total of all the values in the series)—see figure 12.4. Figure 12.4: Percentage item labels In this implementation, the label generator calculates the percentage value on-the-fly. If a category index is supplied in the constructor, the base value used to calculate the percentage is taken from the specified category within the current series. If no category index is available, then the total of all the values in the current series is used as the base. A default percentage formatter is created within the label generator—a more sophisticated implementation would provide the ability for the formatter to be customised via the generator’s constructor. 12.7.2 Source Code The complete source code follows. /* ------------------* ItemLabelDemo2.java * ------------------* (C) Copyright 2005, by Object Refinery Limited. * */ package demo; import java.awt.Color; /** * A simple demo showing a label generator that displays labels that include * a percentage calculation. */ public class ItemLabelDemo2 extends ApplicationFrame { /** * A custom label generator. */ static class LabelGenerator extends AbstractCategoryItemLabelGenerator implements CategoryItemLabelGenerator { /** * The index of the category on which to base the percentage CHAPTER 12. ITEM LABELS * (null = use series total). */ private Integer category; /** A percent formatter. */ private NumberFormat formatter = NumberFormat.getPercentInstance(); /** * Creates a new label generator that displays the item value and a * percentage relative to the value in the same series for the * specified category. * * @param category the category index (zero-based). */ public LabelGenerator(int category) { this(new Integer(category)); } /** * Creates a new label generator that displays the item value and * a percentage relative to the value in the same series for the * specified category. If the category index is null, * the total of all items in the series is used. * * @param category the category index (null permitted). */ public LabelGenerator(Integer category) { super("", NumberFormat.getInstance()); this.category = category; } /** * Generates a label for the specified item. The label is typically * a formatted version of the data value, but any text can be used. * * @param dataset the dataset (null not permitted). * @param series the series index (zero-based). * @param category the category index (zero-based). * * @return the label (possibly null). */ public String generateLabel(CategoryDataset dataset, int series, int category) { String result = null; double base = 0.0; if (this.category != null) { final Number b = dataset.getValue(series, this.category.intValue()); base = b.doubleValue(); } else { base = calculateSeriesTotal(dataset, series); } Number value = dataset.getValue(series, category); if (value != null) { final double v = value.doubleValue(); // you could apply some formatting here result = value.toString() + " (" + this.formatter.format(v / base) + ")"; } return result; } /** * Calculates a series total. * * @param dataset the dataset. * @param series the series index. * * @return The total. */ private double calculateSeriesTotal(CategoryDataset dataset, int series) { double result = 0.0; for (int i = 0; i < dataset.getColumnCount(); i++) { Number value = dataset.getValue(series, i); if (value != null) { result = result + value.doubleValue(); } } 88 CHAPTER 12. ITEM LABELS return result; } } /** * Creates a new demo instance. * * @param title the frame title. */ public ItemLabelDemo2(String title) { super(title); CategoryDataset dataset = createDataset(); JFreeChart chart = createChart(dataset); ChartPanel chartPanel = new ChartPanel(chart); chartPanel.setPreferredSize(new Dimension(500, 270)); setContentPane(chartPanel); } /** * Returns a sample dataset. * * @return the dataset. */ private static CategoryDataset createDataset() { DefaultCategoryDataset dataset = new DefaultCategoryDataset(); dataset.addValue(100.0, "S1", "C1"); dataset.addValue(44.3, "S1", "C2"); dataset.addValue(93.0, "S1", "C3"); dataset.addValue(80.0, "S2", "C1"); dataset.addValue(75.1, "S2", "C2"); dataset.addValue(15.1, "S2", "C3"); return dataset; } /** * Creates a sample chart. * * @param dataset the dataset. * * @return the chart. */ private static JFreeChart createChart(CategoryDataset dataset) { // create the chart... JFreeChart chart = ChartFactory.createBarChart( "Item Label Demo 2", // chart title "Category", // domain axis label "Value", // range axis label dataset, // data PlotOrientation.HORIZONTAL, // orientation true, // include legend true, // tooltips? false // URLs? ); chart.setBackgroundPaint(Color.white); CategoryPlot plot = chart.getCategoryPlot(); plot.setBackgroundPaint(Color.lightGray); plot.setDomainGridlinePaint(Color.white); plot.setRangeGridlinePaint(Color.white); plot.setRangeAxisLocation(AxisLocation.BOTTOM_OR_LEFT); NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis(); rangeAxis.setUpperMargin(0.25); CategoryItemRenderer renderer = plot.getRenderer(); renderer.setItemLabelsVisible(true); // use one or the other of the following lines to see the // different modes for the label generator... renderer.setItemLabelGenerator(new LabelGenerator(null)); //renderer.setLabelGenerator(new LabelGenerator(0)); return chart; 89 CHAPTER 12. ITEM LABELS } /** * Creates a panel for the demo (used by SuperDemo.java). * * @return A panel. */ public static JPanel createDemoPanel() { JFreeChart chart = createChart(createDataset()); return new ChartPanel(chart); } /** * Starting point for the demonstration application. * * @param args ignored. */ public static void main(String[] args) { ItemLabelDemo2 demo = new ItemLabelDemo2("Item Label Demo 2"); demo.pack(); RefineryUtilities.centerFrameOnScreen(demo); demo.setVisible(true); } } 90 Chapter 13 Multiple Axes and Datasets 13.1 Introduction JFreeChart supports the use of multiple axes and datasets in the CategoryPlot and XYPlot classes. You can use this feature to display two or more datasets on a single chart, while making allowance for the fact that the datasets may contain data of vastly different magnitudes—see figure 13.1 for an example. Figure 13.1: A chart with multiple axes Typical charts constructed with JFreeChart use a plot that has a single dataset, a single renderer, a single domain axis and a single range axis. However, it is possible to add multiple datasets, renderers and axes to a plot. In this section, an example is presented showing how to use these additional datasets, renderers and axes. 13.2 An Example 13.2.1 Introduction The MultipleAxisDemo1.java application (included in the JFreeChart Demo distribution) provides a good example of how to create a chart with multiple axes. This section provides some notes on the steps taken within that code. 91 CHAPTER 13. MULTIPLE AXES AND DATASETS 13.2.2 92 Create a Chart To create a chart with multiple axes, datasets, and renderers, you should first create a regular chart (for example, using the ChartFactory class). You can use any chart that is constructed using a CategoryPlot or an XYPlot. In the example, a time series chart is created as follows: XYDataset dataset1 JFreeChart chart = "Multiple Axis "Time of Day", "Primary Range dataset1, true, true, false ); 13.2.3 = createDataset("Series 1", 100.0, new Minute(), 200); ChartFactory.createTimeSeriesChart( Demo 1", Axis", Adding an Additional Axis To add an additional axis to a plot, you can use the setRangeAxis() method: NumberAxis axis2 = new NumberAxis("Range Axis 2"); plot.setRangeAxis(1, axis2); plot.setRangeAxisLocation(1, AxisLocation.BOTTOM OR RIGHT); The setRangeAxis() method is used to add the axis to the plot. Note that an index of 1 (one) has been used—you can add as many additional axes as you require, by incrementing the index each time you add a new axis. The setRangeAxisLocation() method allows you to specify where the axis will appear on the chart, using the AxisLocation class. You can have the axis on the same side as the primary axis, or on the opposite side—the choice is yours. In the example, BOTTOM OR RIGHT is specified, which means (for a range axis) on the right if the plot has a vertical orientation, or at the bottom if the plot has a horizontal orientation. At this point, no additional dataset has been added to the chart, so if you were to display the chart you would see the additional axis, but it would have no data plotted against it. 13.2.4 Adding an Additional Dataset To add an additional dataset to a plot, use the setDataset() method: XYDataset dataset2 = ... // up to you plot.setDataset(1, dataset2); By default, the dataset will be plotted against the primary range axis. To have the dataset plotted against a different axis, use the mapDatasetToDomainAxis() and mapDatasetToRangeAxis() methods. These methods accept two arguments, the first is the index of the dataset, and the second is the index of the axis. 13.2.5 Adding an Additional Renderer When you add an additional dataset, usually it makes sense to add an additional renderer to go with the dataset. Use the setRenderer() method: XYItemRenderer renderer2 = ... // up to you plot.setRenderer(1, renderer2); The index (1 in this case) should correspond to the index of the dataset added previously. Note: if you don’t specify an additional renderer, the primary renderer will be used instead. In that case, the series colors will be shared between the primary dataset and the additional dataset. CHAPTER 13. MULTIPLE AXES AND DATASETS 13.3 93 Hints and Tips When using multiple axes, you need to provide some visual cue to readers to indicate which axis applies to a particular series. In the MultipleAxisDemo1.java application, the color of the axis label text has been changed to match the series color. Additional demos available for download with the JFreeChart Developer Guide include: • DualAxisDemo1.java • DualAxisDemo2.java • DualAxisDemo3.java • DualAxisDemo4.java • MultipleAxisDemo1.java • MultipleAxisDemo2.java • MultipleAxisDemo3.java Chapter 14 Combined Charts 14.1 Introduction JFreeChart supports combined charts via several plot classes that can manage any number of subplots: • CombinedDomainCategoryPlot / CombinedRangeCategoryPlot; • CombinedDomainXYPlot / CombinedRangeXYPlot; This section presents a few examples that use the combined chart facilities provided by JFreeChart. All the examples are included in the JFreeChart demo collection. 14.2 Combined Domain Category Plot 14.2.1 Overview A combined domain category plot is a plot that displays two or more subplots (instances of CategoryPlot) that share a common domain axis. Each subplot maintains its own range axis. An example is shown in figure 14.1. Figure 14.1: A combined domain category plot It is possible to display this chart with a horizontal or vertical orientation—the example shown has a vertical orientation. 94 CHAPTER 14. COMBINED CHARTS 14.2.2 95 Constructing the Chart A demo application (CombinedCategoryPlotDemo1.java, available for download with the JFreeChart Developer Guide) provides an example of how to create this type of chart. The key step is the creation of a CombinedDomainCategoryPlot instance, to which subplots are added: CategoryAxis domainAxis = new CategoryAxis("Category"); CombinedDomainCategoryPlot plot = new CombinedDomainCategoryPlot(domainAxis); plot.add(subplot1, 2); plot.add(subplot2, 1); JFreeChart result = new JFreeChart( "Combined Domain Category Plot Demo", new Font("SansSerif", Font.BOLD, 12), plot, true ); Notice how subplot1 has been added with a weight of 2 (the second argument in the add() method, while subplot2 has been added with a weight of 1. This controls the amount of space allocated to each plot. The subplots are regular CategoryPlot instances that have had their domain axis set to null. For example, in the demo application the following code is used (it includes some customisation of the subplots): CategoryDataset dataset1 = createDataset1(); NumberAxis rangeAxis1 = new NumberAxis("Value"); rangeAxis1.setStandardTickUnits(NumberAxis.createIntegerTickUnits()); LineAndShapeRenderer renderer1 = new LineAndShapeRenderer(); renderer1.setBaseToolTipGenerator(new StandardCategoryToolTipGenerator()); CategoryPlot subplot1 = new CategoryPlot(dataset1, null, rangeAxis1, renderer1); subplot1.setDomainGridlinesVisible(true); CategoryDataset dataset2 = createDataset2(); NumberAxis rangeAxis2 = new NumberAxis("Value"); rangeAxis2.setStandardTickUnits(NumberAxis.createIntegerTickUnits()); BarRenderer renderer2 = new BarRenderer(); renderer2.setBaseToolTipGenerator(new StandardCategoryToolTipGenerator()); CategoryPlot subplot2 = new CategoryPlot(dataset2, null, rangeAxis2, renderer2); subplot2.setDomainGridlinesVisible(true); 14.3 Combined Range Category Plot 14.3.1 Overview A combined range category plot is a plot that displays two or more subplots (instances of CategoryPlot) that share a common range axis. Each subplot maintains its own domain axis. An example is shown in figure 14.2. It is possible to display this chart with a horizontal or vertical orientation (the example above has a vertical orientation). 14.3.2 Constructing the Chart A demo application (CombinedCategoryPlotDemo2.java, available for download with the JFreeChart Developer Guide) provides an example of how to create this type of chart. The key step is the creation of a CombinedRangeCategoryPlot instance, to which subplots are added: ValueAxis rangeAxis = new NumberAxis("Value"); CombinedRangeCategoryPlot plot = new CombinedRangeCategoryPlot(rangeAxis); plot.add(subplot1, 3); plot.add(subplot2, 2); JFreeChart result = new JFreeChart( "Combined Range Category Plot Demo", new Font("SansSerif", Font.BOLD, 12), plot, true ); CHAPTER 14. COMBINED CHARTS 96 Figure 14.2: A combined range category plot. Notice how subplot1 has been added with a weight of 3 (the second argument in the add() method), while subplot2 has been added with a weight of 2. This controls the amount of space allocated to each plot. The subplots are regular CategoryPlot instances that have had their range axis set to null. For example, in the demo application the following code is used (it includes some customisation of the subplots): CategoryDataset dataset1 = createDataset1(); CategoryAxis domainAxis1 = new CategoryAxis("Class 1"); domainAxis1.setCategoryLabelPositions(CategoryLabelPositions.UP 45); domainAxis1.setMaxCategoryLabelWidthRatio(5.0f); LineAndShapeRenderer renderer1 = new LineAndShapeRenderer(); renderer1.setBaseToolTipGenerator(new StandardCategoryToolTipGenerator()); CategoryPlot subplot1 = new CategoryPlot(dataset1, domainAxis1, null, renderer1); subplot1.setDomainGridlinesVisible(true); CategoryDataset dataset2 = createDataset2(); CategoryAxis domainAxis2 = new CategoryAxis("Class 2"); domainAxis2.setCategoryLabelPositions(CategoryLabelPositions.UP 45); domainAxis2.setMaxCategoryLabelWidthRatio(5.0f); BarRenderer renderer2 = new BarRenderer(); renderer2.setBaseToolTipGenerator(new StandardCategoryToolTipGenerator()); CategoryPlot subplot2 = new CategoryPlot(dataset2, domainAxis2, null, renderer2); subplot2.setDomainGridlinesVisible(true); 14.4 Combined Domain XY Plot 14.4.1 Overview A combined domain XY plot is a plot that displays two or more subplots (instances of XYPlot) that share a common domain axis. Each subplot maintains its own range axis. An example is shown in figure 14.3. It is possible to display this chart with a horizontal or vertical orientation (the example shown has a vertical orientation). 14.4.2 Constructing the Chart A demo application (CombinedXYPlotDemo1.java, available for download with the JFreeChart Developer Guide) provides an example of how to create this type of chart. The key step is the creation of a CombinedDomainXYPlot instance, to which subplots are added: CombinedDomainXYPlot plot = new CombinedDomainXYPlot(new NumberAxis("Domain")); plot.setGap(10.0); CHAPTER 14. COMBINED CHARTS 97 Figure 14.3: A combined domain XY plot plot.add(subplot1, 1); plot.add(subplot2, 1); plot.setOrientation(PlotOrientation.VERTICAL); return new JFreeChart( "CombinedDomainXYPlot Demo", JFreeChart.DEFAULT TITLE FONT, plot, true ); Notice how the subplots are added with weights (both 1 in this case). This controls the amount of space allocated to each plot. The subplots are regular XYPlot instances that have had their domain axis set to null. For example, in the demo application the following code is used (it includes some customisation of the subplots): XYDataset data1 = createDataset1(); XYItemRenderer renderer1 = new StandardXYItemRenderer(); NumberAxis rangeAxis1 = new NumberAxis("Range 1"); XYPlot subplot1 = new XYPlot(data1, null, rangeAxis1, renderer1); subplot1.setRangeAxisLocation(AxisLocation.BOTTOM OR LEFT); XYTextAnnotation annotation = new XYTextAnnotation("Hello!", 50.0, 10000.0); annotation.setFont(new Font("SansSerif", Font.PLAIN, 9)); annotation.setRotationAngle(Math.PI / 4.0); subplot1.addAnnotation(annotation); // create subplot 2... XYDataset data2 = createDataset2(); XYItemRenderer renderer2 = new StandardXYItemRenderer(); NumberAxis rangeAxis2 = new NumberAxis("Range 2"); rangeAxis2.setAutoRangeIncludesZero(false); XYPlot subplot2 = new XYPlot(data2, null, rangeAxis2, renderer2); subplot2.setRangeAxisLocation(AxisLocation.TOP OR LEFT); 14.5 Combined Range XY Plot 14.5.1 Overview A combined range XY plot is a plot that displays two or more subplots (instances of XYPlot) that share a common range axis. Each subplot maintains its own domain axis. An example is shown in figure 14.4. It is possible to display this chart with a horizontal or vertical orientation (the example shown has a vertical orientation). CHAPTER 14. COMBINED CHARTS 98 Figure 14.4: A combined range XY plot 14.5.2 Constructing the Chart A demo application (CombinedXYPlotDemo2.java, available for download with the JFreeChart Developer Guide) provides an example of how to create this type of chart. The key step is the creation of a CombinedRangeXYPlot instance, to which subplots are added: // create the plot... CombinedRangeXYPlot plot = new CombinedRangeXYPlot(new NumberAxis("Value")); plot.add(subplot1, 1); plot.add(subplot2, 1); return new JFreeChart( "Combined (Range) XY Plot", JFreeChart.DEFAULT TITLE FONT, plot, true ); Notice how the subplots are added with weights (both 1 in this case). This controls the amount of space allocated to each plot. The subplots are regular XYPlot instances that have had their range axis set to null. For example, in the demo application the following code is used (it includes some customisation of the subplots): // create subplot 1... IntervalXYDataset data1 = createDataset1(); XYItemRenderer renderer1 = new XYBarRenderer(0.20); renderer1.setToolTipGenerator( new StandardXYToolTipGenerator( new SimpleDateFormat("d-MMM-yyyy"), new DecimalFormat("0,000.0") ) ); XYPlot subplot1 = new XYPlot(data1, new DateAxis("Date"), null, renderer1); // create subplot 2... XYDataset data2 = createDataset2(); XYItemRenderer renderer2 = new StandardXYItemRenderer(); renderer2.setToolTipGenerator( new StandardXYToolTipGenerator( new SimpleDateFormat("d-MMM-yyyy"), new DecimalFormat("0,000.0") ) ); XYPlot subplot2 = new XYPlot(data2, new DateAxis("Date"), null, renderer2); Chapter 15 Datasets and JDBC 15.1 Introduction In this section, I describe the use of several datasets that are designed to work with JDBC to obtain data from database tables: • JDBCPieDataset • JDBCCategoryDataset • JDBCXYDataset These datasets have been developed by Bryan Scott of the Australian Antarctic Division. 15.2 About JDBC JDBC is a high-level Java API for working with relational databases. JDBC does a good job of furthering Java’s platform independence, making it possible to write portable code that will work with many different database systems. JDBC provides a mechanism for loading a JDBC driver specific to the database system actually being used. JDBC drivers are available for many databases, on many different platforms. 15.3 Sample Data To see the JDBC datasets in action, you need to create some sample data in a test database. Here is listed some sample data that will be used to create a pie chart, a bar chart and a time series chart. A pie chart will be created using this data (in a table called piedata1): CATEGORY | VALUE ---------+-----London | 54.3 New York | 43.4 Paris | 17.9 Similarly, a bar chart will be created using this data (in a table called categorydata1): CATEGORY | SERIES1 | SERIES2 | SERIES3 ---------+---------+---------+-------London | 54.3 | 32.1 | 53.4 New York | 43.4 | 54.3 | 75.2 Paris | 17.9 | 34.8 | 37.1 99 CHAPTER 15. DATASETS AND JDBC 100 Finally, a time series chart will be generated using this data (in a table called xydata1): X | SERIES1 | SERIES2 | SERIES3 -----------+---------+---------+-------1-Aug-2002 | 54.3 | 32.1 | 53.4 2-Aug-2002 | 43.4 | 54.3 | 75.2 3-Aug-2002 | 39.6 | 55.9 | 37.1 4-Aug-2002 | 35.4 | 55.2 | 27.5 5-Aug-2002 | 33.9 | 49.8 | 22.3 6-Aug-2002 | 35.2 | 48.4 | 17.7 7-Aug-2002 | 38.9 | 49.7 | 15.3 8-Aug-2002 | 36.3 | 44.4 | 12.1 9-Aug-2002 | 31.0 | 46.3 | 11.0 You should set up a test database containing these tables...ask your database administrator to help you if necessary. I’ve called my test database jfreechartdb, but you can change the name if you want to. In the next section I document the steps I used to set up this sample data usingPostgreSQL, the database system that I have available for testing purposes. If you are using a different system, you may need to perform a slightly different procedure—refer to your database documentation for information. 15.4 PostgreSQL 15.4.1 About PostgreSQL PostgreSQL is a powerful object-relational database server, distributed under an open-source licence. You can find out more about PostgreSQL at: http://www.postgresql.org Note: although PostgreSQL is free, it has most of the features of large commercial relational database systems. I encourage you to install it and try it out. 15.4.2 Creating a New Database First, while logged in as the database administrator, I create a test database called jfreechartdb: CREATE DATABASE jfreechartdb; Next, I create a user jfreechart: CREATE USER jfreechart WITH PASSWORD ’password’; This username and password will be used to connect to the database via JDBC. 15.4.3 Creating the Pie Chart Data To create the table for the pie dataset: CREATE TABLE piedata1 ( category VARCHAR(32), value FLOAT ); ...and to populate it: INSERT INTO piedata1 VALUES (’London’, 54.3); INSERT INTO piedata1 VALUES (’New York’, 43.4); INSERT INTO piedata1 VALUES (’Paris’, 17.9); CHAPTER 15. DATASETS AND JDBC 15.4.4 101 Creating the Category Chart Data To create the table for the category dataset: CREATE TABLE category series1 series2 series3 ); categorydata1 ( VARCHAR(32), FLOAT, FLOAT, FLOAT ...and to populate it: INSERT INTO categorydata1 VALUES (’London’, 54.3, 32.1, 53.4); INSERT INTO categorydata1 VALUES (’New York’, 43.4, 54.3, 75.2); INSERT INTO categorydata1 VALUES (’Paris’, 17.9, 34.8, 37.1); 15.4.5 Creating the XY Chart Data To create the table for the XY dataset: CREATE TABLE date series1 series2 series3 ); xydata1 ( DATE, FLOAT, FLOAT, FLOAT ...and to populate it: INSERT INSERT INSERT INSERT INSERT INSERT INSERT INSERT INSERT INTO INTO INTO INTO INTO INTO INTO INTO INTO xydata1 xydata1 xydata1 xydata1 xydata1 xydata1 xydata1 xydata1 xydata1 VALUES VALUES VALUES VALUES VALUES VALUES VALUES VALUES VALUES (’1-Aug-2002’, (’2-Aug-2002’, (’3-Aug-2002’, (’4-Aug-2002’, (’5-Aug-2002’, (’6-Aug-2002’, (’7-Aug-2002’, (’8-Aug-2002’, (’9-Aug-2002’, 54.3, 43.4, 39.6, 35.4, 33.9, 35.2, 38.9, 36.3, 31.0, 32.1, 54.3, 55.9, 55.2, 49.8, 48.4, 49.7, 44.4, 46.3, 53.4); 75.2); 37.1); 27.5); 22.3); 17.7); 15.3); 12.1); 11.0); Granting Table Permissions The last step in setting up the sample database is to grant read access to the new tables to the user jfreechart: GRANT SELECT ON piedata1 TO jfreechart; GRANT SELECT ON categorydata1 TO jfreechart; GRANT SELECT ON xydata1 TO jfreechart; 15.5 The JDBC Driver To access the sample data via JDBC, you need to obtain a JDBC driver for your database. For PostgreSQL, I downloaded a free driver from: http://jdbc.postgresql.org In order to use this driver, I need to ensure that the jar file containing the driver is on the classpath. CHAPTER 15. DATASETS AND JDBC 15.6 The Demo Applications 15.6.1 JDBCPieChartDemo 102 The JDBCPieChartDemo application will generate a pie chart using the data in the piedata1 table, providing that you have configured your database correctly. The code for reading the data is in the readData() method: private PieDataset readData() { JDBCPieDataset data = null; String url = "jdbc:postgresql://nomad/jfreechartdb"; Connection con; try { Class.forName("org.postgresql.Driver"); } catch (ClassNotFoundException e) { System.err.print("ClassNotFoundException: "); System.err.println(e.getMessage()); } try { con = DriverManager.getConnection(url, "jfreechart", "password"); data = new JDBCPieDataset(con); String sql = "SELECT * FROM PIEDATA1;"; data.executeQuery(sql); con.close(); } catch (SQLException e) { System.err.print("SQLException: "); System.err.println(e.getMessage()); } catch (Exception e) { System.err.print("Exception: "); System.err.println(e.getMessage()); } return data; } Important things to note in the code are: • the url used to reference the test database includes the name of my test server (nomad), you will need to modify this; • a connection is made to the database using the username/password combination jfreechart/password; • the query used to pull the data from the database is a standard SELECT query, but you can use any SQL query as long as it returns columns in the required format (refer to the JDBCPieDataset class documentation for details). 15.6.2 JDBCCategoryChartDemo The JDBCCategoryChartDemo application generates a bar chart using the data in the categorydata1 table. The code is almost identical to the JDBCPieChartDemo. Once again, you can use any SQL query as long as it returns columns in the required format (refer to the JDBCCategoryDataset class documentation for details). 15.6.3 JDBCXYChartDemo The JDBCXYChartDemo application generates a time series chart using the data in the xydata1 table. The code is almost identical to the JDBCPieChartDemo. Once again, you can use any SQL query as long as it returns columns in the required format (refer to the JDBCXYDataset class documentation for details). Chapter 16 Exporting Charts to Acrobat PDF 16.1 Introduction In this section, I describe how to export a chart to an Acrobat PDF file using JFreeChart and iText. Along with the description, I provide a small demonstration application that creates a PDF file containing a basic chart. The resulting file can be viewed using Acrobat Reader, or any other software that is capable of reading and displaying PDF files. 16.2 What is Acrobat PDF? Acrobat PDF is a widely used electronic document format. Its popularity is due, at least in part, to its ability to reproduce high quality output on a variety of different platforms. PDF was created by Adobe Systems Incorporated. Adobe provide a free (but closed source) application called Acrobat Reader for reading PDF documents. Acrobat Reader is available on most end-user computing platforms, including GNU/Linux, Windows, Unix, Macintosh and others. If your system doesn’t have Acrobat Reader installed, you can download a copy from: http://www.adobe.com/products/acrobat/readstep.html On some platforms, there are free (in the GNU sense) software packages available for viewing PDF files. Ghostview on Linux is one example. 16.3 iText iText is a popular free Java class library for creating documents in PDF format. It is developed by Bruno Lowagie, Paulo Soares and others. The home page for iText is: http://www.lowagie.com/iText At the time of writing, the latest version of iText is 2.0.1. 16.4 Graphics2D JFreeChart can work easily with iText because iText provides a Graphics2D implementation. Before I proceed to the demonstration application, I will briefly review the Graphics2D class. The java.awt.Graphics2D class, part of the standard Java 2D API, defines a range of methods for drawing text and graphics in a two dimensional space. Particular subclasses of Graphics2D handle all the details of mapping the output (text and graphics) to specific devices. 103 CHAPTER 16. EXPORTING CHARTS TO ACROBAT PDF 104 JFreeChart has been designed to draw charts using only the methods defined by the Graphics2D class. This means that JFreeChart can generate output to any target that can provide a Graphics2D subclass. JFreeChart +draw(Graphics2D) Graphics2D PDF Figure 16.1: The JFreeChart draw() method iText incorporates a PdfGraphics2D class, which means that iText is capable of generating PDF content based on calls to the methods defined by the Graphics2D class...and this makes it easy to produce charts in PDF format, as you will see in the following sections. 16.5 Getting Started To compile and run the demonstration application, you will need the following jar files: File: Description: jfreechart-1.0.9.jar jcommon-1.0.12.jar itext-2.0.1.jar The JFreeChart class library. The JCommon class library (used by JFreeChart). The iText class library. The first two files are included with JFreeChart, and the third is the iText runtime. 16.6 The Application The first thing the sample application needs to do is create a chart. Here we create a time series chart: // create a chart... XYDataset dataset = createDataset(); JFreeChart chart = ChartFactory.createTimeSeriesChart( "Legal & General Unit Trust Prices", "Date", "Price Per Unit", dataset, true, true, false ); // some additional chart customisation here... There is nothing special here—in fact you could replace the code above with any other code that creates a JFreeChart object. You are encouraged to experiment. Next, I will save a copy of the chart in a PDF file: // write the chart to a PDF file... File fileName = new File(System.getProperty("user.home") + "/jfreechart1.pdf"); saveChartAsPDF(fileName, chart, 400, 300, new DefaultFontMapper()); CHAPTER 16. EXPORTING CHARTS TO ACROBAT PDF 105 There are a couple of things to note here. First, I have hard-coded the filename used for the PDF file. I’ve done this to keep the sample code short. In a real application, you would provide some other means for the user to specify the filename, perhaps by presenting a file chooser dialog. Second, the saveChartAsPDF() method hasn’t been implemented yet! To create that method, I’ll first write another more general method, writeChartAsPDF(). This method performs most of the work that will be required by the saveChartAsPDF() method, but it writes data to an output stream rather than a file. public static void writeChartAsPDF(OutputStream out, JFreeChart chart, int width, int height, FontMapper mapper) throws IOException { Rectangle pagesize = new Rectangle(width, height); Document document = new Document(pagesize, 50, 50, 50, 50); try { PdfWriter writer = PdfWriter.getInstance(document, out); document.addAuthor("JFreeChart"); document.addSubject("Demonstration"); document.open(); PdfContentByte cb = writer.getDirectContent(); PdfTemplate tp = cb.createTemplate(width, height); Graphics2D g2 = tp.createGraphics(width, height, mapper); Rectangle2D r2D = new Rectangle2D.Double(0, 0, width, height); chart.draw(g2, r2D); g2.dispose(); cb.addTemplate(tp, 0, 0); } catch (DocumentException de) { System.err.println(de.getMessage()); } document.close(); } Inside this method, you will see some code that sets up and opens an iText document, obtains a Graphics2D instance from the document, draws the chart using the Graphics2D object, and closes the document. You will also notice that one of the parameters for this method is a FontMapper object. The FontMapper interface maps Java Font objects to the BaseFont objects used by iText. The DefaultFontMapper class is predefined with default mappings for the Java logical fonts. If you use only these fonts, then it is enough to create a DefaultFontMapper using the default constructor. If you want to use other fonts (for example, a font that supports a particular character set) then you need to do more work. I’ll give an example of this later. In the implementation of the writeChartAsPDF() method, I’ve chosen to create a PDF document with a custom page size (matching the requested size of the chart). You can easily adapt the code to use a different page size, alter the size and position of the chart and even draw multiple charts inside one PDF document. Now that I have a method to send PDF data to an output stream, it is straightforward to implement the saveChartAsPDF() method. Simply create a FileOutputStream and pass it on to the writeChartAsPDF() method: public static void saveChartAsPDF(File file, JFreeChart chart, int width, int height, FontMapper mapper) throws IOException { OutputStream out = new BufferedOutputStream(new FileOutputStream(file)); writeChartAsPDF(out, chart, width, height, mapper); out.close(); } CHAPTER 16. EXPORTING CHARTS TO ACROBAT PDF 106 This is all the code that is required. The pieces can be assembled into the following program (reproduced in full here so that you can see all the required import statements and the context in which the code is run): /* ------------------* PDFExportDemo1.java * ------------------* (C) Copyright 2002-2005, by Object Refinery Limited. * */ package demo.pdf; import import import import import import import import java.awt.Graphics2D; java.awt.geom.Rectangle2D; java.io.BufferedOutputStream; java.io.File; java.io.FileOutputStream; java.io.IOException; java.io.OutputStream; java.text.SimpleDateFormat; import import import import import import import import import org.jfree.chart.ChartFactory; org.jfree.chart.JFreeChart; org.jfree.chart.axis.DateAxis; org.jfree.chart.plot.XYPlot; org.jfree.chart.renderer.xy.XYLineAndShapeRenderer; org.jfree.data.time.Month; org.jfree.data.time.TimeSeries; org.jfree.data.time.TimeSeriesCollection; org.jfree.data.xy.XYDataset; import import import import import import import import com.lowagie.text.Document; com.lowagie.text.DocumentException; com.lowagie.text.Rectangle; com.lowagie.text.pdf.DefaultFontMapper; com.lowagie.text.pdf.FontMapper; com.lowagie.text.pdf.PdfContentByte; com.lowagie.text.pdf.PdfTemplate; com.lowagie.text.pdf.PdfWriter; /** * A simple demonstration showing how to write a chart to PDF format using * JFreeChart and iText. *

* You can download iText from http://www.lowagie.com/iText. */ public class PDFExportDemo1 { /** * Saves a chart to a PDF file. * * @param file the file. * @param chart the chart. * @param width the chart width. * @param height the chart height. */ public static void saveChartAsPDF(File file, JFreeChart chart, int width, int height, FontMapper mapper) throws IOException { OutputStream out = new BufferedOutputStream(new FileOutputStream(file)); writeChartAsPDF(out, chart, width, height, mapper); out.close(); } /** * Writes a chart to an output stream in PDF format. * * @param out the output stream. * @param chart the chart. * @param width the chart width. * @param height the chart height. * */ public static void writeChartAsPDF(OutputStream out, JFreeChart chart, CHAPTER 16. EXPORTING CHARTS TO ACROBAT PDF int width, int height, FontMapper mapper) throws IOException { Rectangle pagesize = new Rectangle(width, height); Document document = new Document(pagesize, 50, 50, 50, 50); try { PdfWriter writer = PdfWriter.getInstance(document, out); document.addAuthor("JFreeChart"); document.addSubject("Demonstration"); document.open(); PdfContentByte cb = writer.getDirectContent(); PdfTemplate tp = cb.createTemplate(width, height); Graphics2D g2 = tp.createGraphics(width, height, mapper); Rectangle2D r2D = new Rectangle2D.Double(0, 0, width, height); chart.draw(g2, r2D); g2.dispose(); cb.addTemplate(tp, 0, 0); } catch (DocumentException de) { System.err.println(de.getMessage()); } document.close(); } /** * Creates a dataset, consisting of two series of monthly data. * * * * @return the dataset. */ public static XYDataset createDataset() { TimeSeries s1.add(new s1.add(new s1.add(new s1.add(new s1.add(new s1.add(new s1.add(new s1.add(new s1.add(new s1.add(new s1.add(new s1.add(new s1.add(new s1.add(new s1.add(new s1.add(new s1.add(new s1.add(new s1 = new TimeSeries("L&G European Index Trust", Month.class); Month(2, 2001), 181.8); Month(3, 2001), 167.3); Month(4, 2001), 153.8); Month(5, 2001), 167.6); Month(6, 2001), 158.8); Month(7, 2001), 148.3); Month(8, 2001), 153.9); Month(9, 2001), 142.7); Month(10, 2001), 123.2); Month(11, 2001), 131.8); Month(12, 2001), 139.6); Month(1, 2002), 142.9); Month(2, 2002), 138.7); Month(3, 2002), 137.3); Month(4, 2002), 143.9); Month(5, 2002), 139.8); Month(6, 2002), 137.0); Month(7, 2002), 132.8); TimeSeries s2.add(new s2.add(new s2.add(new s2.add(new s2.add(new s2.add(new s2.add(new s2.add(new s2.add(new s2.add(new s2.add(new s2.add(new s2.add(new s2.add(new s2.add(new s2.add(new s2.add(new s2.add(new s2 = new TimeSeries("L&G UK Index Trust", Month.class); Month(2, 2001), 129.6); Month(3, 2001), 123.2); Month(4, 2001), 117.2); Month(5, 2001), 124.1); Month(6, 2001), 122.6); Month(7, 2001), 119.2); Month(8, 2001), 116.5); Month(9, 2001), 112.7); Month(10, 2001), 101.5); Month(11, 2001), 106.1); Month(12, 2001), 110.3); Month(1, 2002), 111.7); Month(2, 2002), 111.0); Month(3, 2002), 109.6); Month(4, 2002), 113.2); Month(5, 2002), 111.6); Month(6, 2002), 108.8); Month(7, 2002), 101.6); TimeSeriesCollection dataset = new TimeSeriesCollection(); dataset.addSeries(s1); dataset.addSeries(s2); return dataset; } public static void main(String[] args) { try { 107 CHAPTER 16. EXPORTING CHARTS TO ACROBAT PDF 108 // create a chart... XYDataset dataset = createDataset(); JFreeChart chart = ChartFactory.createTimeSeriesChart( "Legal & General Unit Trust Prices", "Date", "Price Per Unit", dataset, true, true, false ); // some additional chart customisation here... XYPlot plot = chart.getXYPlot(); XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) plot.getRenderer(); renderer.setShapesVisible(true); DateAxis axis = (DateAxis) plot.getDomainAxis(); axis.setDateFormatOverride(new SimpleDateFormat("MMM-yyyy")); // write the chart to a PDF file... File fileName = new File(System.getProperty("user.home") + "/jfreechart1.pdf"); saveChartAsPDF(fileName, chart, 400, 300, new DefaultFontMapper()); } catch (IOException e) { System.out.println(e.getMessage()); } } } Before you compile and run the application, remember to change the file name used for the PDF file to something appropriate for your system! And include the jar files listed in section 16.5 on your classpath. 16.7 Viewing the PDF File After compiling and running the sample application, you can view the resulting PDF file using a PDF viewer like Acrobat Reader (or, in my case, Gnome PDF Viewer): Most PDF viewer applications provide zooming features that allow you to get a close up view of your charts. 16.8 Unicode Characters It is possible to use the full range of Unicode characters in JFreeChart and iText, as long as you are careful about which fonts you use. In this section, I present some modifications to the previous example to show how to do this. CHAPTER 16. EXPORTING CHARTS TO ACROBAT PDF 16.8.1 109 Background Internally, Java uses the Unicode character encoding to represent text strings. This encoding uses sixteen bits per character, which means there are potentially 65,536 different characters available (the Unicode standard defines something like 38,000 characters). You can use any of these characters in both JFreeChart and iText, subject to one proviso: the font you use to display the text must define the characters used or you will not be able to see them. Many fonts are not designed to display the entire Unicode character set. The following website contains useful information about fonts that do support Unicode (at least to some extent): http://www.slovo.info/unifonts.htm I have tried out the tahoma.ttf font with success. In fact, I will use this font in the example that follows. The Tahoma font doesn’t support every character defined in Unicode, so if you have specific requirements then you need to choose an appropriate font. At one point I had the Arial Unicode MS font (arialuni.ttf) installed on my system—this has support for the full Unicode character set, although this means that the font definition file is quite large (around 24 megabytes!) 16.8.2 Fonts, iText and Java iText has to handle fonts according to the PDF specification. This deals with document portability by allowing fonts to be (optionally) embedded in a PDF file. This requires access to the font definition file. Java, on the other hand, abstracts away some of the details of particular font formats with the use of the Font class. To support the Graphics2D implementation in iText, it is necessary to map Font objects from Java to BaseFont objects in iText. This is the role of the FontMapper interface. If you create a new DefaultFontMapper instance using the default constructor, it will already contain sensible mappings for the logical fonts defined by the Java specification. But if you want to use additional fonts—and you must if you want to use a wide range of Unicode characters—then you need to add extra mappings to the DefaultFontMapper object. 16.8.3 Mapping Additional Fonts I’ve decided to use the Tahoma font to display a chart title that incorporates some Unicode characters. The font definition file (tahoma.ttf) is located, on my system, in the directory: /opt/sun-jdk-1.4.2.08/jre/lib/fonts Here’s the code used to create the FontMapper for use by iText—I’ve based this on an example written by Paulo Soares: DefaultFontMapper mapper = new DefaultFontMapper(); mapper.insertDirectory("/opt/sun-jdk-1.4.2.08/jre/lib/fonts"); DefaultFontMapper.BaseFontParameters pp = mapper.getBaseFontParameters("Tahoma"); if (pp!=null) { pp.encoding = BaseFont.IDENTITY_H; } Now I can modify the code that creates the chart, in order to add a custom title to the chart (I’ve changed the data and chart type also): // create a chart... TimeSeries series = new TimeSeries("Random Data"); Day current = new Day(1, 1, 2000); double value = 100.0; for (int i = 0; i < 1000; i++) { try { value = value + Math.random() - 0.5; CHAPTER 16. EXPORTING CHARTS TO ACROBAT PDF 110 series.add(current, new Double(value)); current = (Day) current.next(); } catch (SeriesException e) { System.err.println("Error adding to series"); } } XYDataset data = new TimeSeriesCollection(series); JFreeChart chart = ChartFactory.createTimeSeriesChart( "Test", "Date", "Value", data, true, false, false ); // Unicode test... String text = "\u278A\u20A0\u20A1\u20A2\u20A3\u20A4\u20A5\u20A6\u20A7\u20A8\u20A9"; //String text = "hi"; Font font = new Font("Tahoma", Font.PLAIN, 12); TextTitle subtitle = new TextTitle(text, font); chart.addSubtitle(subtitle); Notice that the subtitle (a random collection of currency symbols) is defined using escape sequences to specify each Unicode character. This avoids any problems with encoding conversions when I save the Java source file. The output from the modified sample program is shown in figure 16.2. The example has been embedded in this document in PDF format, so it is a good example of the type of output you can expect by following the instructions in this document. Test 102.5 100.0 Value 97.5 95.0 92.5 90.0 87.5 85.0 Jan-2000 Jul-2000 Jan-2001 Jul-2001 Jan-2002 Date Random Data Figure 16.2: A Unicode subtitle Jul-2002 Chapter 17 Exporting Charts to SVG Format 17.1 Introduction In this section, I present an example that shows how to export charts to SVG format, using JFreeChart and Batik (an open source library for working with SVG). 17.2 Background 17.2.1 What is SVG? Scalable Vector Graphics (SVG) is a standard language for describing two-dimensional graphics in XML format. It is a Recommendation of the World Wide Web Consortium (W3C). 17.2.2 Batik Batik is an open source toolkit, written in Java, that allows you to generate SVG content. Batik is available from: http://xml.apache.org/batik At the time of writing, the latest stable version of Batik is 1.6. 17.3 A Sample Application 17.3.1 JFreeChart and Batik JFreeChart and Batik can work together relatively easily because: • JFreeChart draws all chart output using Java’s Graphics2D abstraction; and • Batik provides a concrete implementation of Graphics2D that generates SVG output (SVGGraphics2D). In this section, a simple example is presented to get you started using JFreeChart and Batik. The example is based on the technique described here: http://xml.apache.org/batik/svggen.html 111 CHAPTER 17. EXPORTING CHARTS TO SVG FORMAT 17.3.2 112 Getting Started First, you should download Batik and install it according to the instructions provided on the Batik web page. To compile and run the sample program presented in the next section, you need to ensure that the following jar files are on your classpath: File: Description: jcommon-1.0.12.jar jfreechart-1.0.9.jar batik-awt-util.jar batik-dom.jar batik-svggen.jar batik-util.jar Common classes from JFree. The JFreeChart class library. Batik runtime files. Batik runtime files. Batik runtime files. Batik runtime files. 17.3.3 The Application Create a project in your favourite Java development environment, add the libraries listed in the previous section, and type in the following program (or easier, grab a copy of the source from the JFreeChart demo collection): /* -----------------* SVGExportDemo.java * -----------------* (C) Copyright 2002-2005, by Object Refinery Limited. * */ package demo.svg; import import import import import import java.awt.geom.Rectangle2D; java.io.File; java.io.FileOutputStream; java.io.IOException; java.io.OutputStreamWriter; java.io.Writer; import import import import import import import org.apache.batik.dom.GenericDOMImplementation; org.apache.batik.svggen.SVGGraphics2D; org.jfree.chart.ChartFactory; org.jfree.chart.JFreeChart; org.jfree.data.general.DefaultPieDataset; org.w3c.dom.DOMImplementation; org.w3c.dom.Document; /** * A demonstration showing the export of a chart to SVG format. */ public class SVGExportDemo { /** * Starting point for the demo. * * @param args ignored. */ public static void main(String[] args) throws IOException { // create a dataset... DefaultPieDataset data = new DefaultPieDataset(); data.setValue("Category 1", new Double(43.2)); data.setValue("Category 2", new Double(27.9)); data.setValue("Category 3", new Double(79.5)); // create a chart JFreeChart chart = ChartFactory.createPieChart( "Sample Pie Chart", data, true, false, false ); // THE FOLLOWING CODE BASED ON THE EXAMPLE IN THE BATIK DOCUMENTATION... // Get a DOMImplementation CHAPTER 17. EXPORTING CHARTS TO SVG FORMAT 113 DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation(); // Create an instance of org.w3c.dom.Document Document document = domImpl.createDocument(null, "svg", null); // Create an instance of the SVG Generator SVGGraphics2D svgGenerator = new SVGGraphics2D(document); // set the precision to avoid a null pointer exception in Batik 1.5 svgGenerator.getGeneratorContext().setPrecision(6); // Ask the chart to render into the SVG Graphics2D implementation chart.draw(svgGenerator, new Rectangle2D.Double(0, 0, 400, 300), null); // Finally, stream out SVG to a file using UTF-8 character to // byte encoding boolean useCSS = true; Writer out = new OutputStreamWriter( new FileOutputStream(new File("test.svg")), "UTF-8"); svgGenerator.stream(out, useCSS); } } Running this program creates a file test.svg in SVG format. 17.3.4 Viewing the SVG Batik includes a viewer application (“Squiggle”) which you can use to open and view the SVG file. The Batik download includes instructions for running the viewer, effectively all you require is: java -jar batik-squiggle.jar The following screen shot shows the pie chart that we created earlier, displayed using the browser application. A transformation (rotation) has been applied to the chart from within the browser: If you play about with the viewer, zooming in and out and applying various transformations to the chart, you will begin to appreciate the power of the SVG format. Chapter 18 Applets 18.1 Introduction Subject to a couple of provisos, using JFreeChart in an applet is relatively straightforward. This section provides a brief overview of the important issues and describes a working example that should be sufficient to get you started. Figure 18.1: An applet using JFreeChart Figure 18.1 shows a sample applet that uses JFreeChart. This applet is available online at: http://www.object-refinery.com/jfreechart/applet.html The source code for this applet appears later in this section. 18.2 Issues The main issues to consider when developing applets (whether with or without JFreeChart) are: • browser support; • security restrictions; • code size. Be sure that you understand these issues before you commit significant resources to writing applets. 114 CHAPTER 18. APPLETS 18.2.1 115 Browser Support The vast majority of web browsers provide support for the latest version of Java (JDK 1.5.0) and will therefore have no problems running applets that use JFreeChart (recall that JFreeChart will run on any version of the JDK from 1.3.1 onwards). However, the vast majority of users on the web use (by default in most cases) the one web browser— Microsoft Internet Explorer (MSIE)—that only supports a version of Java (JDK 1.1) that is now hopelessly out-of-date. This is a problem, because applets that use JFreeChart will not work on a default installation of MSIE. There is a workaround—users can download and install Sun’s Java plugin—but, like many workarounds, it is too much effort and inconvenience for many people. The end result is a deployment problem for developers who choose to write applets. This single issue has caused many developers to abandon their plans to develop applets1 and instead choose an easier-to-deploy technology such as Java Servlets (see the next chapter). 18.2.2 Security Applets (and Java more generally) have been designed with security in mind. When an applet runs in your web browser, it is restricted in the operations that it is permitted to perform. For example, an applet typically will not be allowed to read or write to the local filesystem. Describing the details of Java’s security mechanism is beyond the scope of this text, but you should be aware that some functions provided by JFreeChart (for example, the option to save charts to PNG format via the pop-up menu) will not work in applets that are subject to the default security policy. If you need these functions to work, then you will need to study Java’s security mechanism in more detail. 18.2.3 Code Size A final issue to consider is the size of the “runtime” code required for your applet. Before an applet can run, the code (typically packed into jar files) has to be downloaded to the end user’s computer. Clearly, for users with limited bandwidth connections, the size of the code can be an issue. The JFreeChart code is distributed in a jar file that is around 1,000KB in size. That isn’t large— especially when you consider the number and variety of charts that JFreeChart supports—but, at the same time, it isn’t exactly optimal for a user on a dial-up modem connection. And you need to add to that the JCommon jar file (around 290KB) plus whatever code you have for your applet. As always with JFreeChart, you have the source code so you could improve this by repackaging the JFreeChart jar file to include only those classes that are used by your applet (directly or indirectly). 18.3 A Sample Applet As mentioned in the introduction, a sample applet that uses JFreeChart can be seen at the following URL:2 http://www.object-refinery.com/jfreechart/applet.html Two aspects of the sample applet are interesting, the source code that is used to create the applet and the HTML file that is used to invoke the applet. 1 For some people this issue won’t be a concern. For example, you may be developing applets for internal corporate use, and your standard desktop configuration includes a browser that supports JDK 1.5.0. Alternatively, you may be providing an applet for public use via the World Wide Web, but it is not critical that every user be able to run the applet. 2 If the applet does not work for you, please check that your web browser is configured correctly and supports JDK 1.3.1 or later. CHAPTER 18. APPLETS 18.3.1 116 The HTML The HTML used to invoke the applet is important, since it needs to reference the necessary jar files. The HTML applet tag used is: Notice that three jar files are referenced. The first contains the applet class (source code in the next section) only, while the remaining two jar files are the standard JFreeChart and JCommon class libraries (the version numbers reflect the age of the demo rather than the current releases). You can place the applet tag anywhere in your HTML file that you might place some other element (such as an image). 18.3.2 The Source Code The sample applet is created using the following source code (which is included in the “support demos” package). There is very little applet-specific code here—we just extend JApplet: /* -----------* Applet1.java * -----------* (C) Copyright 2002-2005, by Object Refinery Limited. */ package demo.applet; import import import import java.awt.BasicStroke; java.awt.Color; java.awt.event.ActionEvent; java.awt.event.ActionListener; import javax.swing.JApplet; import javax.swing.Timer; import import import import import import import import import import org.jfree.chart.ChartPanel; org.jfree.chart.JFreeChart; org.jfree.chart.axis.DateAxis; org.jfree.chart.axis.NumberAxis; org.jfree.chart.plot.XYPlot; org.jfree.chart.renderer.xy.XYItemRenderer; org.jfree.chart.renderer.xy.XYLineAndShapeRenderer; org.jfree.data.time.Millisecond; org.jfree.data.time.TimeSeries; org.jfree.data.time.TimeSeriesCollection; /** * A simple applet demo. */ public class Applet1 extends JApplet { /** Time series for total memory used. */ private TimeSeries total; /** Time series for free memory. */ private TimeSeries free; /** * Creates a new instance. */ public Applet1() { // create two series that automatically discard data more than // 30 seconds old... this.total = new TimeSeries("Total", Millisecond.class); this.total.setMaximumItemAge(30000); this.free = new TimeSeries("Free", Millisecond.class); this.free.setMaximumItemAge(30000); TimeSeriesCollection dataset = new TimeSeriesCollection(); dataset.addSeries(total); dataset.addSeries(free); CHAPTER 18. APPLETS DateAxis domain = new DateAxis("Time"); NumberAxis range = new NumberAxis("Memory"); XYItemRenderer renderer = new XYLineAndShapeRenderer(true, false); XYPlot plot = new XYPlot(dataset, domain, range, renderer); plot.setBackgroundPaint(Color.lightGray); plot.setDomainGridlinePaint(Color.white); plot.setRangeGridlinePaint(Color.white); renderer.setSeriesPaint(0, Color.red); renderer.setSeriesPaint(1, Color.green); renderer.setSeriesStroke(0, new BasicStroke(1.5f)); renderer.setSeriesStroke(1, new BasicStroke(1.5f)); domain.setAutoRange(true); domain.setLowerMargin(0.0); domain.setUpperMargin(0.0); domain.setTickLabelsVisible(true); range.setStandardTickUnits(NumberAxis.createIntegerTickUnits()); JFreeChart chart = new JFreeChart( "Memory Usage", JFreeChart.DEFAULT_TITLE_FONT, plot, true ); chart.setBackgroundPaint(Color.white); ChartPanel chartPanel = new ChartPanel(chart); chartPanel.setPopupMenu(null); getContentPane().add(chartPanel); new Applet1.DataGenerator().start(); } /** * Adds an observation to the ’total memory’ time series. * * @param y the total memory used. */ private void addTotalObservation(double y) { total.add(new Millisecond(), y); } /** * Adds an observation to the ’free memory’ time series. * * @param y the free memory. */ private void addFreeObservation(double y) { free.add(new Millisecond(), y); } /** * The data generator. */ class DataGenerator extends Timer implements ActionListener { /** * Constructor. */ DataGenerator() { super(100, null); addActionListener(this); } /** * Adds a new free/total memory reading to the dataset. * * @param event the action event. */ public void actionPerformed(ActionEvent event) { long f = Runtime.getRuntime().freeMemory(); long t = Runtime.getRuntime().totalMemory(); addTotalObservation(t); addFreeObservation(f); } } } 117 Chapter 19 Servlets 19.1 Introduction The Java Servlets API is a popular technology for creating web applications. JFreeChart is well suited for use in a servlet environment and, in this section, some examples are presented to help those developers that are interested in using JFreeChart for web applications. All the sample code in this section is available for download from: http://www.object-refinery.com/jfreechart/premium/index.html The file to download is jfreechart-1.0.9-demo.zip.1 19.2 A Simple Servlet The ServletDemo1 class implements a very simple servlet that returns a PNG image of a bar chart generated using JFreeChart. When it is run, the servlet will return a raw image to the client (web browser) which will display the image without any surrounding HTML—see figure 19.1. Typically, Figure 19.1: ServletDemo1 in a browser you will not present raw output in this way, so this servlet is not especially useful on its own, but the example is: 1 To access this page you need to enter the username and password provided to you in the confirmation e-mail you received when you purchased the JFreeChart Developer Guide. 118 CHAPTER 19. SERVLETS 119 • a good illustration of the request-response nature of servlets; • useful as a test case if you are configuring a server environment and want to check that everything is working. We will move on to a more complex example later, showing how to request different charts using HTML forms, and embedding the generated charts within HTML output. Here is the code for the basic servlet: /* ----------------* ServletDemo1.java * ----------------* (C) Copyright 2002-2004, by Object Refinery Limited. * */ package demo; import java.io.IOException; import java.io.OutputStream; import import import import javax.servlet.ServletException; javax.servlet.http.HttpServlet; javax.servlet.http.HttpServletRequest; javax.servlet.http.HttpServletResponse; import import import import import org.jfree.chart.ChartFactory; org.jfree.chart.ChartUtilities; org.jfree.chart.JFreeChart; org.jfree.chart.plot.PlotOrientation; org.jfree.data.category.DefaultCategoryDataset; /** * A basic servlet that returns a PNG image file generated by JFreeChart. * This class is described in the JFreeChart Developer Guide in the * "Servlets" chapter. */ public class ServletDemo1 extends HttpServlet { /** * Creates a new demo. */ public ServletDemo1() { // nothing required } /** * Processes a GET request. * * @param request the request. * @param response the response. * * @throws ServletException if there is a servlet related problem. * @throws IOException if there is an I/O problem. */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { OutputStream out = response.getOutputStream(); try { DefaultCategoryDataset dataset = new DefaultCategoryDataset(); dataset.addValue(10.0, "S1", "C1"); dataset.addValue(4.0, "S1", "C2"); dataset.addValue(15.0, "S1", "C3"); dataset.addValue(14.0, "S1", "C4"); dataset.addValue(-5.0, "S2", "C1"); dataset.addValue(-7.0, "S2", "C2"); dataset.addValue(14.0, "S2", "C3"); dataset.addValue(-3.0, "S2", "C4"); dataset.addValue(6.0, "S3", "C1"); dataset.addValue(17.0, "S3", "C2"); dataset.addValue(-12.0, "S3", "C3"); dataset.addValue( 7.0, "S3", "C4"); dataset.addValue(7.0, "S4", "C1"); dataset.addValue(15.0, "S4", "C2"); dataset.addValue(11.0, "S4", "C3"); dataset.addValue(0.0, "S4", "C4"); dataset.addValue(-8.0, "S5", "C1"); CHAPTER 19. SERVLETS 120 dataset.addValue(-6.0, "S5", "C2"); dataset.addValue(10.0, "S5", "C3"); dataset.addValue(-9.0, "S5", "C4"); dataset.addValue(9.0, "S6", "C1"); dataset.addValue(8.0, "S6", "C2"); dataset.addValue(null, "S6", "C3"); dataset.addValue(6.0, "S6", "C4"); dataset.addValue(-10.0, "S7", "C1"); dataset.addValue(9.0, "S7", "C2"); dataset.addValue(7.0, "S7", "C3"); dataset.addValue(7.0, "S7", "C4"); dataset.addValue(11.0, "S8", "C1"); dataset.addValue(13.0, "S8", "C2"); dataset.addValue(9.0, "S8", "C3"); dataset.addValue(9.0, "S8", "C4"); dataset.addValue(-3.0, "S9", "C1"); dataset.addValue(7.0, "S9", "C2"); dataset.addValue(11.0, "S9", "C3"); dataset.addValue(-10.0, "S9", "C4"); JFreeChart chart = ChartFactory.createBarChart( "Bar Chart", "Category", "Value", dataset, PlotOrientation.VERTICAL, true, true, false ); response.setContentType("image/png"); ChartUtilities.writeChartAsPNG(out, chart, 400, 300); } catch (Exception e) { System.err.println(e.toString()); } finally { out.close(); } } } The doGet() method is called by the servlet engine when a request is made by a client (usually a web browser). In response to the request, the servlet performs several steps: • an OutputStream reference is obtained for returning output to the client; • a chart is created; • the content type for the response is set to image/png. This tells the client what type of data it is receiving; • a PNG image of the chart is written to the output stream; • the output stream is closed. 19.3 Compiling the Servlet Note that the classes in the javax.servlet.* package (and sub-packages), used by the demo servlet, are not part of the Java 2 Standard Edition (J2SE). In order to compile the above code using J2SE, you will need to obtain a servlet.jar file. I’ve used the one that is redistributed with Tomcat (an open source servlet engine written using Java). You can find out more about Tomcat at: http://tomcat.apache.org/ You will also require the JFreeChart and JCommon jar files to compile the above servlet. Change your working directory to jfreechart-1.0.9-demo, then enter the following command (on Windows, you need to change the colons to semi-colons, and the forward slashes to backward slashes): javac -classpath jfreechart-1.0.9.jar:lib/jcommon-1.0.12.jar:lib/servlet.jar source/demo/ServletDemo1.java CHAPTER 19. SERVLETS 121 This should create a ServletDemo1.class file. The next section describes how to deploy this servlet using Tomcat. 19.4 Deploying the Servlet Servlets are deployed in the webapps directory provided by your servlet engine. In my case, I am using Tomcat 5.5.15 on Ubuntu Linux 5.10, and the directory is:2 /home/dgilbert/apache-tomcat-5.5.15/webapps Within the webapps directory, create a jfreechart1 directory to hold the first servlet demo, then create the following structure within the directory: .../jfreechart1/WEB-INF/web.xml .../jfreechart1/WEB-INF/lib/jfreechart-1.0.9.jar .../jfreechart1/WEB-INF/lib/jcommon-1.0.12.jar .../jfreechart1/WEB-INF/classes/demo/ServletDemo1.class You need to create the web.xml file—it provides information about the servlet: ServletDemo1 demo.ServletDemo1 ServletDemo1 /servlet/ServletDemo1 Once you have all these files in place, restart your servlet engine and type in the following URL using your favourite web browser: http://localhost:8080/jfreechart1/servlet/ServletDemo1 If all is well, you will see the chart image displayed in your browser, as shown in figure 19.1. 19.5 Embedding Charts in HTML Pages It is possible to embed a chart image generated by a servlet inside an HTML page (that is generated by another servlet). This is demonstrated by ServletDemo2, which is also available in the jfreechart-1.0.9-demo.zip file. ServletDemo2 processes a request by returning a page of HTML that, in turn, references another servlet (ServletDemo2ChartGenerator) that returns a PNG image of a chart. The end result is a chart embedded in an HTML page, as shown in figure 19.2. Here is the code for ServletDemo2: 2 Servlets are portable between different servlet engines, so if you are using a different servlet engine, consult the documentation to find the location of the webapps folder. CHAPTER 19. SERVLETS 122 Figure 19.2: ServletDemo2 in a browser /* ----------------* ServletDemo2.java * ----------------* (C) Copyright 2002-2004, by Object Refinery Limited. * */ package demo; import java.io.IOException; import java.io.PrintWriter; import import import import javax.servlet.ServletException; javax.servlet.http.HttpServlet; javax.servlet.http.HttpServletRequest; javax.servlet.http.HttpServletResponse; /** * A basic servlet that generates an HTML page that displays a chart generated by * JFreeChart. *

* This servlet uses another servlet (ServletDemo2ChartGenerator) to create a PNG image * for the embedded chart. *

* This class is described in the JFreeChart Developer Guide. */ public class ServletDemo2 extends HttpServlet { /** * Creates a new servlet demo. */ public ServletDemo2() { // nothing required } /** * Processes a POST request. *

* The chart.html page contains a form for generating the first request, after that * the HTML returned by this servlet contains the same form for generating subsequent * requests. * * @param request the request. * @param response the response. * * @throws ServletException if there is a servlet related problem. * @throws IOException if there is an I/O problem. */ public void doPost(HttpServletRequest request, HttpServletResponse response) CHAPTER 19. SERVLETS 123 throws ServletException, IOException { PrintWriter out = new PrintWriter(response.getWriter()); try { String param = request.getParameter("chart"); response.setContentType("text/html"); out.println(""); out.println(""); out.println("JFreeChart Servlet Demo 2"); out.println(""); out.println(""); out.println("

JFreeChart Servlet Demo

"); out.println("

"); out.println("Please choose a chart type:"); out.println("

"); String pieChecked = (param.equals("pie") ? " CHECKED" : ""); String barChecked = (param.equals("bar") ? " CHECKED" : ""); String timeChecked = (param.equals("time") ? " CHECKED" : ""); out.println(" Pie Chart"); out.println(" Bar Chart"); out.println(" Time Series Chart"); out.println("

"); out.println(""); out.println("

"); out.println("

"); out.println(""); out.println(""); out.println(""); out.flush(); out.close(); } catch (Exception e) { System.err.println(e.toString()); } finally { out.close(); } } } Notice how this code gets a reference to a Writer from the response parameter, rather than an OutputStream as in the previous example. The reason for this is because this servlet will be returning text (HTML), compared to the previous servlet which returned binary data (a PNG image).3 The response type is set to text/html since this servlet returns HTML text. An important point to note is that the tag in the HTML references another servlet (ServletDemo2ChartGenerator), and this other servlet creates the required chart image. The actual chart returned is controlled by the chart parameter, which is set up in the HTML using a

element. Here is the source code for ServletDemo2ChartGenerator: /* ------------------------------* ServletDemo2ChartGenerator.java * ------------------------------* (C) Copyright 2002-2004, by Object Refinery Limited. * */ package demo; import java.io.IOException; import java.io.OutputStream; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; 3 The Writer is wrapped in a PrintWriter in order to use the more convenient methods available in the latter class. CHAPTER 19. SERVLETS import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import import import import import import import import import import import org.jfree.chart.ChartFactory; org.jfree.chart.ChartUtilities; org.jfree.chart.JFreeChart; org.jfree.chart.plot.PlotOrientation; org.jfree.data.category.DefaultCategoryDataset; org.jfree.data.general.DefaultPieDataset; org.jfree.data.time.Day; org.jfree.data.time.TimeSeries; org.jfree.data.time.TimeSeriesCollection; org.jfree.data.xy.XYDataset; org.jfree.date.SerialDate; /** * A servlet that returns one of three charts as a PNG image file. This servlet is * referenced in the HTML generated by ServletDemo2. *

* Three different charts can be generated, controlled by the ’type’ parameter. The possible * values are ’pie’, ’bar’ and ’time’ (for time series). *

* This class is described in the JFreeChart Developer Guide. */ public class ServletDemo2ChartGenerator extends HttpServlet { /** * Default constructor. */ public ServletDemo2ChartGenerator() { // nothing required } /** * Process a GET request. * * @param request the request. * @param response the response. * * @throws ServletException if there is a servlet related problem. * @throws IOException if there is an I/O problem. */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { OutputStream out = response.getOutputStream(); try { String type = request.getParameter("type"); JFreeChart chart = null; if (type.equals("pie")) { chart = createPieChart(); } else if (type.equals("bar")) { chart = createBarChart(); } else if (type.equals("time")) { chart = createTimeSeriesChart(); } if (chart != null) { response.setContentType("image/png"); ChartUtilities.writeChartAsPNG(out, chart, 400, 300); } } catch (Exception e) { System.err.println(e.toString()); } finally { out.close(); } } /** * Creates a sample pie chart. * * @return a pie chart. */ private JFreeChart createPieChart() { // create a dataset... DefaultPieDataset data = new DefaultPieDataset(); 124 CHAPTER 19. SERVLETS data.setValue("One", new Double(43.2)); data.setValue("Two", new Double(10.0)); data.setValue("Three", new Double(27.5)); data.setValue("Four", new Double(17.5)); data.setValue("Five", new Double(11.0)); data.setValue("Six", new Double(19.4)); JFreeChart chart = ChartFactory.createPieChart( "Pie Chart", data, true, true, false ); return chart; } /** * Creates a sample bar chart. * * @return a bar chart. */ private JFreeChart createBarChart() { DefaultCategoryDataset dataset = new DefaultCategoryDataset(); dataset.addValue(10.0, "S1", "C1"); dataset.addValue(4.0, "S1", "C2"); dataset.addValue(15.0, "S1", "C3"); dataset.addValue(14.0, "S1", "C4"); dataset.addValue(-5.0, "S2", "C1"); dataset.addValue(-7.0, "S2", "C2"); dataset.addValue(14.0, "S2", "C3"); dataset.addValue(-3.0, "S2", "C4"); dataset.addValue(6.0, "S3", "C1"); dataset.addValue(17.0, "S3", "C2"); dataset.addValue(-12.0, "S3", "C3"); dataset.addValue( 7.0, "S3", "C4"); dataset.addValue(7.0, "S4", "C1"); dataset.addValue(15.0, "S4", "C2"); dataset.addValue(11.0, "S4", "C3"); dataset.addValue(0.0, "S4", "C4"); dataset.addValue(-8.0, "S5", "C1"); dataset.addValue(-6.0, "S5", "C2"); dataset.addValue(10.0, "S5", "C3"); dataset.addValue(-9.0, "S5", "C4"); dataset.addValue(9.0, "S6", "C1"); dataset.addValue(8.0, "S6", "C2"); dataset.addValue(null, "S6", "C3"); dataset.addValue(6.0, "S6", "C4"); dataset.addValue(-10.0, "S7", "C1"); dataset.addValue(9.0, "S7", "C2"); dataset.addValue(7.0, "S7", "C3"); dataset.addValue(7.0, "S7", "C4"); dataset.addValue(11.0, "S8", "C1"); dataset.addValue(13.0, "S8", "C2"); dataset.addValue(9.0, "S8", "C3"); dataset.addValue(9.0, "S8", "C4"); dataset.addValue(-3.0, "S9", "C1"); dataset.addValue(7.0, "S9", "C2"); dataset.addValue(11.0, "S9", "C3"); dataset.addValue(-10.0, "S9", "C4"); JFreeChart chart = ChartFactory.createBarChart3D( "Bar Chart", "Category", "Value", dataset, PlotOrientation.VERTICAL, true, true, false ); return chart; } /** * Creates a sample time series chart. * * @return a time series chart. */ private JFreeChart createTimeSeriesChart() { // here we just populate a series with random data... 125 CHAPTER 19. SERVLETS 126 TimeSeries series = new TimeSeries("Random Data"); Day current = new Day(1, SerialDate.JANUARY, 2001); for (int i = 0; i < 100; i++) { series.add(current, Math.random() * 100); current = (Day) current.next(); } XYDataset data = new TimeSeriesCollection(series); JFreeChart chart = ChartFactory.createTimeSeriesChart( "Time Series Chart", "Date", "Rate", data, true, true, false ); return chart; } } To compile these two servlets, you can enter the following command at the command line: javac -classpath jfreechart-1.0.9.jar:lib/jcommon-1.0.12.jar:lib/servlet.jar source/demo/ServletDemo2.java source/demo/ServletDemo2ChartGenerator.java The following sections describe the supporting files required for the servlet, and how to deploy them. 19.6 Supporting Files Servlets typically generate output for clients that access the web application via a web browser. Most web applications will include at least one HTML page that is used as the starting point for the application. For the demo servlets above, the following index.html page4 is used:

JFreeChart : Basic Servlet Demo

JFreeChart: Basic Servlet Demo

There are two sample servlets available:

  • a very basic servlet to generate a bar chart;
  • another servlet that allow you to select one of three sample charts. The selected chart is displayed in an HTML page.
There are two hyperlinks in this page, the first references the first demo servlet (ServletDemo1) and the second references another HTML page, chart.html:
JFreeChart Servlet Demo 2

JFreeChart Servlet Demo

Please choose a chart type: Pie Chart Bar Chart 4 You’ll find this file in the servlets directory of the demo distribution, along with the other servlet support files. CHAPTER 19. SERVLETS 127 Time Series Chart

This second HTML page contains a
element used to specify a parameter for the second servlet (ServletDemo2). When this servlet runs, it returns its own HTML that is almost identical to the above but also includes an element with a reference to the ServletDemo2ChartGenerator servlet. 19.7 Deploying Servlets After compiling the demo servlets, they need to be deployed to a servlet engine, along with the supporting files, so that they can be accessed by clients. Fortunately, this is relatively straightforward. The first requirement is a web.xml file to describe the web application being deployed: ServletDemo1 demo.ServletDemo1 ServletDemo2 demo.ServletDemo2 ServletDemo2ChartGenerator demo.ServletDemo2ChartGenerator ServletDemo1 /servlet/ServletDemo1 ServletDemo2 /servlet/ServletDemo2 ServletDemo2ChartGenerator /servlet/ServletDemo2ChartGenerator This file lists the servlets by name, and specifies the class file that implements the servlet. The actual class files will be placed in a directory where the servlet engine will know to find them (the classes sub-directory within a directory specific to the application). The final step is copying all the files to the appropriate directory for the servlet engine. In testing with Tomcat, I created a jfreechart2 directory within Tomcat’s webapps directory. The index.html and chart.html files are copied to this directory. CHAPTER 19. SERVLETS 128 webapps/jfreechart2/index.html webapps/jfreechart2/chart.html Next, a subdirectory WEB-INF is created within the jfreechart2 directory, and the web.xml file is copied to here. webapps/jfreechart2/WEB-INF/web.xml A classes subdirectory is created within WEB-INF to hold the .class files for the three demo servlets. These need to be saved in a directory hierarchy matching the package hierarchy: webapps/jfreechart2/WEB-INF/classes/demo/ServletDemo1.class webapps/jfreechart2/WEB-INF/classes/demo/ServletDemo2.class webapps/jfreechart2/WEB-INF/classes/demo/ServletDemo2ChartGenerator.class Finally, the servlets make use of classes in the JFreeChart and JCommon class libraries. The jar files for these libraries need to be added to a lib directory within WEB-INF. You will need: webapps/jfreechart2/WEB-INF/lib/jcommon-1.0.12.jar webapps/jfreechart2/WEB-INF/lib/jfreechart-1.0.9.jar Now restart your servlet engine, and point your browser to: http://localhost:8080/jfreechart2/index.html If all the files have been put in the correct places, you should see the running servlet demonstration (this has been tested using Tomcat 5.5.15 running on Ubuntu Linux 5.10 for AMD64). Chapter 20 Miscellaneous 20.1 Introduction This section contains miscellaneous information about JFreeChart. 20.2 X11 / Headless Java If you are using JFreeChart in a server environment running Unix / Linux, you may encounter the problem that JFreeChart won’t run without X11. This is a common problem for Java code that relies on AWT, see the following web page for further information: http://java.sun.com/products/java-media/2D/forDevelopers/java2dfaq.html#xvfb There is also a thread in the JFreeChart forum with lots of info: http://www.jfree.org/phpBB2/viewtopic.php?t=1012 20.3 Java Server Pages Developers that are interested in using JFreeChart with JSP will want to check out the Cewolf project: http://cewolf.sourceforge.net/ Thanks to Guido Laures for leading this effort. 20.4 Loading Images Images in Java are represented by the Image class. You can load an image using the createImage() method in the Toolkit class, but you need to be aware that this method loads the image asynchronously— in other words, the method returns immediately (before the image is loaded) and the image loading continues in a separate thread. This can cause problems if you use the image without first waiting for it to complete loading. You can use the MediaTracker class to check the progress of an image as it loads. But in the case where you just want to ensure that you have a fully loaded image, a useful technique is to use Swing’s ImageIcon class to do the image loading for you: ImageIcon icon = new ImageIcon("/home/dgilbert/temp/daylight.png"); Image image = icon.getImage(); In this case, the constructor doesn’t return until the image is fully loaded, so by the time you call the getImage() method, you know that the image loading is complete. 129 Chapter 21 Packages 21.1 Overview The following sections contain reference information for the classes, arranged by package, that make up the JFreeChart class library. Package: Description: org.jfree.chart org.jfree.chart.annotations org.jfree.chart.axis org.jfree.chart.editor The main chart classes. A simple framework for annotating charts. Axis classes and related interfaces. A framework (incomplete) for providing property editors for charts. Classes for writing image files. Classes representing chart entities. The event classes. HTML image map utility classes. The item label and tooltip classes. Needle classes for the compass plot. Plot classes and interfaces. Dial plot classes and interfaces. The base package for renderers. Plug-in renderers for use with the CategoryPlot class. Plug-in renderers for use with the XYPlot class. Servlet utility classes. Chart title classes. Interfaces and classes for generating URLs in image maps. Utility classes. Dataset interfaces and classes. The CategoryDataset interface and related classes. The ContourDataset interface and related classes. The Function2D interface and related classes. Dataset interfaces and classes for Gantt charts. General dataset classes. General I/O classes for datasets. Some JDBC dataset classes. Classes that are used for generating statistics. Time-based dataset interfaces and classes. Classes to represent an open-high-low-close dataset. Classes for reading datasets from XML. The XYDataset interface and related classes. org.jfree.chart.encoders org.jfree.chart.entity org.jfree.chart.event org.jfree.chart.imagemap org.jfree.chart.labels org.jfree.chart.needle org.jfree.chart.plot org.jfree.chart.plot.dial org.jfree.chart.renderer org.jfree.chart.renderer.category org.jfree.chart.renderer.xy org.jfree.chart.servlet org.jfree.chart.title org.jfree.chart.urls org.jfree.chart.util org.jfree.data org.jfree.data.category org.jfree.data.contour org.jfree.data.function org.jfree.data.gantt org.jfree.data.general org.jfree.data.io org.jfree.data.jdbc org.jfree.data.statistics org.jfree.data.time org.jfree.data.time.ohlc org.jfree.data.xml org.jfree.data.xy Additional information can be found in the HTML format API documentation that is generated from the JFreeChart source files. 130 Chapter 22 Package: org.jfree.chart 22.1 Overview This package contains the major classes and interfaces in the JFreeChart Class Library, including the all important JFreeChart class. 22.2 ChartColor 22.2.1 Overview This class defines some standard colors. 22.2.2 Methods This class defines the following methods: å public static Paint[] createDefaultPaintArray(); Returns an array of Paint instances. This array is used by the DefaultDrawingSupplier class as the default series colors for most plots. 22.3 ChartFactory 22.3.1 Overview This class contains a range of convenient methods for creating standard types of charts. HINT: The use of these methods is optional. Take a look at the source code for the method you are using to see if it might be a better option to cut-and-paste the code into your application, and then customise it to meet your requirements. 22.3.2 Pie Charts To create a regular pie chart, you can use either of the following methods: å public static JFreeChart createPieChart(String title, PieDataset dataset, boolean legend, boolean tooltips, Locale locale); [1.0.7] Creates a pie chart based on the specified dataset (null permitted), with tooltips formatted according to the specified locale. The resulting chart is constructed using a PiePlot. å public static JFreeChart createPieChart(String title, PieDataset dataset, boolean legend, boolean tooltips, boolean urls); Creates a pie chart based on the specified dataset (null permitted). The chart is constructed 131 CHAPTER 22. PACKAGE: ORG.JFREE.CHART 132 using a PiePlot. Note that URL support is only applicable to the creation of HTML image maps. To create a pie chart with a “3D effect”: å public static JFreeChart createPieChart3D(String title, PieDataset dataset, boolean legend, boolean tooltips, Locale locale); [1.0.7] Creates a pie chart with a 3D perspective, using the specified dataset (which may be null). The chart is constructed using a PiePlot3D. The locale is used to create default formatters for the tool tip generator. å public static JFreeChart createPieChart3D(String title, PieDataset dataset, boolean legend, boolean tooltips, boolean urls) Creates a 3D pie chart for the specified PieDataset (null permitted). The chart is constructed using a PiePlot3D. To create a single chart containing multiple pie charts: å public static JFreeChart createMultiplePieChart(String title, CategoryDataset dataset, TableOrder order, boolean legend, boolean tooltips, boolean urls); Creates a multiple pie chart for the specified CategoryDataset. This chart is constructed using a MultiplePiePlot. The order argument can be either TableOrder.BY ROW or TableOrder.BY COLUMN. To create a single chart containing multiple pie charts with a “3D effect”: å public static JFreeChart createMultiplePieChart3D(String title, CategoryDataset dataset, TableOrder order, boolean legend, boolean tooltips, boolean urls); Creates a multiple pie chart for the specified CategoryDataset. This chart is constructed using a MultiplePiePlot. The order argument can be either TableOrder.BY ROW or TableOrder.BY COLUMN. A special case of pie chart can be created to display the “difference” between two datasets: å public static JFreeChart createPieChart(String title, PieDataset dataset, PieDataset previousDataset, int percentDiffForMaxScale, boolean greenForIncrease, boolean legend, boolean tooltips, Locale locale, boolean subTitle, boolean showDifference); [1.0.7] Returns a pie chart that displays the difference between the two supplied datasets. å public static JFreeChart createPieChart(String title, PieDataset dataset, PieDataset previousDataset, int percentDiffForMaxScale, boolean greenForIncrease, boolean legend, boolean tooltips, boolean urls, boolean subTitle, boolean showDifference); As above. A ring chart is a customised form of pie chart: å public static JFreeChart createRingChart(String title, PieDataset dataset, boolean legend, boolean tooltips, Locale locale); [1.0.7] Creates a ring chart based on the supplied dataset (which may be null). Numerical values in the default tool tip generator will be formatted according to the specified locale. å public static JFreeChart createRingChart(String title, PieDataset dataset, boolean legend, boolean tooltips, boolean urls); Creates a ring chart based on the supplied dataset (which may be null). Note that URL support is only applicable for charts that are used to create HTML image maps. 22.3.3 Bar Charts To create a bar chart: å public static JFreeChart createBarChart(String title, String categoryAxisLabel, String valueAxisLabel, CategoryDataset dataset, PlotOrientation orientation, boolean legend, boolean tooltips, boolean urls); Creates a horizontal or vertical bar chart for the given CategoryDataset (see the BarRenderer class documentation for an example). To create a bar chart with a “3D effect”: CHAPTER 22. PACKAGE: ORG.JFREE.CHART 133 å public static JFreeChart createBarChart3D(String title, String categoryAxisLabel, String valueAxisLabel, CategoryDataset dataset, PlotOrientation orientation, boolean legend, boolean tooltips, boolean urls); Creates a bar chart with 3D effect for the given CategoryDataset (see the BarRenderer3D class documentation for an example). To create a stacked bar chart: å public static JFreeChart createStackedBarChart(String title, String categoryAxisLabel, String valueAxisLabel, CategoryDataset data, PlotOrientation orientation, boolean legend, boolean tooltips, boolean urls); Creates a stacked bar chart for the given CategoryDataset. To create a stacked bar chart with a “3D effect”: å public static JFreeChart createStackedBarChart3D(String title, String categoryAxisLabel, String valueAxisLabel, CategoryDataset data, PlotOrientation orientation, boolean legend, boolean tooltips, boolean urls); Creates a stacked bar chart with 3D effect for the given CategoryDataset. To create a bar chart using an IntervalXYDataset (bearing in mind that you can use the XYBarDataset wrapper to convert any XYDataset to the required type): å public static JFreeChart createXYBarChart(String title, String xAxisLabel, boolean dateAxis, String yAxisLabel, IntervalXYDataset dataset, PlotOrientation orientation, boolean legend, boolean tooltips, boolean urls); Creates an XY bar chart for the given IntervalXYDataset. The dateAxis argument allows you to select whether the chart is created with a DateAxis or a NumberAxis for the domain axis. The chart created with this method uses a XYPlot and XYBarRenderer. 22.3.4 Line Charts To create a line chart based on a CategoryDataset: å public static JFreeChart createLineChart(String title, String categoryAxisLabel, String valueAxisLabel, CategoryDataset dataset, PlotOrientation orientation, boolean legend, boolean tooltips, boolean urls); Creates a line chart for the given CategoryDataset. The chart will be constructed with a CategoryPlot and a LineAndShapeRenderer. å public static JFreeChart createLineChart3D(String title, String categoryAxisLabel, String valueAxisLabel, CategoryDataset dataset, PlotOrientation orientation, boolean legend, boolean tooltips, boolean urls); Creates a line chart for the given CategoryDataset, with a pseudo 3D effect. The chart will be constructed with a CategoryPlot and a LineRenderer3D. To create a line chart based on a XYDataset: å public static JFreeChart createXYLineChart(String title, String xAxisLabel, String yAxisLabel, XYDataset dataset, PlotOrientation orientation, boolean legend, boolean tooltips, boolean urls) Creates a XY line chart for the given XYDataset. 22.3.5 Other Chart Types To create a scatter plot: å public static JFreeChart createScatterPlot(String title, String xAxisLabel, String yAxisLabel, XYDataset data, PlotOrientation orientation, boolean legend, boolean tooltips, boolean urls); Creates a scatter plot for the given XYDataset. To create a time series chart: CHAPTER 22. PACKAGE: ORG.JFREE.CHART 134 å public static JFreeChart createTimeSeriesChart(String title, String timeAxisLabel, String valueAxisLabel, XYDataset data, boolean legend, boolean tooltips, boolean urls); Creates a time series chart for the given XYDataset. To create a high-low-open-close chart: å public static JFreeChart createHighLowChart(String title, String timeAxisLabel, String valueAxisLabel, OHLCDataset dataset, Timeline timeline, boolean legend); Creates a high-low-open-close chart for the given OHLCDataset. To create a candlestick chart: å public static JFreeChart createCandlestickChart(String title, String timeAxisLabel, String valueAxisLabel, OHLCDataset data, boolean legend); Creates a candlestick chart for the given OHLCDataset. To create an area chart using data from a XYDataset: å public static JFreeChart createXYAreaChart(String title, String xAxisLabel, String yAxisLabel, XYDataset dataset, PlotOrientation orientation, boolean legend, boolean tooltips, boolean urls); Creates an area chart for the specified dataset. The chart that is created uses a XYPlot and a XYAreaRenderer. To create a stacked area chart using data from a TableXYDataset: å public static JFreeChart createStackedXYAreaChart(String title, String xAxisLabel, String yAxisLabel, TableXYDataset dataset, PlotOrientation orientation, boolean legend, boolean tooltips, boolean urls); Creates a stacked area chart for the specified dataset (notice that the dataset must be a TableXYDataset for stacking). The chart that is created uses a XYPlot and a StackedXYAreaRenderer. To create a box-and-whisker chart where the domain values are categories: å public static JFreeChart createBoxAndWhiskerChart(String title, String categoryAxisLabel, String valueAxisLabel, BoxAndWhiskerCategoryDataset dataset, boolean legend); [1.0.4] Creates a box-and-whisker chart from the specified dataset. This chart will use a CategoryPlot and a BoxAndWhiskerRenderer. To create a box-and-whisker chart where the domain values are numbers or dates: å public static JFreeChart createBoxAndWhiskerChart(String title, String timeAxisLabel, String valueAxisLabel, BoxAndWhiskerXYDataset dataset, boolean legend); Creates a box-and-whisker chart from the specified dataset. This chart will use a XYPlot and a BoxAndWhiskerRenderer. 22.3.6 Notes This class contains methods for common chart types only. There are many other chart types that you can create by mixing and matching plots and renderers. It is worthwhile to review the source code for the methods in this class, then consider how you could substitute different renderers or axes to create different types of charts. Don’t be afraid to copy, paste and modify the code from this class! 22.4 ChartFrame 22.4.1 Overview A frame containing a chart within a ChartPanel. CHAPTER 22. PACKAGE: ORG.JFREE.CHART 22.4.2 135 Constructors There are two constructors: å public ChartFrame(String title, JFreeChart chart); Creates a new ChartFrame containing the specified chart. The second constructor gives you the opportunity to request that the chart is contained within a JScrollPane: å public ChartFrame(String title, JFreeChart chart, boolean scrollPane); Creates a new ChartFrame containing the specified chart. The scrollPane flag indicates whether or not the chart should be displayed within a ScrollPane. 22.4.3 Methods To access the chart’s panel: å public ChartPanel getChartPanel(); Returns the panel that contains the chart. Notes This class is used in a few demo applications, but you won’t generally need to use it yourself— instead, you’ll most likely create a ChartPanel and add that directly to your own forms. 22.5 ChartMouseEvent 22.5.1 Overview An event generated by the ChartPanel class to represent a mouse click or a mouse movement over a chart. These events are passed to listeners via the ChartMouseListener interface. 22.5.2 Constructor To create a new event: å public ChartMouseEvent(JFreeChart chart, MouseEvent trigger, ChartEntity entity); Creates a new event for the specified chart. The event also records the underlying trigger event and the entity underneath the mouse pointer (possibly null). Event objects will usually be created by the ChartPanel class and sent to all registered listeners—you won’t normally need to create an instance of this class yourself. 22.5.3 Methods Use the following methods to access the attributes for the event: å public JFreeChart getChart(); Returns the chart (never null) that the event relates to. å public MouseEvent getTrigger(); Returns the underlying mouse event (never null) that triggered the generation of this event. This contains information about the mouse location, among other things. Note that the mouse location here is given in coordinates relative to the source component (which is the ChartPanel)—to convert to the corresponding (x, y) values in data space, you need to take into account the axis ranges and the current data area (see MouseListenerDemo4.java for an example). å public ChartEntity getEntity(); Returns the chart entity underneath the mouse pointer (this may be null). There are many subclasses of the ChartEntity class, and by determining which subclass is used you can find additional information about the entity “underneath” the mouse pointer. CHAPTER 22. PACKAGE: ORG.JFREE.CHART 22.5.4 136 Notes Some points to note: • to receive notification of these events, an object first needs to implement the ChartMouseListener interface and then register itself with a ChartPanel object, via the addChartMouseListener() method (see section 22.7.6);1 • some demos (MouseListenerDemo1-4.java) are included in the JFreeChart demo collection. 22.6 ChartMouseListener 22.6.1 Overview An interface that defines the callback methods for a chart mouse listener. Any class that implements this interface can be registered with a ChartPanel and receive notification of mouse events. This mechanism can be used to implement interactive charts in Swing applications (information about the chart element at the current mouse location is contained in the ChartMouseEvent object). This is a low-level mechanism, but very flexible. 22.6.2 Methods This receives notification of mouse click events: å void chartMouseClicked(ChartMouseEvent event); A callback method for receiving notification of a mouse click on a chart. This method receives notification of mouse movement events: å void chartMouseMoved(ChartMouseEvent event); A callback method for receiving notification of a mouse movement event on a chart. 22.6.3 Notes Some points to note: • some demo applications (MouseListenerDemo1-4.java) are included in the JFreeChart demo collection. 22.7 ChartPanel 22.7.1 Overview A panel that provides a convenient means to display a JFreeChart instance in a Swing-based userinterface (extends javax.swing.JPanel). The panel can be set up to include a popup menu providing access to: • chart properties – the property editors are incomplete, but allow you to customise many chart properties; • printing – print a chart via the standard Java printing facilities; • saving – write the chart to a PNG format file; 1 It should be obvious, but apparently needs stating in some cases, that the mouse events relate to JFreeChart usage in a Swing-based application—if you are developing web-applications (and don’t want to employ applets or Java Web Start) then you’ll need to rely on chart images plus HTML image maps (all of which JFreeChart can help with, but none of which have anything to do with ChartMouseEvents). CHAPTER 22. PACKAGE: ORG.JFREE.CHART 137 • zooming – zoom in or out by adjusting the axis ranges; In addition, the panel can: • provide offscreen buffering to improve performance when redrawing overlapping frames; • display tool tips; All of these features are used in the demonstration applications included with the JFreeChart Developer Guide. 22.7.2 Constructors The standard constructor accepts a JFreeChart as the only parameter, and creates a panel that displays the chart: å public ChartPanel(JFreeChart chart); Creates a new panel for displaying the specified chart. By default, the panel is automatically updated whenever the chart changes (for example, if you modify the range for an axis, the chart will be redrawn automatically). å public ChartPanel(JFreeChart chart, boolean useBuffer); Creates a new panel for displaying the specified chart. If useBuffer is true, the panel draws the chart to an off-screen buffered image, then copies the image to the screen as required. For charts that draw slowly (for example, those with a large number of data points), this will improve performance by ensuring that the chart is only redrawn when necessary. 22.7.3 The Chart The chart that is displayed by the panel is accessible via the following methods: å public JFreeChart getChart(); Returns the chart that is displayed in the panel. å public void setChart(JFreeChart chart); Sets the chart that is displayed in the panel. The panel registers with the chart as a change listener, so that it can repaint the chart whenever it changes. 22.7.4 Chart Scaling JFreeChart is designed to draw charts at arbitrary sizes. In the case of the ChartPanel class, the chart is drawn to fit the current size of the panel (which is usually determined externally by a layout manager). When the panel gets very small (or very large) the layout procedure used by JFreeChart may not produce good results. To counteract this, the ChartPanel class specifies minimum and maximum drawing thresholds. When the panel dimensions fall below the minimum threshold (or above the maximum threshold) the chart is drawn at the maximum (minimum) size then scaled down (up) to fit the actual panel size. You can control the threshold values with the following methods: å public int getMinimumDrawWidth(); Returns the lower threshold for the chart drawing width. The default is 300 pixels. å public void setMinimumDrawWidth(double width); Sets the lower threshold for the chart drawing width. If the panel is narrower than this, the chart is drawn at the specified width then scaled down to fit the panel. å public int getMinimumDrawHeight(); Returns the lower threshold for the chart drawing height. The default is 200 pixels. CHAPTER 22. PACKAGE: ORG.JFREE.CHART 138 å public void setMinimumDrawHeight(double height); Sets the lower threshold for the chart drawing height. If the panel is shorter than this, the chart is drawn at the specified height then scaled down to fit the panel. For the maximum drawing size threshold, you can use the following methods: å public int getMaximumDrawWidth(); Returns the upper threshold for the chart drawing width. The default value is 800 pixels. å public void setMaximumDrawWidth(double width); Sets the upper threshold for the chart drawing width. If the panel is wider than this, the chart is drawn at the specified width then scaled up to fit the panel. å public int getMaximumDrawHeight(); Returns the upper threshold for the chart drawing height. The default value is 600 pixels. å public void setMaximumDrawHeight(double height); Sets the upper threshold for the chart drawing height. If the panel is taller than this, the chart is drawn at the specified height then scaled up to fit the panel. When chart scaling is being applied, the getScreenDataArea() can be used to determine the data area in the coordinate space of the panel. 22.7.5 Tooltips The panel includes support for displaying tool tips (assuming that tool tips have been generated by the plot or renderer). To disable (or re-enable) the display of tool tips, use the following method: å public void setDisplayToolTips(boolean flag); Switches the display of tool tips on or off for this panel. The panel uses the standard Swing tool tip mechanism, which means that the tool tip timings (initial delay, dismiss delay and reshow delay) can be controlled application-wide using the usual Swing API calls. In addition, the panel has a facility to temporarily override the application wide settings while the mouse pointer is within the bounds of the panel: å public void setInitialDelay(int delay); Sets the initial delay (in milliseconds) before tool tips are displayed. å public void setDismissDelay(int delay); Sets the delay (in milliseconds) before tool tips are dismissed. å public void setReshowDelay(int delay); Sets the delay (in milliseconds) before tool tips are reshown. 22.7.6 Chart Mouse Events Any object that implements the ChartMouseListener interface can register with the panel to receive notification of any mouse events that relate to the chart. å public void addChartMouseListener(ChartMouseListener listener) Adds an object to the list of objects that should receive notification of any ChartMouseEvents that occur. å public void removeChartMouseListener(ChartMouseListener listener); Removes an object from the list of objects that should receive notification of chart mouse events. CHAPTER 22. PACKAGE: ORG.JFREE.CHART 22.7.7 139 The Popup Menu The chart panel has a popup menu that provides menu items for property editing, saving charts to PNG, printing charts, and some zooming options. The constructors provide options for including/excluding any of these options. You can access the popup menu with the following methods: å public JPopupMenu getPopupMenu(); Returns the popup menu for the panel. å public void setPopupMenu(JPopupMenu popup); Sets the popup menu for the panel. Set this to null if you don’t want a popup menu at all. A couple of the functions that can be accessed via the popup menu can also be called via the API: å public void doEditChartProperties(); [1.0.3] Presents a chart property editor that allows some chart properties to be updated. As mentioned elsewhere, the property editors are incomplete. å public void doSaveAs() throws IOException; Presents a file chooser component that allows the user to save the chart to a file in PNG format. å public void createChartPrintJob(); Presents a print dialog and prints the chart to a single page. A default directory can be specified for the “save as” option: å public File getDefaultDirectoryForSaveAs(); [1.0.7] Returns the default directory presented in the file chooser when saving a chart via the “Save As...” menu item. The default value is null, which means the user’s home directory is selected. å public void setDefaultDirectoryForSaveAs(File directory); [1.0.7] Sets the default directory that is presented in the file chooser when saving a chart via the “Save As...” menu item. If you set this to null, the user’s home directory will be used as the default. If the directory argument is not in fact a directory, this method throws an IllegalArgumentException. 22.7.8 Zooming The chart panel supports chart zooming for many types of charts. From the user perspective, zooming is initiated either via the popup menu or via a mouse drag on the displayed chart. The following methods are used to switch zooming on or off, for one or both axes: å public boolean isDomainZoomable(); Returns true if the panel will update the domain axis bounds in response to zoom requests, and false otherwise. å public void setDomainZoomable(boolean flag); Sets the flag that controls whether or not the panel will update the domain axis bounds (assuming the axis supports this) in response to zoom requested. å public boolean isRangeZoomable(); Returns true if the panel will update the range axis bounds in response to zoom requests, and false otherwise. å public void setRangeZoomable(boolean flag); Sets the flag that controls whether or not the panel will update the range axis bounds (assuming the axis supports this) in response to zoom requested. å public void setMouseZoomable(boolean flag); A convenience method that sets the domainZoomable and rangeZoomable flags simultaneously. å public void setMouseZoomable(boolean flag, boolean fillRectangle) A convenience method that sets the domainZoomable and rangeZoomable flags simultaneously. The fillZoomRectangle flag controls the appearance of the rectangle drawn on the panel to show the zoom area while the user drags the mouse over the chart panel: CHAPTER 22. PACKAGE: ORG.JFREE.CHART 140 å public boolean getFillZoomRectangle(); Returns true if the zoom rectangle should be filled, and false if it should be drawn as an outline only. å public void setFillZoomRectangle(boolean flag); Sets the flag that controls whether or not the zoom rectangle is filled or drawn as an outline. The zoom rectangle is displayed while the mouse is dragged within the chart panel, to highlight the area that will be displayed in the chart once the zoom is completed. The zoom trigger distance specifies the minimum distance that the mouse must be dragged before a zoom operation is triggered: å public int getZoomTriggerDistance(); Returns the minimum distance (in Java2D units) that the mouse must be dragged in order to trigger a zoom operation. The default value is 10. å public void setZoomTriggerDistance(int distance); Sets the minimum distance (in Java2D units) that the mouse must be dragged in order to trigger a zoom operation. The zooming operations interact with the plot via the Zoomable interface—plots that do not implement this interface will not be zoomable. 22.7.9 Other Methods To get information about the entities in the chart drawn within the panel: å public ChartRenderingInfo getChartRenderingInfo(); Returns a structure containing information about the chart drawn within the panel. Note that any dimensions in this structure do not take into account the scaling that may be applied by the panel. Some convenience methods can return information about the chart. To find the data area for a chart (that is, the area inside the axes where the data is plotted) in the coordinate space of the panel, you can use the following methods: å public Rectangle2D getScreenDataArea(); Returns the area within which the data is plotted, in screen coordinates. This takes into account any scaling applied by the panel—see section 22.7.4. å public Rectangle2D getScreenDataArea(int x, int y); Returns the area within which the data is plotted on the screen, for the subplot at the screen coordinate (x, y). The returned data area is also specified in screen coordinates—this takes into account any scaling applied by the panel. If the chart doesn’t have any subplots, this method is equivalent to the getScreenDataArea() method (that is, it returns the data area for the main plot). 22.7.10 Notes The size of the ChartPanel is determined by the layout manager used to arrange components in your user interface. In some cases, the layout manager will respect the preferred size of the panel, which you can set like this: chartPanel.setPreferredSize(new Dimension(500, 270)); This class implements the Printable interface, to provide a simple mechanism for printing a chart. An option in the panel’s popup menu calls the createPrintJob() method. The print job ends up calling the print() method to draw the chart on a single piece of paper. If you need greater control over the printing process—for example, you want to display several charts on one page—you can write your own implementation of the Printable interface (in any class that has access to the chart(s) you want to print). The implementation incorporated with the ChartPanel class is a basic example, provided for convenience only. CHAPTER 22. PACKAGE: ORG.JFREE.CHART 141 See Also JFreeChart. 22.8 ChartRenderingInfo 22.8.1 Overview This class can be used to collect information about a chart as it is rendered, particularly information concerning the dimensions of various sub-components of the chart. In the current implementation, four pieces of information are recorded for most chart types: • the chart area; • the plot area (including the axes); • the data area (“inside” the axes); • the dimensions and other information (including tool tips) for the entities within a chart; You have some control over the information that is generated. For instance, tool tips will not be generated unless you set up a generator in the renderer. 22.8.2 Constructors The default constructor: å public ChartRenderingInfo(); Creates a ChartRenderingInfo object. Entity information will be collected using an instance of StandardEntityCollection. An alternative constructor allows you to supply a specific entity collection: å public ChartRenderingInfo(EntityCollection entities); Creates a ChartRenderingInfo object. 22.8.3 Methods To get the area in which the chart is drawn: å public Rectangle2D getChartArea(); Returns the area in which the chart has been drawn. å public void setChartArea(Rectangle2D area); Sets the area (in Java2D space) into which the chart has been drawn. This method is called by JFreeChart, you won’t normally call it yourself. You should note that this method records (after the fact) where a chart has been drawn—setting this attribute has no impact on the chart itself. To access the entity collection: å public EntityCollection getEntityCollection(); Returns the entity collection (which may be null). å public void setEntityCollection(EntityCollection entities); Sets the entity collection. If you set this to null, no entity information is retained as the chart is rendered (which saves a lot of resources, but means that tooltips and HTML image maps cannot be generated). å public void clear(); Clears all the information from this instance. å public PlotRenderingInfo getPlotInfo(); Returns the PlotRenderingInfo state object for this instance. You can use this to obtain rendering information for the chart’s plot. CHAPTER 22. PACKAGE: ORG.JFREE.CHART 22.8.4 142 Equals, Cloning and Serialization This class overrides the equals() method: å public boolean equals(Object obj); Tests this instance for equality with an arbitrary object. å public Object clone() throws CloneNotSupportedException; Returns a deep clone of this instance. 22.8.5 Notes The ChartPanel class automatically collects entity information using this class, because it needs it to generate tool tips. 22.9 ChartUtilities 22.9.1 Overview This class contains utility methods for: • creating images from charts—supported formats are PNG and JPEG; • generating HTML image maps. All of the methods in this class are static. 22.9.2 Generating PNG Images The Portable Network Graphics (PNG) format is a good choice for creating chart images. The format offers: • a free and open specification; • fast and effective compression; • no loss of quality when images are reconstructed from the compressed binary format; • excellent support in most web clients; JFreeChart provides support for writing charts in PNG format via either: • an encoder developed by J. David Eisenberg (published as free software under the terms of the GNU LGPL). You can find this encoder at: http://www.catcode.com • Java’s ImageIO library; The former option is used on JDK 1.3.1, while the latter option is used with JDK 1.4.2 or later. The most general method allows you to write the image data directly to an output stream: å public static void writeChartAsPNG(OutputStream out, JFreeChart chart, int width, int height) throws IOException Writes a chart image of the specified size directly to the output stream in PNG format. If you need to retain information about the chart dimensions and content (to create an HTML image map, for example) you can pass in a newly created ChartRenderingInfo object using this method: CHAPTER 22. PACKAGE: ORG.JFREE.CHART 143 å public static void writeChartAsPNG(OutputStream out, JFreeChart chart, int width, int height, ChartRenderingInfo info) Writes a chart image of the specified size directly to the output stream, and collects chart information in the supplied info object. If info is null, no chart info is collected. The above methods have counterparts that write image data directly to a file: å public static void saveChartAsPNG(File file, JFreeChart chart, int width, int height); Saves a chart image of the specified size into the specified file, using the PNG format. å public static void saveChartAsPNG(File file, JFreeChart chart, int width, int height, ChartRenderingInfo info); Saves a chart to a PNG format image file. If an info object is supplied, it will be populated with information about the structure of the chart. 22.9.3 Generating JPEG Images The Joint Photographic Experts Group (JPEG) image format is supported using methods that are almost identical to those listed for PNG in the previous section. NOTE: JPEG is not an ideal format for charts. Images lose some definition after decompression from this format. This is most noticeable in high color contrast areas, which are common in charts. It is recommended that you use PNG format instead of JPEG, if at all possible. Since JFreeChart must rely on Java’s ImageIO API to write images in JPEG format, these methods can only be used on Java 1.4.2 or later. To write a chart to a file in JPEG format: å public static void saveChartAsJPEG(File file, JFreeChart chart, int width, int height); Equivalent to saveChartAsJPEG(file, chart, width, height, null)—see the next method. As with the PNG methods, if you need to know more information about the structure of the chart within the generated image, you will need to pass in a ChartRenderingInfo object: å public static void saveChartAsJPEG(File file, JFreeChart chart, int width, int height, ChartRenderingInfo info); Saves a chart to a JPEG format image file with the specified dimensions. If info is not null, it will be populated with information about the structure of the chart. If file or chart is null, this method throws an IllegalArgumentException. Alternative methods allow you to specify the quality setting for the JPEG encoding: å public static void saveChartAsJPEG(File file, float quality, JFreeChart chart, int width, int height) throws IOException; Equivalent to saveChartAsJPEG(file, quality, chart, width, height, null)—see the next method. å public static void saveChartAsJPEG(File file, float quality, JFreeChart chart, int width, int height, ChartRenderingInfo info) throws IOException; Saves a chart to a JPEG format image file with the specified dimensions. The quality setting should be in the range 0.0 (low quality) to 1.0 (high quality). If file or chart is null, this method throws an IllegalArgumentException. 22.9.4 HTML Image Maps An HTML image map is an HTML fragment used to describe the characteristics of an image file. The image map can define regions within the image, and associate these with URLs and tooltip information. NOTE: Most methods supporting HTML image map creation have been relocated in the ImageMapUtilities class. CHAPTER 22. PACKAGE: ORG.JFREE.CHART 144 To generate a simple HTML image map for a JFreeChart instance, first generate an image for the chart and be sure to retain the ChartRenderingInfo object from the image drawing. Then, generate the image map using the following method: å public static void writeImageMap(PrintWriter writer, String name, ChartRenderingInfo info, boolean useOverLibForToolTips); Writes a element containing the region definitions for a chart that has been converted to an image. The info object should be the structure returned from the method call that wrote the chart to an image file. There are two demonstration applications in the JFreeChart download that illustrate how this works: ImageMapDemo1 and ImageMapDemo2. 22.9.5 Notes Some points to note: • when writing charts to image files, PNG tends to be a better format for charts than JPEG since the compression is “lossless” for PNG. 22.10 ClipPath 22.10.1 Overview This class is used by the ContourPlot class. This class is deprecated as of version 1.0.4. 22.11 DrawableLegendItem 22.11.1 Overview Used to represent a LegendItem plus it’s physical drawing characteristics (position, label location etc.) as it is being laid out on the chart. This class is deprecated (as of version 1.0.2) as it is no longer used by JFreeChart. 22.12 Effect3D 22.12.1 Overview An interface that should be implemented by renderers that use a “3D effect”. This allows the 3D axis classes to synchronise their own “3D effect” with that of the renderer and plot. 22.12.2 Methods This interface defines two methods: å public double getXOffset(); Returns the x-offset (in Java2D units) for the 3D effect. å public double getYOffset(); Returns the y-offset (in Java2D units) for the 3D effect. See Also BarRenderer3D, CategoryAxis3D, NumberAxis3D. CHAPTER 22. PACKAGE: ORG.JFREE.CHART 22.13 HashUtilities 22.13.1 Overview 145 A utility class to assist with the generation of hash codes. This class was first introduced in JFreeChart 1.0.3. 22.13.2 Methods The following methods compute hash codes for the specified input: å public static int hashCodeForPaint(Paint p); [1.0.3] å public static int hashCodeForDoubleArray(double[] a); [1.0.3] å public static int hashCode(int pre, boolean b); [1.0.7] å public static int hashCode(int pre, double d); [1.0.7] å public static int hashCode(int pre, Paint p); [1.0.7] å public static int hashCode(int pre, Stroke s); [1.0.7] å public static int hashCode(int pre, String s); [1.0.7] å public static int hashCode(int pre, Comparable c); [1.0.7] å public static int hashCode(int pre, int i); [1.0.8] å public static int hashCode(int pre, Object obj); [1.0.8] å public static int hashCode(int pre, BooleanList list); [1.0.9] å public static int hashCode(int pre, PaintList list); [1.0.9] å public static int hashCode(int pre, StrokeList list); [1.0.9] 22.14 JFreeChart 22.14.1 Overview The JFreeChart class coordinates the entire process of drawing charts. One method: public void draw(Graphics2D g2, Rectangle2D area); ...instructs the JFreeChart object to draw a chart onto a specific area on some graphics device. Java supports several graphics devices—including the screen, the printer, and buffered images—via different implementations of the abstract class java.awt.Graphics2D. Thanks to this abstraction, JFreeChart can generate charts on any of these target devices, as well as others implemented by third parties (for example, the SVG Generator implemented by the Batik Project). CHAPTER 22. PACKAGE: ORG.JFREE.CHART 146 In broad terms, the JFreeChart class sets up a context for drawing a Plot. The plot obtains data from a Dataset, and may delegate the drawing of individual data items to a CategoryItemRenderer or an XYItemRenderer, depending on the plot type (not all plot types use renderers). The JFreeChart class can work with many different Plot subclasses. Depending on the type of plot, a specific dataset will be required. Table 22.1 summarises the combinations that are currently available: Dataset: Compatible Plot Types: BoxAndWhiskerCategoryDataset BoxAndWhiskerXYDataset CategoryDataset CategoryPlot with a BoxAndWhiskerRenderer. XYPlot with a XYBoxAndWhiskerRenderer. CategoryPlot subclasses with various renderers, or a SpiderWebPlot. ContourPlot. CategoryPlot with a GanttRenderer. CategoryPlot with an IntervalBarRenderer. XYPlot with an XYBarRenderer. XYPlot with a HighLowRenderer or a CandlestickRenderer. PiePlot. CategoryPlot with a classfStatisticalBarRenderer. CompassPlot, MeterPlot and ThermometerPlot. WaferMapPlot. XYPlot with a WindItemRenderer. XYPlot with various renderers. XYPlot with an XYBubbleRenderer. ContourDataset GanttCategoryDataset IntervalCategoryDataset IntervalXYDataset OHLCDataset PieDataset StatisticalCategoryDataset ValueDataset WaferMapDataset WindDataset XYDataset XYZDataset Table 22.1: Compatible plot and dataset types 22.14.2 Constructors All constructors require you to supply a Plot instance (the Plot maintains a reference to the dataset used for the chart). The simplest constructor is: å public JFreeChart(Plot plot); Creates a new JFreeChart instance. The chart will have no title, and no legend. For greater control, a more complete constructor is available: å public JFreeChart(Plot plot, String title, Font titleFont, boolean createLegend); Creates a new JFreeChart instance. This constructor allows you to specify a single title (you can add additional titles, later, if necessary). The ChartFactory class provides some utility methods that can make the process of constructing charts simpler. 22.14.3 Attributes The attributes maintained by the JFreeChart class are listed in Table 22.2. 22.14.4 Anti-Aliasing When drawing to pixel-based displays, the use of a technique called anti-aliasing can improve the appearance of the output by “smoothing” the edges of lines and shapes. Using anti-aliasing for drawing operations is usually slower, but the results often look better. You can control whether or not JFreeChart uses anti-aliasing with the following methods: å public boolean getAntiAlias(); Returns true if this chart is drawn with anti-aliased graphics, and false otherwise. CHAPTER 22. PACKAGE: ORG.JFREE.CHART Attribute: Description: borderVisible A flag that controls whether or not a border is drawn around the outside of the chart. The Stroke used to draw the chart’s border. The Paint used to paint the chart’s border. The chart title (an instance of TextTitle). A list of subtitles. The chart legend. The plot. A flag that indicates whether or not the chart should be drawn with anti-aliasing. The background paint for the chart. An optional background image for the chart. The alignment of the background image (if there is one). The alpha transparency for the background image. A flag that controls whether or not change events are passed on to the chart’s registered listeners; The Java2D rendering hints that will be applied when the chart is drawn. borderStroke borderPaint title subTitles legend plot antialias backgroundPaint backgroundImage backgroundImageAlignment backgroundImageAlpha notify renderingHints 147 Table 22.2: Attributes for the JFreeChart class å public void setAntiAlias(boolean flag); Sets a flag controlling whether or not anti-aliasing is used when drawing the chart, and sends a ChartChangeEvent to all registered listeners. While people generally agree that anti-aliased shapes and lines look better, opinion is divided when it comes to text. Fortunately, the anti-aliasing setting can be controlled independently for text items, using the following methods: å public Object getTextAntiAlias(); [1.0.5] Returns the current hint for text anti-aliasing—see the java.awt.RenderingHints class for valid values. The default value is null, which generally means that the text follows the general anti-aliasing hint (see getAntiAlias()). å public void setTextAntiAlias(boolean flag); [1.0.5] A convenience method that switches text anti-aliasing on or off—see the following method. å public void setTextAntiAlias(Object val); [1.0.5] Sets the text anti-aliasing hint value to val and sends a ChartChangeEvent to all registered listeners. Valid arguments include: • null – clears the setting, in which case the text will generally follow the hint that applies to general graphics (see getAntiAlias()); • RenderingHints.VALUE TEXT ANTIALIAS ON – text anti-aliasing on; • RenderingHints.VALUE TEXT ANTIALIAS OFF – text anti-aliasing off; • RenderingHints.VALUE TEXT ANTIALIAS GASP – introduced in Java 1.6.0, this setting turns anti-aliasing off for certain font sizes where hinting is optimal, and on for other sizes. 22.14.5 Methods The most important method for a chart is the draw() method: å public void draw(Graphics2D g2, Rectangle2D chartArea); Draws the chart on the Graphics2D device, within the specified area. The chart does not retain any information about the location or dimensions of the items it draws. Callers that require such information should use the alternative method: CHAPTER 22. PACKAGE: ORG.JFREE.CHART 148 å public void draw(Graphics2D g2, Rectangle2D chartArea, ChartRenderingInfo info); Draws the chart on the Graphics2D device, within the specified area. If info is not null, it will be populated with information about the items drawn within the chart (to be returned to the caller). To set the title for a chart: å public void setTitle(String title); Sets the title for a chart and sends a ChartChangeEvent to all registered listeners. An alternative method for setting the chart title is: å public void setTitle(TextTitle title); Sets the title for a chart and sends a ChartChangeEvent to all registered listeners. Although a chart can have only one title, it can have any number of subtitles: å public void addSubtitle(Title title); Adds a title to the chart. The legend shows the names of the series (or sometimes categories) in a chart, next to a small color indicator. To add a legend to the chart: å public void addLegend(LegendTitle legend); Adds a legend to the chart and triggers a ChartChangeEvent. An IllegalArgumentException is thrown if legend is null. Note that legends are implemented as chart titles, so they can be positioned in the same way as any subtitle (at the top, bottom, left or right of the chart). å public void removeLegend(); Removes the first legend from the chart and triggers a ChartChangeEvent. To set the background paint for the chart: å public void setBackgroundPaint(Paint paint); Sets the background paint for the chart and sends a ChartChangeEvent to all registered listeners. If this is set to null, the chart background will be transparent. 22.14.6 Background Image A chart can have a background image (optional)—for an example, see TimeSeriesDemo4.java in the JFreeChart demo collection. å public Image getBackgroundImage(); Returns the background image for the chart (possibly null). å public void setBackgroundImage(Image image); Sets the background image for the chart (null permitted) and sends a ChartChangeEvent to all registered listeners. You must ensure that the image is fully loaded before passing it to this method—see section 20.4 for more information. To control the alignment of the background image: å public int getBackgroundImageAlignment(); Returns a code that specifies the alignment of the background image. å public void setBackgroundImageAlignment(int alignment); Sets the alignment for the background image and sends a ChartChangeEvent to all registered listeners. Standard alignment codes are defined by the Align class. To control the alpha transparency of the background image: å public float getBackgroundImageAlpha(); Returns the alpha transparency for the background image. å public void setBackgroundImageAlpha(float alpha); Sets the alpha transparency for the background image then sends a ChartChangeEvent to all registered listeners. The alpha should be a value between 0.0 (fully transparent) and 1.0 (opaque). An alternative option is to set a background image for the chart’s Plot—this image will be positioned within the plot area only rather than the entire chart area. CHAPTER 22. PACKAGE: ORG.JFREE.CHART 22.14.7 149 The Chart Border A border can be drawn around the outside of a chart, if required. By default, no border is drawn, since in many cases a border can be added externally (for example, in an HTML page). If you do require a border, use the following methods: å public boolean isBorderVisible(); Returns the flag that controls whether or not a border is drawn around the outside of the chart. The default value is false. å public void setBorderVisible(boolean visible); Sets the flag that controls whether or not a border is drawn around the outside of the chart, and sends a ChartChangeEvent to all registered listeners. To control the appearance of the border: å public Stroke getBorderStroke(); Returns the Stroke used to draw the chart border, if there is one. å public void setBorderStroke(Stroke stroke); Sets the Stroke used to draw the chart border, if there is one, and sends a ChartChangeEvent to all registered listeners. å public Paint getBorderPaint(); Returns the Paint used to draw the chart border, if there is one. å public void setBorderPaint(Paint paint); Sets the Paint used to paint the chart border, if there is one, and sends a ChartChangeEvent to all registered listeners. 22.14.8 Chart Change Listeners If an object wants to “listen” for changes that are made to a chart, it needs to implement the ChartChangeListener interface so that it can register with the chart instance to receive ChartChangeEvent notifications. For example, a ChartPanel instance automatically registers itself with the chart that it displays—any change to the chart results in the panel being repainted. To receive notification of any change to a chart, a listener object should register via this method: å public void addChangeListener(ChartChangeListener listener); Register to receive chart change events. To stop receiving change notifications, a listener object should deregister via this method: å public void removeChangeListener(ChartChangeListener listener); Deregister to stop receiving chart change events. There are situations where you might want to temporarily disable the event notification mechanism— use the following methods: å public boolean isNotify(); Returns the flag that controls whether or not change events are sent to registered listeners. å public void setNotify(boolean notify); Sets the flag that controls whether or not change events are sent to registered listeners. You can use this method to temporarily turn off the notification mechanism. For example, when a chart is displayed in a ChartPanel, every update to the chart’s data will trigger a repaint of the chart. If you need to add several items to the chart’s dataset, typically you’ll only want the chart to be repainted once, after the last data item is added. You can achieve that as follows: chart.setNotify(false); // do several dataset updates here... chart.setNotify(true); CHAPTER 22. PACKAGE: ORG.JFREE.CHART 22.14.9 150 Creating Images The JFreeChart class includes utility methods for creating a BufferedImage containing the chart: å public BufferedImage createBufferedImage(int width, int height); Creates a buffered image containing the chart. The size of the image is specified by the width and height arguments. å public BufferedImage createBufferedImage(int width, int height, ChartRenderingInfo info); Creates a buffered image containing the chart. The size of the image is specified by the width and height arguments. The info argument is used to collect information about the chart as it is being drawn (required if you want to create an HTML image map for the image). One other variation draws the chart at one size then scales it (up or down) to fit a different image size: å public BufferedImage createBufferedImage(int imageWidth, int imageHeight, double drawWidth, double drawHeight, ChartRenderingInfo info) Creates an image containing a chart that has been drawn at one size then scaled (up or down) to fit the image size. 22.14.10 Notes Some points to note: • the ChartFactory class provides a large number of methods for creating “ready-made” charts. • the Java2D API is used throughout JFreeChart, so JFreeChart does not work with JDK1.1 (a common question from applet developers). 22.15 LegendItem 22.15.1 Overview A class that records the attributes of an item that should appear in a legend (see the LegendTitle class). Instances of this class are usually created by a renderer, which should set the attributes to match the visual representation of the corresponding series. Table 22.3 lists the attributes defined by the class. Attribute: Description: label description shapeVisible shape shapeFilled fillPaint shapeOutlineVisible outlinePaint outlineStroke lineVisible lineStroke linePaint The label (usually the series name). A description of the item (not currently used). A flag that indicates whether or not the shape is visible. The shape displayed for the legend item. A flag that controls whether or not the shape is filled. The fill paint. A flag that indicates whether or not the shape outline is visible. The outline paint. The outline stroke. A flag that indicates whether or not the line is visible. The line stroke. The line paint. Table 22.3: Attributes for the LegendItem class CHAPTER 22. PACKAGE: ORG.JFREE.CHART 22.15.2 151 Constructors To create a legend item: å public LegendItem(String label, String description, String toolTipText, String urlText, Shape shape, Paint fillPaint); Creates a new legend item record. å public LegendItem(String label, String description, String toolTipText, String urlText, Shape shape, Paint fillPaint, Stroke outlineStroke, Paint outlinePaint); Creates a new legend item record. å public LegendItem(String label, String description, String toolTipText, String urlText, Shape line, Stroke lineStroke, Paint linePaint); Creates a new legend item record. å public LegendItem(String label, String description, String toolTipText, String urlText, boolean shapeVisible, Shape shape, boolean shapeFilled, Paint fillPaint, boolean shapeOutlineVisible, Paint outlinePaint, Stroke outlineStroke, boolean lineVisible, Shape line, Stroke lineStroke, Paint linePaint); Creates a new legend item record. å public LegendItem(AttributedString label, String description, String toolTipText, String urlText, Shape shape, Paint fillPaint); Creates a new legend item record. å public LegendItem(AttributedString label, String description, String toolTipText, String urlText, Shape shape, Paint fillPaint, Stroke outlineStroke, Paint outlinePaint); Creates a new legend item record. å public LegendItem(AttributedString label, String description, String toolTipText, String urlText, Shape line, Stroke lineStroke, Paint linePaint); Creates a new legend item record. å public LegendItem(AttributedString label, String description, String toolTipText, String urlText, boolean shapeVisible, Shape shape, boolean shapeFilled, Paint fillPaint, boolean shapeOutlineVisible, Paint outlinePaint, Stroke outlineStroke, boolean lineVisible, Shape line, Stroke lineStroke, Paint linePaint); Creates a new legend item record. 22.15.3 Methods The following methods are defined: å public int getDatasetIndex(); [1.0.2] Returns the dataset index for this legend item. å public void setDatasetIndex(int index); [1.0.2] Sets the dataset index for this legend item. å public int getSeriesIndex(); [1.0.2] Returns the series index for this legend item. å public void setSeriesIndex(int index); [1.0.2] Sets the series index for the legend item. å public String getLabel(); Returns the legend item label. å public AttributedString getAttributedLabel(); Returns an attributed legend item label, or null. å public String getDescription(); Returns the description for the legend item (not used). å public String getToolTipText(); Returns the tool tip text for the legend item. CHAPTER 22. PACKAGE: ORG.JFREE.CHART 152 å public String getURLText(); Returns the URL for the legend item (only used in HTML image maps). å public boolean isShapeVisible(); Returns a flag that controls whether or not the legend item shape should be displayed. å public Shape getShape(); Returns the shape to display as the graphic for this legend item. å public boolean isShapeFilled(); Returns a flag that controls whether or not the legend item shape should be filled. å public Paint getFillPaint(); Returns the fill paint for the series represented by this legend item. å public boolean isShapeOutlineVisible(); Returns a flag that controls whether or not the legend item shape should have its outline drawn. å public Stroke getLineStroke(); Returns the stroke used to draw the line for the legend item graphic. å public Paint getLinePaint(); Returns the line paint. å public Paint getOutlinePaint(); Returns the outline paint for the series represented by this legend item. å public Stroke getOutlineStroke(); Returns the outline stroke for the series represented by this legend item. å public boolean isLineVisible(); Returns a flag that controls whether or not a line is drawn as part of the legend item graphic. å public Shape getLine(); Returns the line, if any, to be drawn for the legend item graphic. å public GradientPaintTransformer getFillPaintTransformer(); [1.0.4] Returns the gradient paint transformer, if any, used by the renderer for the series represented by this legend item. å public void setFillPaintTransformer(GradientPaintTransformer transformer); [1.0.4] Sets the gradient paint transformer used by the renderer for the series represented by this legend item. 22.15.4 Notes Some points to note: • the LegendItemSource interface defines a method that should return a collection of legend items; • originally this was an immutable class, which is why there are so many constructors with varying arguments, and some attributes with no setter methods; • this class implements the Serializable interface. See Also LegendItemCollection, LegendTitle. 22.16 LegendItemCollection 22.16.1 Overview A collection of legend items, typically returned by the getLegendItems() method in the plot classes. You can create your own collection of legend items and pass it to a CategoryPlot or XYPlot via the setFixedLegendItems() method, as a way of overriding the automatically generated legend items. CHAPTER 22. PACKAGE: ORG.JFREE.CHART 22.16.2 153 Constructors There is a single constructor: å public LegendItemCollection(); Creates a new empty collection. 22.16.3 Methods To add an item to the collection: å public void add(LegendItem item); Adds the specified item to the collection. To add a collection of items to this collection: å public void addAll(LegendItemCollection collection); Adds all the items from the given collection to this collection (by copying references, the items themselves are not duplicated/cloned). To find out how many items there are in the collection: å public int getItemCount(); Returns the number of items in the collection. To retrieve an item from the collection: å public LegendItem get(int index); Returns the item with the specified index. To get an iterator that provides access to the items in the collection: å public Iterator iterator(); Returns an iterator that provides access to the items in the collection. 22.16.4 Equals, Cloning and Serialization This class overrides the equals() method: å public boolean equals(Object obj); Tests this collection for equality with an arbitrary object. This method returns true if and only if: • obj is not null; • obj is an instance of LegendItemCollection; • both collections contain the same items in the same order. Instances of this class are Cloneable and Serializable. See Also LegendItem. 22.17 LegendItemSource 22.17.1 Overview An interface for obtaining a collection of legend items. This interface is implemented (or extended) by: • Plot (to work for all plot types); • CategoryItemRenderer; • XYItemRenderer; A LegendTitle will use one or more of these sources to obtain legend items for display on the chart. This provides an opportunity for the legend to display just a subset of the items from a chart, if required. CHAPTER 22. PACKAGE: ORG.JFREE.CHART ID: Description: LegendRenderingOrder.STANDARD LegendRenderingOrder.REVERSE Items are rendered in order. Items are rendered in reverse order. 154 Table 22.4: Tokens defined by LegendRenderingOrder 22.17.2 Methods To obtain a collection of legend items: å public LegendItemCollection getLegendItems(); Returns a collection of legend items (possibly empty, but never null). See Also LegendItem, LegendItemCollection. 22.18 LegendRenderingOrder 22.18.1 Overview A class that defines tokens that control the order of the items in the legend. See table 22.4 for the tokens that are defined. 22.18.2 Notes This class is a left-over from older versions of JFreeChart, and is not currently used. It should probably be deprecated. 22.19 PolarChartPanel 22.19.1 Overview An extension of the ChartPanel class with a pop-up menu that applies to polar charts. Chapter 23 Package: org.jfree.chart.annotations 23.1 Overview The annotations framework provides a mechanism for adding small text and graphics items to charts, usually to highlight a particular data item. In the current release, annotations can be added to the CategoryPlot and XYPlot classes. This framework is relatively basic at present, additional features are likely to be added in the future. 23.2 AbstractXYAnnotation 23.2.1 Overview A base class that can be used by classes that need to implement the XYAnnotation interface. Subclasses provided by JFreeChart include: • XYBoxAnnotation – draws a box at specified data coordinates; • XYDrawableAnnotation – draws an instance of Drawable; • XYImageAnnotation – draws an image; • XYLineAnnotation – draws a line between specified data coordinates; • XYPointerAnnotation – draws some text plus an arrow pointing at a data point; • XYPolygonAnnotation – draws a polygon; • XYShapeAnnotation – draws an arbitrary Shape; • XYTextAnnotation – draws a string. If you create your own custom annotations, you don’t have to subclass AbstractXYAnnotation, but it will save you some work. 23.2.2 Constructors This class defines a single (protected) constructor: å protected AbstractXYAnnotation(); Initialises the tool tip text and URL to null. 155 CHAPTER 23. PACKAGE: ORG.JFREE.CHART.ANNOTATIONS 23.2.3 156 General Attributes To access the tool tip text for the annotation: å public String getToolTipText(); Returns the tool tip text for this annotation. The default value is null. å public void setToolTipText(String text); Sets the tool tip text for this annotation (null is permitted). No change event is generated. To access the URL for the annotation: å public String getURL(); Returns the URL that will be used for this annotation in an HTML image map. The default value is null. å public void setURL(String url); Sets the URL that will be used for this annotation in an HTML image map (null is permitted). No change event is generated. 23.2.4 Other Methods The draw method is abstract, and must be implemented by subclasses: å public abstract void draw(Graphics2D g2, XYPlot plot, Rectangle2D dataArea, ValueAxis domainAxis, ValueAxis rangeAxis, int rendererIndex, PlotRenderingInfo info); To be implemented by subclasses. This method will be called by JFreeChart when the annotation needs to be drawn—you won’t normally call this method directly from your own code. A utility method is provided for subclasses to add an entity: å protected void addEntity(PlotRenderingInfo info, Shape hotspot, int rendererIndex, String toolTipText, String urlText); A utility method for adding an entity—this is available for calling by subclasses (typically from the draw() method). 23.2.5 Equals, Cloning and Serialization This class overrides the equals(Object) method: å public boolean equals(Object obj); Tests this annotation for equality with an arbitrary object. This method returns true if and only if: • obj is not null; • obj is an instance of AbstractXYAnnotation; • both annotations have the same tool tip and URL text. Subclasses of this class should be Cloneable and Serializable, otherwise charts that use these annotations won’t support cloning and serialization. 23.2.6 Notes Some points to note: • there is no event notification mechanism for annotations, so when you update an annotation, the chart display will not automatically be refreshed. One way to trigger a repaint (at least, if your chart is displayed in a ChartPanel) is to call chart.setNotify(true). See Also XYAnnotation. CHAPTER 23. PACKAGE: ORG.JFREE.CHART.ANNOTATIONS 23.3 CategoryAnnotation 23.3.1 Overview 157 The interface that must be supported by annotations that are to be added to a CategoryPlot. The classes that implement this interface are: • CategoryLineAnnotation; • CategoryPointerAnnotation; • CategoryTextAnnotation. You can write your own annotation that implements this interface. Annotations are added to a plot using the addAnnotation() method (in the CategoryPlot class). 23.3.2 Interface This interface defines a single method: å public void draw(Graphics2D g2, CategoryPlot plot, Rectangle2D dataArea, CategoryAxis domainAxis, ValueAxis rangeAxis); Draws the annotation. This method is typically called by JFreeChart, not user code. 23.3.3 Notes Some points to note: • for now, a CategoryAnnotation can only be added directly to a CategoryPlot, and is positioned relative to the plot’s primary axes. It would make sense to allow annotations to be assigned to a renderer (as can be done with XYAnnotation) so that the annotation can be plotted against secondary axes. See Also CategoryLineAnnotation, CategoryPointerAnnotation, CategoryTextAnnotation. 23.4 CategoryLineAnnotation 23.4.1 Overview An annotation that draws a line between two points on a CategoryPlot (each defined by a (category, value) data item).1 This class implements CategoryAnnotation. 23.4.2 Constructor To create a new instance: å public CategoryLineAnnotation(Comparable category1, double value1, Comparable category2, double value2, Paint paint, Stroke stroke); Creates a new annotation that connects (category1, value1) and (category2, value2) with a straight line drawn using the specified paint and stroke. 1 This class was requested by a client. Personally, I don’t see a compelling use for it—if you know of one, please let me know! CHAPTER 23. PACKAGE: ORG.JFREE.CHART.ANNOTATIONS 23.4.3 158 General Attributes To access the location used for the start of the line: å public Comparable getCategory1(); Returns the category for the start of the line (never null). å public void setCategory1(Comparable category); Sets the category for the start of the line (null is not permitted). You should ensure that this category actually exists in the dataset. å public double getValue1(); Returns the value for the start of the line. å public void setValue1(double value); Sets the value for the start of the line. To access the location used for the end of the line: å public Comparable getCategory2(); Returns the category for the start of the line (never null). å public void setCategory2(Comparable category); Sets the category for the end of the line (null is not permitted). You should ensure that this category actually exists in the dataset. å public double getValue2(); Returns the value for the end of the line. å public void setValue2(double value); Sets the value for the end of the line. To access the paint used to draw the line: å public Paint getPaint(); Returns the paint used to draw the line (never null). å public void setPaint(Paint paint); Sets the paint used to draw the line (null is not permitted). To access the stroke used to draw the line: å public Stroke getStroke(); Returns the stroke used to draw the line (never null). å public void setStroke(Stroke stroke); Sets the stroke used to draw the line (null is not permitted). 23.4.4 Other Methods The annotation is drawn by the following method, which is typically called by JFreeChart rather than user code: å public void draw(Graphics2D g2, CategoryPlot plot, Rectangle2D dataArea, CategoryAxis domainAxis, ValueAxis rangeAxis); Draws the annotation. 23.4.5 Equals, Cloning and Serialization This class overrides the equals(Object) method: å public boolean equals(Object obj); Tests this annotation for equality with an arbitrary object. This method returns true if and only if: • obj is not null; • obj is an instance of CategoryLineAnnotation; • both annotations have the same field values. Instances of this class are Cloneable and Serializable. CHAPTER 23. PACKAGE: ORG.JFREE.CHART.ANNOTATIONS 159 See Also CategoryAnnotation. 23.5 CategoryPointerAnnotation 23.5.1 Overview An annotation for a CategoryPlot that displays a text item and an arrow pointing towards a point on a chart defined by a (category, value) pair—see figure 23.1 for an example. This class implements the CategoryAnnotation interface, and was first introduced in JFreeChart 1.0.3. Java Standard Class Library Number of Classes By Release 3000 2800 2600 2400 Class Count 2200 2000 Released 4-Dec-1998 1800 1600 1400 1200 1000 800 600 400 200 0 JDK 1.0 JDK 1.1 JDK 1.2 JDK 1.3 JDK 1.4 Release Source: Java In A Nutshell (4th Edition) by David Flanagan (O'Reilly) Figure 23.1: A CategoryPointerAnnotation (see CategoryPointerAnnotationDemo1.java) 23.5.2 Constructors To create a new instance: å public CategoryPointerAnnotation(String label, Comparable key, double value, double angle); Creates a new pointer annotation. The label is the text to be displayed (null not permitted). The key and value specify the location on the chart for the annotation. The angle specifies the rotation of the arrow that points at the specified point, in radians. To customise the appearance of the arrow, use the methods documented in the next section. 23.5.3 General Attributes In addition to the attributes inherited from CategoryTextAnnotation, this class defines a number of items concerning the appearance of the arrow that points towards a fixed location on the chart. To control the angle of the pointer: å public double getAngle(); [1.0.3] Returns the angle of the pointer (in radians, using the same conventions as Java’s Arc2D class). å public void setAngle(double angle); [1.0.3] Sets the angle of the pointer (in radians, using the same conventions as Java’s Arc2D class). The arrow points towards a location on the chart (specified in the constructor). To control the distance between the tip of the arrow and the anchor point on the chart: å public double getTipRadius(); [1.0.3] Returns the distance from the anchor point to the tip of the arrow, in Java2D units. The default value is 10.0. CHAPTER 23. PACKAGE: ORG.JFREE.CHART.ANNOTATIONS å public void setTipRadius(double radius); [1.0.3] Sets the distance from the anchor point to the tip of the arrow, in Java2D units. Since the tip of the arrow is pointing towards the anchor point, this should be a lower value than the base radius. To control the length of the arrow: å public double getBaseRadius(); [1.0.3] Returns the distance from the anchor point to the base of the arrow, in Java2D units. The default value is 30.0. The difference between the base radius and the tip radius is the overall length of the arrow. å public void setBaseRadius(double radius); [1.0.3] Sets the distance from the anchor point to the base of the arrow, in Java2D units. To control the offset from the base of the arrow to the label anchor point: å public double getLabelOffset(); [1.0.3] Returns the offset from the base of the arrow to the label, in Java2D units. The default value is 3.0. å public void setLabelOffset(double offset); [1.0.3] Sets the offset from the base of the arrow to the label, in Java2D units. To control the length of the arrow head: å public double getArrowLength(); [1.0.3] Returns the length of the arrow head, in Java2D units. The default value is 5.0. å public void setArrowLength(double length); [1.0.3] Sets the length of the arrow head, in Java2D units. To control the width of the arrow head: å public double getArrowWidth(); [1.0.3] Returns the width of the arrow head, in Java2D units. The default value is 3.0. å public void setArrowWidth(double width); [1.0.3] Sets the width of the arrow head, in Java2D units. To control the stroke used to draw the arrow: å public Stroke getArrowStroke(); [1.0.3] Returns the stroke used to draw the arrow. The default is BasicStroke(1.0f). å public void setArrowStroke(Stroke stroke); [1.0.3] Sets the stroke used to draw the arrow. To control the color of the arrow: å public Paint getArrowPaint(); [1.0.3] Returns the paint used to draw/fill the arrow. The default is Color.black. å public void setArrowPaint(Paint paint); [1.0.3] Sets the paint used to draw/fill the arrow. 23.5.4 Other Methods The following method is called by JFreeChart as required: å public void draw(Graphics2D g2, CategoryPlot plot, Rectangle2D dataArea, CategoryAxis domainAxis, ValueAxis rangeAxis); [1.0.3] Draws the annotation. This method is typically called by JFreeChart, not user code. 160 CHAPTER 23. PACKAGE: ORG.JFREE.CHART.ANNOTATIONS 23.5.5 161 Equals, Cloning and Serialization This class overrides the equals() method: å public boolean equals(Object obj); [1.0.3] Tests this annotation for equality with an arbitrary object. Instances of this class are Cloneable and Serializable. 23.5.6 Notes Some points to note: • this class is a subclass of CategoryTextAnnotation; • a demo (CategoryPointerAnnotationDemo1.java) is included in the JFreeChart demo collection. See Also CategoryTextAnnotation. 23.6 CategoryTextAnnotation 23.6.1 Overview A CategoryAnnotation that can be used to display an item of text at some location (defined by a (category, value) pair) on a CategoryPlot. This class extends TextAnnotation. 23.6.2 Constructor To create a new annotation: å public CategoryTextAnnotation(String text, Comparable category, double value); Creates a new annotation that displays the specified text at a point corresponding to the specified value for the given category. 23.6.3 General Attributes This class inherits a number of attributes from TextAnnotation, and adds a few of its own. The text for the annotation is drawn relative to an alignment point that is defined on the chart using the following attributes: • the category; • the category anchor point; • the data value. To control the category: å public Comparable getCategory(); Returns the category key for this annotation. å public void setCategory(Comparable category); Sets the category key for this annotation. If category is null, this method throws an IllegalArgumentException. To control the category anchor point: å public CategoryAnchor getCategoryAnchor(); Returns the category anchor point, which helps to determine the position of the alignment point for the annotation. The default value is CategoryAnchor.MIDDLE. CHAPTER 23. PACKAGE: ORG.JFREE.CHART.ANNOTATIONS 162 å public void setCategoryAnchor(CategoryAnchor anchor); Sets the category anchor point, which is used to determine the position of the alignment point for the annotation. If anchor is null, this method throws an IllegalArgumentException. To control the value: å public double getValue(); Returns the value that determines the alignment point for the annotation. å public void setValue(double value); Sets the value that determines the alignment point for the annotation. 23.6.4 Other Methods To draw the annotation: å public void draw(Graphics2D g2, CategoryPlot plot, Rectangle2D dataArea, CategoryAxis domainAxis, ValueAxis rangeAxis); Draws the annotation. This method is called by JFreeChart, you shouldn’t need to call it directly. 23.6.5 Equals, Cloning and Serialization This class overrides the equals() method: å public boolean equals(Object obj); Tests this annotation for equality with an arbitrary object. Instances of this class are Cloneable and Serializable. 23.6.6 Notes Some points to note: • there is no event notification for annotations, so automatic chart redrawing does not occur when an annotation is updated; • CategoryTextAnnotation is a subclass of TextAnnotation; • a demo (SurveyResultsDemo1.java) is included in the JFreeChart demo collection. See Also CategoryAnnotation. 23.7 TextAnnotation 23.7.1 Overview The base class for a text annotation. The class includes font, paint, alignment and rotation settings. Subclasses will add location information to the content represented by this class. At present, the only subclass in JFreeChart is CategoryTextAnnotation. 23.7.2 Constructor The constructor for this class is protected since you won’t create an instance of this class directly (use a subclass): å protected TextAnnotation(String text); Creates a new text annotation that displays the given text. Default values for the remaining attributes are: CHAPTER 23. PACKAGE: ORG.JFREE.CHART.ANNOTATIONS • • • • • 23.7.3 163 font = new Font("SansSerif", Font.PLAIN, 10); paint = Color.black; textAnchor = TextAnchor.CENTER; rotationAnchor = TextAnchor.CENTER; rotationAngle = 0.0; General Attributes To control the text displayed by the annotation: å public String getText(); Returns the text displayed by the annotation (never null). å public void setText(String text); Sets the text displayed by the annotation (null is not permitted). To control the font: å public Font getFont(); Returns the font used to display the text. This method never returns null. å public void setFont(Font font); Sets the font used to display the text. If font is null, this method throws an IllegalArgumentException. To control the text color: å public Paint getPaint(); Returns the paint used to draw the text (never null). å public void setPaint(Paint paint); Sets the paint used to draw the text. If paint is null, this method throws an IllegalArgumentException. To control the anchor point that will be aligned to some point (defined by the subclass): å public TextAnchor getTextAnchor(); Returns the anchor point for the text, this will be aligned to a specified point on the chart (that is defined by the subclass). å public void setTextAnchor(TextAnchor anchor); Sets the anchor point for the text. This will be aligned to some point on the chart (that is specified by the subclass). To control the rotation anchor point: å public TextAnchor getRotationAnchor(); Returns the text anchor point about which any rotation is performed. å public void setRotationAnchor(TextAnchor anchor); Sets the rotation anchor point for the text. To control the rotation angle: å public double getRotationAngle(); Returns the rotation angle (in radians). å public void setRotationAngle(double angle); Sets the rotation angle for the text (in radians). The text is rotated about the rotation anchor point (see the getRotationAnchor() method). 23.7.4 Equals, Cloning and Serialization This class overrides the equals() method: å public boolean equals(Object obj); Tests this annotation for equality with an arbitrary object. This method returns true if and only if: • obj is not null; • obj is an instance of TextAnnotation; • obj has the same attributes as this annotation. Instances of this class are Serializable, but not Cloneable. CHAPTER 23. PACKAGE: ORG.JFREE.CHART.ANNOTATIONS 23.7.5 164 Notes Some points to note: • the XYTextAnnotation class is NOT a subclass of this class. See Also CategoryTextAnnotation. 23.8 XYAnnotation 23.8.1 Overview An XYAnnotation is a small text or graphical item that can be added to an arbitrary location on a chart. This interface defines the drawing method that must be supported by annotations that are to be added to an XYPlot (or an XYItemRenderer). This interface is implemented by: • XYBoxAnnotation; • XYDrawableAnnotation; • XYImageAnnotation; • XYLineAnnotation; • XYPointerAnnotation; • XYPolygonAnnotation; • XYShapeAnnotation; • XYTextAnnotation; You can, of course, provide your own implementations of the interface. 23.8.2 Interface This interface defines one method for drawing the annotation: å public void draw(Graphics2D g2, Rectangle2D dataArea, XYPlot plot, ValueAxis domainAxis, ValueAxis rangeAxis); Draws the annotation. The dataArea is the space defined by (within) the two axes. If the annotation defines its location in terms of data values, the axes can be used to convert these values to Java2D coordinates. 23.8.3 Notes Some points to note: • there is no event notification mechanism (yet) for annotations. If you modify an annotation, you will need to manually trigger a redraw of the chart (for example, by calling chart.setNotify(true)); • a couple of demos (AnnotationDemo1.java and AnnotationDemo2.java) are included in the JFreeChart demo collection. See Also AbstractXYAnnotation. CHAPTER 23. PACKAGE: ORG.JFREE.CHART.ANNOTATIONS 23.9 XYBoxAnnotation 23.9.1 Overview 165 An XYAnnotation that highlights a rectangular region within the data area of an XYPlot—see figure 23.2 for an example. XYBoxAnnotation is a subclass of AbstractXYAnnotation. Breakdowns Hours of Operation 200,000 150,000 100,000 Jul.05 Aug.05 Jun.05 Apr.05 May.05 Jan.05 Feb.05 Mar.05 Dec.04 Oct.04 Nov.04 Sep.04 Jul.04 Aug.04 Jun.04 Apr.04 May.04 Mar.04 Jan.04 Feb.04 Dec.03 0 Nov.03 50,000 Production Date Old New Figure 23.2: An XYBoxAnnotation (see XYBoxAnnotationDemo1.java) 23.9.2 Constructors To create a new annotation: å public XYBoxAnnotation(double x0, double y0, double x1, double y1); Creates a new annotation covering the rectangular region from (x0, y0) to (x1, y1). The box annotation will be drawn as a black outline using a 1 unit wide plain stroke (BasicStroke(1.0f)). å public XYBoxAnnotation(double x0, double y0, double x1, double y1, Stroke stroke, Paint outlinePaint); Creates a new annotation covering the rectangular region from (x0, y0) to (x1, y1). The box annotation will be drawn as an outline using the specified stroke and paint. If either stroke or paint is null, the annotation will not be visible. å public XYBoxAnnotation(double x0, double y0, double x1, double y1, Stroke stroke, Paint outlinePaint, Paint fillPaint); Creates a new annotation covering the rectangular region from (x0, y0) to (x1, y1). The box annotation will be drawn and filled using the specified stroke, outline paint and fill paint. If stroke or outlinePaint is null, no outline will be drawn. If fillPaint is null, the box will not be filled. 23.9.3 Methods JFreeChart calls the following method to draw the annotation: å public void draw(Graphics2D g2, XYPlot plot, Rectangle2D dataArea, ValueAxis domainAxis, ValueAxis rangeAxis, int rendererIndex, PlotRenderingInfo info); Draws the annotation within the specified area of the plot. This method is called by JFreeChart, you won’t normally call it directly from your own code. 23.9.4 Equals, Cloning and Serialization This class overrides the equals(Object) method: å public boolean equals(Object obj); Tests this annotation for equality with an arbitrary object. The method returns true if and only if: CHAPTER 23. PACKAGE: ORG.JFREE.CHART.ANNOTATIONS 166 • obj is not null; • obj is an instance of XYBoxAnnotation; • both annotations have the same attributes. Instances of this class are Cloneable (PublicCloneable) and Serializable. 23.9.5 Notes Some points to note: • the annotation will only be visible if it falls within the current bounds of the plot’s axes; • you can define a tool tip and/or URL for the annotation, using methods inherited from AbstractXYAnnotation; • you can use this annotation with an XYPlot that uses a DateAxis—just specify the relevant coordinates in terms of milliseconds since 1-Jan-1970; • a demo (XYBoxAnnotationDemo1.java) is included in the JFreeChart demo collection. See Also XYAnnotation. 23.10 XYDrawableAnnotation 23.10.1 Overview An XYAnnotation that draws an object at some (x, y) location on an XYPlot. The object can be any implementation of the Drawable interface (defined in the JCommon class library). Figure 23.3 shows a chart with such an annotation—the small red circle containing the blue crosshair is an XYDrawableAnnotation. Marker Demo 1 210 Original Close (02:00) Close Date (02:15) 205 200 Bid Start Price 195 190 185 Y 180 Target Price 175 Supplier 1 Supplier 2 170 165 160 Best Bid 155 150 145 01:20 01:30 01:40 01:50 02:00 02:10 02:20 02:30 Time Figure 23.3: An XYDrawableAnnotation (see MarkerDemo1.java) 23.10.2 Constructors To create a new annotation: å public XYDrawableAnnotation(double x, double y, double width, double height, Drawable drawable); Creates a new annotation that will be drawn within the specified rectangular area (in data space). CHAPTER 23. PACKAGE: ORG.JFREE.CHART.ANNOTATIONS 23.10.3 167 Notes Some points to note: • a demo (MarkerDemo1.java) is included in the JFreeChart demo collection. See Also XYAnnotation. 23.11 XYImageAnnotation 23.11.1 Overview An annotation that allows an image to be displayed at an arbitrary (x, y) location on an XYPlot. To add an image annotation to a plot, use code similar to the following: XYPlot plot = (XYPlot) chart.getPlot(); Image image = ... // fetch a small image from somewhere XYImageAnnotation a1 = new XYImageAnnotation(5.0, 2.0, image); plot.addAnnotation(a1); You need to ensure that the image is fully loaded before you supply it to the XYImageAnnotation constructor, otherwise it may not appear the first time your chart is drawn (see section 20.4). 23.11.2 Constructor The following constructors are defined: å public XYImageAnnotation(double x, double y, Image image); Equivalent to XYImageAnnotation(x, y, image, RectangleAnchor.CENTER)—see the next construc- tor. å public XYImageAnnotation(double x, double y, Image image, RectangleAnchor anchor); [1.0.4] Creates an annotation that will display the specified image at the given (x, y) location. The coordinates are specified in data-space (that is, the axis coordinates of the chart) and the image will be aligned to this point according to the anchor setting. If image or anchor is null, this method throws an IllegalArgumentException. 23.11.3 Attributes All the attributes for this class are specified via the constructor and cannot be updated: å public double getX(); [1.0.4] Returns the x-coordinate for the anchor point to which the image will be aligned. å public double getY(); [1.0.4] Returns the y-coordinate for the anchor point to which the image will be aligned. å public Image getImage(); [1.0.4] Returns the image to be displayed by this renderer. å public RectangleAnchor getImageAnchor(); [1.0.4] Returns the image anchor, which will be aligned to the (x, y) location on the chart when the image annotation is displayed. 23.11.4 Drawing Once an annotation has been added to a plot, the plot will take care of drawing it every time the chart is redrawn. The following method is used: å public void draw(Graphics2D g2, XYPlot plot, Rectangle2D dataArea, ValueAxis domainAxis, ValueAxis rangeAxis); Draws the annotation within the specified dataArea. This method is called by the plot, you shouldn’t need to call it yourself. CHAPTER 23. PACKAGE: ORG.JFREE.CHART.ANNOTATIONS 23.11.5 168 Equals, Cloning and Serialization This class overrides the equals() method specified in Object: å public boolean equals(Object object); Tests this annotation for equality with an arbitrary object. This method will return true if object is an instance of XYImageAnnotation with the same coordinates and image as this annotation. The annotation can be cloned: å public Object clone() throws CloneNotSupportedException; Returns a clone of the annotation. At present, serialization is not supported because images are not automatically serializable. Hopefully this will be fixed in a future release by writing our own image serialization code (for instance, by writing the image data to PNG format, then decoding it again upon deserialization). 23.11.6 Notes Some points to note: • the PlotOrientationDemo1 application (source code is included in the JFreeChart Demo distribution) includes an image annotation for each sub-chart. See Also XYAnnotation. 23.12 XYLineAnnotation 23.12.1 Overview A simple annotation that draws a line between a starting point (x0, y0) and an ending point (x1, y1) on an XYPlot. To add a line annotation to a plot, use code similar to the following: XYPlot plot = (XYPlot) chart.getPlot(); XYLineAnnotation a1 = new XYLineAnnotation(1.0, 2.0, 3.0, 4.0, new BasicStroke(1.5f), Color.red); plot.addAnnotation(a1); 23.12.2 Constructors To create a new annotation: å public XYLineAnnotation(double x1, double y1, double x2, double y2); Creates an annotation that will draw a line from (x1, y1) to (x2, y2) on the chart. By default, the line is black and uses a stroke width of 1.0. å public XYLineAnnotation(double x1, double y1, double x2, double y2, Stroke stroke, Paint paint); Creates an annotation that will draw a line from (x1, y1) to (x2, y2) on the chart. The line is drawn using the specified stroke and paint. 23.12.3 Drawing Once an annotation has been added to a plot, the plot will take care of drawing it every time the chart is redrawn. The following method is used: å public void draw(Graphics2D g2, XYPlot plot, Rectangle2D dataArea, ValueAxis domainAxis, ValueAxis rangeAxis); Draws the annotation within the specified dataArea. This method is called by the plot, you shouldn’t need to call it yourself. CHAPTER 23. PACKAGE: ORG.JFREE.CHART.ANNOTATIONS 23.12.4 169 Equals, Cloning and Serialization This class overrides the equals() method specified in Object: å public boolean equals(Object object); Tests this annotation for equality with an arbitrary object. This method will return true if object is an instance of XYLineAnnotation with the same coordinates, stroke and paint settings as this annotation. The annotation can be cloned: å public Object clone() throws CloneNotSupportedException; Returns a clone of the annotation. This class is Serializable. 23.12.5 Notes Some points to note: • if you want to use a line annotation on a time series chart, the x-coordinates of the annotation should be specified in “milliseconds since 1-Jan-1970, GMT”. See Also XYAnnotation. 23.13 XYPointerAnnotation 23.13.1 Overview An annotation that displays an arrow pointing towards a specific (x, y) location on an XYPlot (see figure 23.4). The arrow can have a label at one end. Figure 23.4: An XYPointerAnnotation example 23.13.2 Usage To add a pointer annotation to an XYPlot: XYPlot plot = (XYPlot) chart.getPlot(); XYPointerAnnotation pointer = new XYPointerAnnotation( "Best Bid", millis, 163.0, 3.0 * Math.PI / 4.0 ); pointer.setTipRadius(10.0); pointer.setBaseRadius(35.0); pointer.setFont(new Font("SansSerif", Font.PLAIN, 9)); pointer.setPaint(Color.blue); pointer.setTextAnchor(TextAnchor.HALF ASCENT RIGHT); plot.addAnnotation(pointer); CHAPTER 23. PACKAGE: ORG.JFREE.CHART.ANNOTATIONS 23.13.3 Constructor To create a new pointer annotation: å public XYPointerAnnotation(String label, double x, double y, double angle); Creates a new pointer annotation to highlight the specified (x, y) location on the chart. 23.13.4 General Attributes To control the angle of the arrow: å public double getAngle(); Returns the angle of the arrow (in radians). å public void setAngle(double angle); Sets the angle of the arrow (in radians). If you imagine a clockface, an angle of 0 results in an arrow pointing from 3 o’clock to the center of the clock face, with positive values proceeding from 3 o’clock in a clockwise direction. To control the distance between the (x, y) location and the tip of the arrow: å public double getTipRadius(); Returns the radius of the circle that determines how far from the (x, y) location the tip of the arrow is. å public void setTipRadius(double radius); Sets the radius of the circle that determines the end point of the arrow. To control the distance between the (x, y) location and the base of the arrow: å public double getBaseRadius(); Returns the radius of the circle that determines how far from the (x, y) location to the base of the arrow. å public void setBaseRadius(double radius); Sets the radius of the circle that determines the base point for the arrow. To control the offset between the base of the arrow and the label anchor point: å public double getLabelOffset(); Returns the label offset (in Java2D units). å public void setLabelOffset(double offset); Sets the label offset from the base of the arrow (in Java2D units). To control the length of the arrow head: å public double getArrowLength(); Returns the length of the arrow head (in Java2D units). å public void setArrowLength(double length); Sets the length of the arrow head (in Java2D units). To control the width of the arrow head: å public double getArrowWidth(); Returns the width of the arrow head in Java2D units. å public void setArrowWidth(double width); Sets the width of the arrow head in Java2D units. To control the Stroke used to draw the arrow: å public Stroke getArrowStroke(); Returns the stroke used to draw the arrow (never null). å public void setArrowStroke(Stroke stroke); Sets the stroke used to draw the arrow (null not permitted). To control the Paint used to draw the arrow: å public Paint getArrowPaint(); Returns the paint used to draw the arrow (never null). å public void setArrowPaint(Paint paint); Sets the paint used to draw the arrow (null not permitted). 170 CHAPTER 23. PACKAGE: ORG.JFREE.CHART.ANNOTATIONS 23.13.5 171 Other Methods To draw the annotation (this method is called by the plot, you shouldn’t need to call it directly yourself): å public void draw(Graphics2D g2, XYPlot plot, Rectangle2D dataArea, ValueAxis domainAxis, ValueAxis rangeAxis); Draws the annotation. 23.13.6 Notes Some points to note: • annotations don’t current have a change notification mechanism, so charts do not automatically refresh when an annotation is modified; • a demo (XYPointerAnnotationDemo1.java) is included in the JFreeChart demo collection. See Also XYAnnotation. 23.14 XYPolygonAnnotation 23.14.1 Overview A simple annotation that draws a polygon on an XYPlot. The polygon’s coordinates are specified in data space (that is, the coordinate system defined by the plot’s axes). See figure 23.5 for an example. XYPolygonAnnotationDemo1 9.0 8.5 8.0 7.5 7.0 6.5 6.0 Y 5.5 5.0 4.5 4.0 3.5 3.0 2.5 2.0 1.5 1.0 1.7 1.8 1.9 2.0 2.1 2.2 2.3 2.4 2.5 2.6 2.7 2.8 2.9 3.0 3.1 3.2 X Series 1 Series 2 Figure 23.5: An XYPolygonAnnotation (see XYPolygonAnnotationDemo1.java) 23.14.2 Usage A demo is provided by XYPolygonAnnotationDemo1.java. 23.14.3 Constructors There are several constructors for this class. For each one, the first argument is an array containing the (x, y) coordinates of the polygon’s vertices. These coordinates should be specified using the coordinate system defined by the chart’s axes. CHAPTER 23. PACKAGE: ORG.JFREE.CHART.ANNOTATIONS 172 å public XYPolygonAnnotation(double[] polygon); Creates a new annotation that draws a polygon with the supplied coordinates. The polygon will be drawn with a black outline, one Java2D unit wide. The polygon is not filled. å public XYPolygonAnnotation(double[] polygon, Stroke stroke, Paint outlinePaint) Creates a new annotation that draws the specified polygon with the given stroke and outline paint. The polygon is not filled. å public XYPolygonAnnotation(double[] polygon, Stroke stroke, Paint outlinePaint, Paint fillPaint); Creates a new annotation that draws a polygon with the specified vertices, using the supplied stroke, outlinePaint and fillPaint. For all constructors, the polygon array must contain an even number of items, since it contains a sequence of (x, y) coordinates. 23.14.4 Methods To get the coordinates of the polygon: å public double[] getPolygonCoordinates(); [1.0.2] Returns the coordinates of the polygon’s vertices. To get the outline attributes for the annotation: å public Stroke getOutlineStroke(); [1.0.2] Returns the stroke used to draw the outline of the polygon. If this is null, no outline is drawn. å public Paint getOutlinePaint(); [1.0.2] Returns the paint used to draw the outline of the polygon. If this is null, no outline is drawn. To get the fill paint for the annotation: å public Paint getFillPaint(); [1.0.2] Returns the paint used to fill the polygon. If this is null, the polygon is not filled. The annotation is drawn (by the plot) using this method (which you shouldn’t need to call yourself): å public void draw(Graphics2D g2, XYPlot plot, Rectangle2D dataArea, ValueAxis domainAxis, ValueAxis rangeAxis, int rendererIndex, PlotRenderingInfo info); Draws the annotation within the specified dataArea. 23.14.5 Equals, Cloning and Serialization To test this class for equality with an arbitrary object: å public boolean equals(Object obj); Returns true if this annotation is equal to the specified obj. This method will return true if and only if: • obj is not null; • obj is an instance of XYPolygonAnnotation; • obj defines a polygon with the same vertices (in the same order) as this annotation; • obj has the same stroke, outlinePaint and fillPaint as this annotation; This class is cloneable and implements the PublicCloneable interface. This class is also serializable. 23.14.6 Notes Some points to note: • the polygon annotation will only be visible on a chart if it falls within the current axis bounds; • for a demo, see XYPolygonAnnotationDemo1.java. CHAPTER 23. PACKAGE: ORG.JFREE.CHART.ANNOTATIONS 173 See Also XYAnnotation. 23.15 XYShapeAnnotation 23.15.1 Overview A simple annotation that draws a shape on an XYPlot. The shape’s coordinates are specified in “data space” (that is, the coordinate system defined by the plot’s axes). 23.15.2 Constructors This class has several constructors. The attributes of the annotation are specified via the constructor and cannot be modified subsequently: å public XYShapeAnnotation(Shape shape); Creates a new annotation that will draw the given shape with a black outline. å public XYShapeAnnotation(Shape shape, Stroke stroke, Paint outlinePaint); Creates a new annotation that will draw the given shape with the specified stroke and outline paint. å public XYShapeAnnotation(Shape shape, Stroke stroke, Paint outlinePaint, Paint fillPaint); Creates a new annotation that will draw the given shape with the specified stroke, outline paint and fill paint. If either the stroke or outlinePaint is null, no outline is drawn. If the fillPaint is null, the shape is not filled. 23.15.3 Methods There are no methods for setting the attributes of the annotation—these are set in the constructor and cannot be modified. The following method is called by the plot to draw the annotation, normally you won’t need to call it directly: å public void draw(Graphics2D g2, XYPlot plot, Rectangle2D dataArea, ValueAxis domainAxis, ValueAxis rangeAxis, int rendererIndex, PlotRenderingInfo info); Draws the annotation. 23.15.4 Equals, Cloning and Serialization To test this annotation for equality with an arbitrary object: å public boolean equals(Object obj); Tests the annotation for equality with obj. This method returns true if and only if: • obj is not null; • obj is an instance of XYShapeAnnotation; • obj has the same attributes as this annotation. This class is Cloneable2 and Serializable. 23.15.5 Notes Before drawing, the shape must be transformed to Java2D coordinates. The transformation code assumes linear scales on the axes, so this type of annotation may not work well with logarithmic axes. 2 Technically, this probably isn’t necessary since instances of this class are immutable. CHAPTER 23. PACKAGE: ORG.JFREE.CHART.ANNOTATIONS 174 See Also XYAnnotation. 23.16 XYTextAnnotation 23.16.1 Overview A text annotation that can be added to an XYPlot. You can use this class to add a small text label at some (x, y) location on a chart. This class is a subclass of AbstractXYAnnotation. 23.16.2 Usage To add a simple annotation to an XYPlot: XYPlot plot = (XYPlot) chart.getPlot(); XYAnnotation annotation = new XYTextAnnotation("Hello World!", 10.0, 25.0); plot.addAnnotation(annotation); The text will be centered on the specified (x, y) location. 23.16.3 Constructors To create a new annotation: å public XYTextAnnotation(String text, double x, double y); Creates a new text annotation for display at the specified (x, y) location (in data space). An exception is thrown if the text argument is null. 23.16.4 General Attributes To control the text for the annotation: å public String getText(); Returns the text displayed by the annotation (never null). The initial value is specified in the constructor. å public void setText(String text); Sets the text for the annotation (no event is generated). If text is null, this method throws an IllegalArgumentException. To control the location on the chart that the annotation will be aligned to: å public double getX(); Returns the x-coordinate (in data space). å public void setX(double x); Sets the x-coordinate (in data space) for the annotation. No event is generated. å public double getY(); Returns the y-coordinate (in data space). å public void setY(double y); Sets the y-coordinate (in data space) for the annotation. No event is generated. To control the font used to display the text annotation: å public Font getFont(); Returns the font used to display the text annotation (never null). Font("SansSerif", Font.PLAIN, 10). The default value is å public void setFont(Font font); Sets the font used to display the text annotation (no event is generated). If font is null, this method throws an IllegalArgumentException. To control the paint used to display the text annotation: CHAPTER 23. PACKAGE: ORG.JFREE.CHART.ANNOTATIONS 175 å public Paint getPaint(); Returns the paint used to display the text (never null). The default value is Color.black. å public void setPaint(Paint paint); Sets the paint used to display the text annotation (no event is generated). If paint is null, this method throws an IllegalArgumentException. The text anchor defines a point on the text’s framing rectangle that will be aligned to the (x, y) location on the chart: å public TextAnchor getTextAnchor(); Returns the text anchor (never null). This is a point on the framing rectangle for the text that is aligned to the ( x, y) location on the chart. The default value is TextAnchor.CENTER (in other words, the text annotation will be centered over the (x, y) location). å public void setTextAnchor(TextAnchor anchor) Sets the text anchor (no event is generated). If anchor is null, this method throws an IllegalArgumentException. The rotation anchor defines a point on the text’s framing rectangle about which the text will be rotated: å public TextAnchor getRotationAnchor(); Returns the rotation anchor (never null). The default value is TextAnchor.CENTER. å public void setRotationAnchor(TextAnchor anchor); Sets the rotation anchor (no event is generated). If anchor is null, this method throws an IllegalArgumentException. To control the rotation angle: å public double getRotationAngle(); Returns the rotation angle, which is measured in radians (clockwise). The default value is 0.0. å public void setRotationAngle(double angle); Sets the rotation angle in radians (no event is generated). 23.16.5 Other Methods The following method is used to draw the annotation. It is called by the plot, you won’t normally need to call this method yourself: å public void draw(Graphics2D g2, XYPlot plot, Rectangle2D dataArea, ValueAxis domainAxis, ValueAxis rangeAxis); Draws the annotation. 23.16.6 Equals, Cloning and Serialization This class overrides the equals() method: å public boolean equals(Object obj); Tests this annotation for equality with an arbitrary object. Instances of this class are Cloneable and Serializable. 23.16.7 Notes Some points to note: • annotations added directly to the plot are positioned relative to the primary axes. You can also add the annotation to an XYItemRenderer, in which case the annotation is drawn relative to the axes used by that renderer; • a demo (AnnotationDemo1.java) is included in the JFreeChart demo collection; • the XYPointerAnnotation subclass can be used to display a label with an arrow pointing to some (x, y) value. CHAPTER 23. PACKAGE: ORG.JFREE.CHART.ANNOTATIONS See Also XYAnnotation. 176 Chapter 24 Package: org.jfree.chart.axis 24.1 Overview This package contains all the axis classes plus a few assorted support classes and interfaces: • the CategoryPlot and XYPlot classes maintain references to two axes (by default), which we refer to as the domain axis and range axis. These terms are based on the idea that these plots are providing a visual representation of a function that maps a set of domain values onto a set of range values. For most purposes, you can think of the domain axis as the X-axis and the range axis as the Y-axis, but we prefer the more generic terms. • the default settings provided by the axis classes should work well for a wide range of applications. However, there are many ways to customise the behaviour of the axes by modifying attributes via the JFreeChart API. Be sure to read through the API documentation to become familiar with the options that are available. • a powerful feature of JFreeChart is the support for multiple domain and range axes on a single plot. If you plan to make use of this feature, you should refer to section 13 for more information. The axis classes are Cloneable and Serializable. 24.2 Axis 24.2.1 Overview An abstract base class representing an axis. Some subclasses of Plot, including CategoryPlot and XYPlot, will use axes to display data. Figure 24.1 illustrates the axis class hierarchy. 24.2.2 Constructors The constructors for this class are protected, you cannot create an instance of this class directly— you must use a subclass. 24.2.3 Attributes The attributes maintained by the Axis class are listed in Table 24.1. There are methods to read and update most of these attributes. In most cases, updating an axis attribute will result in an AxisChangeEvent being sent to all (or any) registered listeners. The default values used to initialise the axis attributes are listed in Table 24.2. 177 CHAPTER 24. PACKAGE: ORG.JFREE.CHART.AXIS 178 Axis ValueAxis CategoryAxis DateAxis NumberAxis SubCategoryAxis CategoryAxis3D NumberAxis3D SymbolAxis LogarithmicAxis Figure 24.1: Axis classes Attribute: Description: plot visible label labelFont labelPaint labelInsets labelAngle axisLineVisible axisLinePaint axisLineStroke tickLabelsVisible tickLabelFont tickLabelPaint tickLabelInsets tickMarksVisible tickMarkStroke tickMarkPaint tickMarkInsideLength The plot to which the axis belongs. A flag that controls whether or not the axis is visible. The axis label. The font for the axis label. The foreground colour for the axis label. The space to leave around the outside of the axis label. The angle of rotation for the axis label. A flag that controls whether or not a line is drawn for the axis. The paint used to draw the axis line if it is visible. The stroke used to draw the axis line if it is visible. A flag controlling the visibility of tick labels. The font for the tick labels. The color for the tick labels. The space to leave around the outside of the tick labels. A flag controlling the visibility of tick marks. The stroke used to draw the tick marks. The paint used to draw the tick marks. The amount by which the tick marks extend into the plot area (in Java2D units). The amount by which the tick marks extend outside the plot area (in Java2D units). tickMarkOutsideLength Table 24.1: Attributes for the Axis class 24.2.4 Usage To change the attributes of an axis, you must first obtain a reference to the axis. Usually, you will obtain the reference from the plot that uses the axis. For example: CategoryPlot plot = (CategoryPlot) chart.getPlot(); CategoryAxis axis = plot.getDomainAxis(); // change axis attributes here... Notice that the getDomainAxis() method returns a particular subclass of Axis (CategoryAxis in this case). That’s okay, because the subclass inherits all the attributes defined by Axis anyway. 24.2.5 The Axis Label The axis label typically describes what an axis is measuring (for example, “Sales in US$”). To access the axis label: å public String getLabel(); Returns the axis label (possibly null). CHAPTER 24. PACKAGE: ORG.JFREE.CHART.AXIS Name: DEFAULT DEFAULT DEFAULT DEFAULT DEFAULT DEFAULT DEFAULT Value: AXIS AXIS AXIS TICK TICK TICK TICK LABEL FONT LABEL PAINT LABEL INSETS LABEL FONT LABEL PAINT LABEL INSETS STROKE new Font("SansSerif", Font.PLAIN, 14); Color.black; new Insets(2, 2, 2, 2); new Font("SansSerif", Font.PLAIN, 10); Color.black; new Insets(2, 1, 2, 1); new BasicStroke(1); Table 24.2: Axis class default attribute values å public void setLabel(String label); Sets the axis label and sends an AxisChangeEvent to all registered listeners. If you set the label to null, no label is displayed for the axis. To access the font used to display the axis label: å public Font getLabelFont(); Returns the Font used to display the axis label. å public void setLabelFont(Font font); Sets the Font used to display the axis label and sends an AxisChangeEvent to all registered listeners. To access the paint used to display the axis label: å public Paint getLabelPaint(); Returns the paint used to display the axis label. å public void setLabelPaint(Paint paint); Sets the paint used to display the axis label and sends an AxisChangeEvent to all registered listeners. To control the rotation angle for the axis label: å public double getLabelAngle(); Returns the angle of rotation (in radians) for the axis label. The default value is 0.0. å public void setLabelAngle(double angle); Sets the angle of rotation for the axis label and sends an AxisChangeEvent to all registered listeners. The angle is specified in radians. 24.2.6 The Axis Line The axis draws a line along the edge of the plot’s data area: å public boolean isAxisLineVisible(); Returns true if the axis draws a line along the edge of the data area, and false otherwise. The default value is true. å public void setAxisLineVisible(boolean visible); Sets the flag that controls whether or not a line is drawn along the edge of the data area by the axis, and sends an AxisChangeEvent to all registered listeners. The stroke used to draw the axis line (if it is visible) is controlled by the following methods: å public Stroke getAxisLineStroke(); Returns the stroke used to draw the axis line (never null). The default value is BasicStroke(1.0f). å public void setAxisLineStroke(Stroke stroke); Sets the stroke used to draw the axis line and sends an AxisChangeEvent to all registered listeners. If stroke is null, this method throws an IllegalArgumentException. The paint used to draw the axis line (if it is visible) is controlled by the following methods: 179 CHAPTER 24. PACKAGE: ORG.JFREE.CHART.AXIS 180 å public Paint getAxisLinePaint(); Returns the paint used to draw the axis line (never null). The default value is Color.GRAY. å public void setAxisLinePaint(Paint paint); Sets the paint used to draw the axis line and sends an AxisChangeEvent to all registered listeners. If paint is null, this method throws an IllegalArgumentException. Note that the CategoryPlot and XYPlot classes also draw an outline around the data area. The outline is drawn before (under) the axis line(s). The plot outline stroke and paint are defined in the Plot class. 24.2.7 Tick Marks and Labels It is common for axes to have small marks at regular intervals to show the scale of values displayed by the axis. In JFreeChart, we refer to these marks as “tick marks”, and the labels corresponding to these marks as “tick labels”. This class defines the basic attributes that control the appearance of tick marks and labels, but leaves the actual generation and formatting up to specific subclasses. To control the visibility of the tick marks for an axis: å public boolean isTickMarksVisible(); Returns the flag that controls whether or not the tick marks are visible. The default value is true. å public void setTickMarksVisible(boolean flag); Sets the flag that controls whether or not tick marks are visible, then sends an AxisChangeEvent to all registered listeners. To control the stroke used to draw the tick marks: å public Stroke getTickMarkStroke(); Returns the stroke used to draw the tick marks (never null). The default value is BasicStroke(1.0f). å public void setTickMarkStroke(Stroke stroke); Sets the stroke used to draw the tick marks (null not permitted) then sends an AxisChangeEvent to all registered listeners. To control the paint used to draw the tick marks: å public Paint getTickMarkPaint(); Returns the paint used to draw the tick marks (never null). The default value is Color.black. å public void setTickMarkPaint(Paint paint); Sets the paint used to draw the tick marks (null not permitted) then sends an AxisChangeEvent to all registered listeners. To control the length of the tick marks, you can set the “inside” and “outside” lengths: å public float getTickMarkInsideLength(); Returns the length of the tick mark on the inside of the data area, in Java2D units. The default value is 0.0f. å public void setTickMarkInsideLength(float length); Sets the length of the tick mark on the inside of the data area, in Java2D units, and sends an AxisChangeEvent to all registered listeners. å public float getTickMarkOutsideLength(); Returns the length of the tick mark extension into the plot area, in Java2D units. The default value is 2.0f. å public void setTickMarkOutsideLength(float length); Sets the length of the tick mark on the outside of the data area, in Java2D units, and sends an AxisChangeEvent to all registered listeners. To control the visibility of the tick labels for an axis: CHAPTER 24. PACKAGE: ORG.JFREE.CHART.AXIS 181 å public boolean isTickLabelsVisible(); Returns the flag that controls whether or not the tick labels are visible. The default value is true. å public void setTickLabelsVisible(boolean flag); Sets the flag that controls whether or not the tick labels are visible and sends an AxisChangeEvent to all registered listeners. To control the font used to draw the tick labels: å public Font getTickLabelFont(); Returns the tick label font (never null). The default value is Font("SansSerif", Font.PLAIN, 10). å public void setTickLabelFont(Font font); Sets the tick label font and sends an AxisChangeEvent to all registered listeners. If font is null, this method throws an IllegalArgumentException. To control the paint used to draw the tick labels: å public Paint getTickLabelPaint(); Returns the tick label paint. The default value is Color.black. å public void setTickLabelPaint(Paint paint); Sets the tick label paint and sends an AxisChangeEvent to all registered listeners. If paint is null, this method throws an IllegalArgumentException. 24.2.8 The Fixed Dimension It is possible to specify a fixed “dimension” for an axis. This is an ugly hack to help align subplots in the combined plots. For a vertical axis, the fixed dimension applies to the width of the axis and for a horizontal axis the fixed dimension applies to the height of the axis. å public double getFixedDimension(); Returns the fixed dimension for the axis, in Java2D units. å public void setFixedDimension(double dimension); Sets the fixed dimension for the axis, in Java2D units. During layout, if the axis width or height (depending on the orientation) is less than this value, it is increased to match dimension. The value defaults to 0.0 which means it is ignored. Note that the CategoryAxis class completely ignores this setting. 24.2.9 Other Methods All axes are drawn by the plot that owns the axis, using this method: å public abstract AxisState draw(Graphics2D g2, double cursor, Rectangle2D plotArea, Rectangle2D dataArea, RectangleEdge edge); Draws the axis along the specified edge of the data area. Given that there may be more than one axis on a particular edge, the cursor value specifies the distance from the edge that the axis should be drawn (to take account of other axes that have already been drawn). An AxisState object is returned which provides information about the axis (for example, the tick values which the plot will use to draw gridlines if they are visible). All axes are given the opportunity to refresh the axis ticks during the drawing process, which allows for dynamic adjustment depending on the amount of space available for drawing the axis: å public abstract List refreshTicks(Graphics2D g2, AxisState state, Rectangle2D plotArea, Rectangle2D dataArea, RectangleEdge edge); Creates a list of ticks for the axis and updates the axis state. CHAPTER 24. PACKAGE: ORG.JFREE.CHART.AXIS 24.2.10 182 Change Notification This class implements a change notification mechanism that is used to notify other objects whenever an axis is changed in some way. This is part of a JFreeChart-wide mechanism that makes it possible to receive notifications whenever a component of a chart is changed. Most often, such notifications result in the chart being redrawn. The following methods are used: å public void addChangeListener(AxisChangeListener listener); Registers an object to receive notification whenever the axis changes. å public void removeChangeListener(AxisChangeListener listener); Deregisters an object, so that it no longer receives notification when the axis changes. å public void notifyListeners(AxisChangeEvent event); Notifies all registered listeners that a change has been made to the axis. See Also AxisChangeEvent, AxisChangeListener, CategoryAxis, DateAxis, NumberAxis. 24.3 AxisCollection 24.3.1 Overview A storage structure that is used to record the axes that have been assigned to the top, bottom, left and right sides of a plot. 24.3.2 Notes Axis collections are maintained only temporarily during the process of drawing a chart. 24.4 AxisLocation 24.4.1 Overview This class is used to represent the possible axis locations for a 2D chart: • AxisLocation.TOP OR LEFT; • AxisLocation.TOP OR RIGHT; • AxisLocation.BOTTOM OR LEFT; • AxisLocation.BOTTOM OR RIGHT; The final position of the axis is dependent on the orientation of the plot (horizontal or vertical) and whether the axis is being used as a domain or a range axis. 24.4.2 Notes The axis location is set using methods in the CategoryPlot and XYPlot classes. CHAPTER 24. PACKAGE: ORG.JFREE.CHART.AXIS 24.5 AxisSpace 24.5.1 Overview 183 This class is used to record the amount of space (in Java2D units) required to display the axes around the edges of a plot. Since the plot may contain many axes (or, in the most complex case, many subplots containing many axes) this class is used to collate the space requirements for all the axes. plotArea top dataArea left right bottom Figure 24.2: AxisSpace Attributes Axes are always drawn around the edges of the data area but should never extend outside the plot area. 24.5.2 Methods There are methods to get and set each of the attributes top, bottom, left and right maintained by this class. To add space to a particular edge: å public void add(double space, RectangleEdge edge); Adds the specified amount of space (in Java2D units) to one edge. Sometimes you want to ensure that there is at least a specified amount of space for the axis along a particular edge (this is used to ensure that the data areas in combined plots are aligned). The following methods achieve this: å public void ensureAtLeast(double space, RectangleEdge edge); Ensures that there is at least the specified amount of space for the axes along the specified edge. å public void ensureAtLeast(AxisSpace space); As above, but applied to all the edges. Given a rectangle and an instance of AxisSpace, you can calculate the size of an inner rectangle (essentially this is how the data area is computed from the plot area): å public Rectangle2D shrink(Rectangle2D area, Rectangle2D result); Calculates an inner rectangle based on the current space settings. If result is null a new Rectangle2D is created for the result, otherwise the supplied rectangle is recycled. 24.6 AxisState 24.6.1 Overview Instances of this class are used to record state information for an axis during the process of drawing the axis to some output target. CHAPTER 24. PACKAGE: ORG.JFREE.CHART.AXIS 24.6.2 184 Notes By recording state information per drawing of an axis, it should be possible for separate threads to draw the same axis to different output targets simultaneously without interfering with one another. This is part of an effort to (eventually) make JFreeChart thread-safe. 24.7 CategoryAnchor 24.7.1 Overview An enumeration of the anchor points within the space allocated for a single category on a CategoryAxis: Default: Value: CategoryAnchor.START CategoryAnchor.MIDDLE CategoryAnchor.END The start of the category. The middle of the category. The end of the category. 24.7.2 Usage This class is used to control the position of the domain axis gridlines drawn in a CategoryPlot (see the setDomainGridlinePosition() method). 24.8 CategoryAxis 24.8.1 Overview A category axis is used as the domain axis in a CategoryPlot. Categories are displayed at regular intervals along the axis, with a gap before the first category (the lower margin), a gap after the last category (the upper margin) and a gap between each category (the category margin). Category Axis CATEGORY 1 lowerMargin CATEGORY 2 CATEGORY N upperMargin categoryMargin Figure 24.3: The CategoryAxis margins The axis will usually display a label for each category. There are a range of options for controlling the position, alignment and rotation of the labels—these are described in section 24.8.6. 24.8.2 Constructor This class has two contructors: å public CategoryAxis(); Equivalent to CategoryAxis(null)—see the next constructor. å public CategoryAxis(String label); Creates a new category axis with the specified label. If you prefer no axis label, you can use null for the label argument. All other attributes are set to default values. CHAPTER 24. PACKAGE: ORG.JFREE.CHART.AXIS Attribute: Description: lowerMargin The margin that appears before the first category, expressed as a percentage of the overall axis length (defaults to 0.05 or five percent). The margin that appears after the last category, expressed as a percentage of the overall axis length (defaults to 0.05 or five percent). The margin between categories, expressed as a percentage of the overall axis length (to be distributed between N-1 gaps, where N is the number of categories). The default value is 0.20 (twenty percent). The offset between the axis line and the category labels. A structure that defines label positioning information for each possible axis location (the axis may be located at the top, bottom, left or right of the plot). upperMargin categoryMargin categoryLabelPositionOffset categoryLabelPositions 185 Table 24.3: Attributes for the CategoryAxis class 24.8.3 Attributes The attributes maintained by the CategoryAxis class are listed in Table 24.3. These attributes are in addition to those inherited from the Axis class (see section 24.2.3 for details). The following default values are used: Default: Value: DEFAULT AXIS MARGIN DEFAULT CATEGORY MARGIN 0.05 (5 percent). 0.20 (20 percent). 24.8.4 Setting Axis Margins To control the lower margin for the axis: å public double getLowerMargin(); Returns the lower margin for the axis, as a percentage of the total axis length. The default value is 0.05 (five percent). å public void setLowerMargin(double margin); Sets the lower margin for the axis and sends an AxisChangeEvent to all registered listeners. The margin is a percentage of the axis length (for example, 0.05 for a five percent margin). To control the upper margin for the axis: å public double getUpperMargin(); Returns the upper margin for the axis, as a percentage of the total axis length. The default value is 0.05 (five percent). å public void setUpperMargin(double margin); Sets the upper margin for the axis and sends an AxisChangeEvent to all registered listeners. The margin is a percentage of the axis length (for example, 0.05 for a five percent margin). To control the margin between categories: å public double getCategoryMargin(); Returns the (total) margin between all categories, as a percentage of the total axis length. The default value is 0.20 (that is, twenty percent of the axis length is allocated to the gaps between categories). å public void setCategoryMargin(double margin); Sets the category margin for the axis and sends an AxisChangeEvent to all registered listeners. The margin is a percentage of the axis length (for example, 0.20 for a twenty percent margin). The overall margin is distributed over N-1 gaps where N is the number of categories displayed on the axis. CHAPTER 24. PACKAGE: ORG.JFREE.CHART.AXIS 24.8.5 186 Category Labels The labels displayed on the axis to represent each category are obtained directly from the dataset, by calling the toString() method on the dataset’s column key (similarly, the series label displayed in the legend is obtained by calling the toString() method on the row key). There are many options available for positioning, aligning and rotating the category labels on the axis—these options are described in more detail in the next section. Here, we simply describe the technique for rotating the category labels by 90 degrees, which is a common requirement: CategoryPlot plot = (CategoryPlot) chart.getPlot(); CategoryAxis axis = plot.getDomainAxis(); axis.setCategoryLabelPositions(CategoryLabelPositions.UP 90); 24.8.6 Category Label Positioning and Alignment There are many options for controlling the positioning, alignment and rotation of category labels. This provides a great deal of flexibility, but at the price of being somewhat complex. By default, JFreeChart will display category labels on a single line, truncated if necessary. However, multi-line labels are supported: å public int getMaximumCategoryLabelLines(); Returns the current maximum number of lines for displaying category labels. The default value is 1. å public void setMaximumCategoryLabelLines(int lines); Sets the maximum number of lines for displaying category labels and sends an AxisChangeEvent to all registered listeners. Line wrapping occurs when longer labels reach the maximum width allowed for category labels. This maximum category label width is specified in a relative way, in the CategoryLabelPosition class. In addition, there is an override setting in this class: å public float getMaximumCategoryLabelWidthRatio(); Returns the maximum category label width setting, which is expressed as a percentage of either (a) the category label rectangle, or (b) the length of the range axis. The default value is 0.0, which means this override setting is ignored. å public void setMaximumCategoryLabelWidthRatio(float ratio); Sets the maximum category label width, expressed as a percentage of (a) the category label rectangle, or (b) the length of the range axis. This setting overrides the value specified in the CategoryLabelPosition class (see below). After setting the value, an AxisChangeEvent is sent to all registered listeners. To control the offset between the axis and the category labels: å public int getCategoryLabelPositionOffset(); Returns the offset (in Java2D units) between the axis and the category labels. The default value is 4. å public void setCategoryLabelPositionOffset(int offset); Sets the offset, in Java2D units, between the axis and the category labels, then sends an AxisChangeEvent to all registered listeners. To control the position and rotation of the category labels: å public CategoryLabelPositions getCategoryLabelPositions(); Returns an object containing the four CategoryLabelPosition instances that apply for each possible location of the axis. This method never returns null. å public void setCategoryLabelPositions(CategoryLabelPositions positions); Sets the attribute that controls the position, alignment and rotation of the category labels along the axis, then sends an AxisChangeEvent to all registered listeners. CHAPTER 24. PACKAGE: ORG.JFREE.CHART.AXIS 187 The CategoryLabelPositions class is just a structure containing four instances of the CategoryLabelPosition class. When the axis needs to determine where it is going to draw the category labels, it will select one of those instances depending on the current location of the axis (at the top, bottom, left or right of the plot). It is the attributes of the CategoryLabelPosition object that ultimately determine where the labels are drawn. • the first attribute is an anchor point relative to a notional category rectangle that is computed by the axis (see figure 24.4).Within this rectangle, an anchor point is specified using the RectangleAnchor class. Category Axis CATEGORY 2 CATEGORY N Category 1 Label Rectangle Figure 24.4: A category label rectangle • the second attribute is a text anchor, which defines a point on the category label which is aligned with the anchor point on within the category rectangle mentioned previously. This is specified using the TextBlockAnchor class. Try running the DrawStringDemo class in the JCommon distribution to see how the anchor is used to align text to a point on the screen. • two additional attributes define a rotation anchor point and a rotation angle. These are applied once the label text has been positioned using the previous two attributes; • a width ratio and width ratio type control the maximum width of the category labels. 24.8.7 Per Category Tick Label Settings The category label font and paint settings are inherited from the Axis class. However, the CategoryAxis class also provides the ability to override these settings on a per-category basis: å public Font getTickLabelFont(Comparable category); Returns the override font for the specified category, or null if there is no setting for that category. å public void setTickLabelFont(Comparable category, Font font); Sets the override font for the specified category, and sends an AxisChangeEvent to all registered listeners. å public Paint getTickLabelPaint(Comparable category); Returns the override paint for the specified category, or null if there is no setting for that category. å public void setTickLabelPaint(Comparable category, Paint paint); Sets the override paint for the specified category, and sends an AxisChangeEvent to all registered listeners. 24.8.8 Category Label Tool Tips It is possible to specify tooltips for the labels along the category axis. This can be useful if you want to use short category names, but have the opportunity to display a longer description. To add a tool tip: å public void addCategoryLabelToolTip(Comparable category, String tooltip); Adds a tooltip for the specified category. To remove a tool tip: CHAPTER 24. PACKAGE: ORG.JFREE.CHART.AXIS 188 å public void removeCategoryLabelToolTip(Comparable category); Removes the tooltip for the specified category. To remove all tool tips: å public void clearCategoryLabelToolTips(); Removes all category label tool tips. This feature is not supported by other axis types yet. 24.8.9 Other Methods To control whether or not a line is drawn for the axis: å public void setAxisLineVisible(boolean visible); Sets the flag that controls whether or not a line is drawn for the axis. Often, this isn’t required because the CategoryPlot draws an outline around itself by default. However, sometimes the plot will have no outline OR the axis may be offset from the plot. The Java2D coordinates for the start, middle and end of the category along the axis are given by: å public double getCategoryStart(int category, int categoryCount, Rectangle2D area, RectangleEdge edge); Returns the start of the specified category (in Java2D units), assuming the axis lies along the specified edge of the given area. å public double getCategoryMiddle(int category, int categoryCount, Rectangle2D area, RectangleEdge edge); Returns the middle of the specified category (in Java2D units), assuming the axis lies along the specified edge of the given area. å public double getCategoryEnd(int category, int categoryCount, Rectangle2D area, RectangleEdge edge); Returns the end of the specified category (in Java2D units), assuming the axis lies along the specified edge of the given area. 24.8.10 Internals In JFreeChart, axes are owned/managed by a plot. The plot is responsible for assigning drawing space to all of the axes in a plot, which it does by first asking the axes to estimate the space they require (primarily for the axis labels). The following method is used: å public AxisSpace reserveSpace(Graphics2D g2, Plot plot, Rectangle2D plotArea, RectangleEdge edge, AxisSpace space); Updates the axis space to allow room for this axis to be drawn. When reserving space, the axis needs to determine the tick marks along the axis, which it does via the following method: å public List refreshTicks(Graphics2D g2, AxisState state, Rectangle2D plotArea, Rectangle2D dataArea, RectangleEdge edge); Returns a list of the ticks along the axis. After the plot has estimated the space required for each axis, it then computes the “data area” and draws all the axes around the edges of this area: å public AxisState draw(Graphics2D g2, double cursor, Rectangle2D plotArea, Rectangle2D dataArea, RectangleEdge edge); Draws the axis along a specific edge of the data area. The cursor is a measure of how far from the edge of the data area the axis should be drawn (another axis may have been drawn along the same edge already, for example) and the plot area is the region inside which all the axes should fit (it contains the data area). For a given rectangular region in Java2D space, the axis can be used to calculate an x-coordinate or a y-coordinate (depending on which edge of the rectangle the axis is aligned) for the start, middle or end of a particular category on the axis: CHAPTER 24. PACKAGE: ORG.JFREE.CHART.AXIS 189 å public double getCategoryJava2DCoordinate(CategoryAnchor anchor, int category, int categoryCount, Rectangle2D area, RectangleEdge edge); Returns the x- or y-coordinate (in Java2D space) of the specified category. å protected double calculateCategorySize(int categoryCount, Rectangle2D area, RectangleEdge edge); Returns the width (in Java2D units) of one category assuming the axis lies along the specified edge of the given area. The size is a function of the length of the edge along which the axis lies, the number of categories, and the upper, lower and category margins specified for the axis. å protected double calculateCategoryGapSize(int categoryCount, Rectangle2D area, RectangleEdge edge); Returns the width (in Java2D units) of the gap between categories, assuming the axis lies along the specified edge of the given area. The gap size is a function of the length of the edge along which the axis lies, the number of categories, and the upper, lower and category margins specified for the axis. To draw the category labels, JFreeChart calls the following method: å protected AxisState drawCategoryLabels(Graphics2D g2, Rectangle2D plotArea, Rectangle2D dataArea, RectangleEdge edge, AxisState state, PlotRenderingInfo plotState); [1.0.2] Draws the category labels.1 24.8.11 Cloning and Serialization This class is Cloneable and Serializable. 24.8.12 Notes Some points to note: • tick marks are not supported by this axis (yet); • the foreground paint can be set for tick labels, but not the background paint. See Also CategoryPlot, CategoryAxis3D. 24.9 CategoryAxis3D 24.9.1 Overview An extension of the CategoryAxis class that adds a 3D effect. If you use a CategoryItemRenderer that draws items with a 3D effect, then you need to ensure that you are using this class rather than a regular CategoryAxis. Eventually, the aim is to combine this class into the CategoryAxis class. 24.9.2 Constructors There are two constructors: å public CategoryAxis3D(); Creates a new axis with no label. å public CategoryAxis3D(String label); Creates a new axis with the specified label (null is permitted). 1 Prior to 1.0.2, a drawCategoryLabels() method without the dataArea argument was used. CHAPTER 24. PACKAGE: ORG.JFREE.CHART.AXIS 24.9.3 190 Methods The 3D effect is implemented simply by overriding two key methods: å public AxisState draw(Graphics2D g2, double cursor, Rectangle2D plotArea, Rectangle2D dataArea, RectangleEdge edge, PlotRenderingInfo plotState); Draws the axis with a 3D effect. The offsets for the 3D effect are obtained from the plot’s main renderer. å public double getCategoryJava2DCoordinate(CategoryAnchor anchor, int category, int categoryCount, Rectangle2D area, RectangleEdge edge); Returns the Java2D coordinate for the specified category, taking into account the 3D effect. See Also NumberAxis3D. 24.10 CategoryLabelPosition 24.10.1 Overview This class records the attributes that control the positioning (including alignment and rotation) of category labels along a CategoryAxis: • the category anchor - a RectangleAnchor that is used to determine the point on the axis against which the category label is aligned. This is specified relative to a rectangular area that the CategoryAxis allocates for the category (see figure 24.4); • the label anchor - a TextBlockAnchor that determines the point on the category label (a TextBlock) that is aligned with the category anchor; • the rotation anchor - the point on the category label about which the label is rotated (note that there may be no rotation); • the rotation angle - the angle of the rotation, specified in radians; • the category label width type - controls whether the maximum width for the labels is relative to the width of the category label rectangle (the default) or the length of the range axis (useful when labels are rotated so that they are perpendicular to the category axis); • the maximum category label width ratio, measured as a percentage of either the category label rectangle or the length of the range axis (see the previous setting). 24.10.2 Usage To customise the label positioning, alignment and rotation, you would typically create four instances of this class (one for each of the possible axis locations) and use these to create a CategoryLabelPositions object. 24.10.3 Notes The following points should be noted: • instances of this class are immutable, a fact that is relied upon by code elsewhere in the JFreeChart library. CHAPTER 24. PACKAGE: ORG.JFREE.CHART.AXIS 24.11 CategoryLabelPositions 24.11.1 Overview 191 This class is used to specify the positions of category labels on a CategoryAxis. To account for the fact that an axis can appear in one of four different locations (the top, bottom, left or right of the plot) this class contains four instances of the CategoryLabelPosition class—the axis will choose the appropriate one when the labels are being drawn. Several static instances of this class have been predefined in order to simplify general usage of the CategoryAxis class: Value: Description: STANDARD UP 90 The default label positions. The labels are rotated 90 degrees, with the text running from the bottom to the top of the chart. The labels are rotated 90 degrees, with the text running from the top to the bottom of the chart. The labels are rotated 45 degrees, with the text running towards the top of the chart. The labels are rotated 45 degrees, with the text running towards the bottom of the chart. DOWN 90 UP 45 DOWN 45 Table 24.4: Static instances of the CategoryLabelPositions class 24.11.2 Usage For example, to change the category axis labels to a 45 degree angle: CategoryAxis domainAxis = plot.getDomainAxis(); domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP 45); The above example uses one of the predefined instances of this class. However, you can also experiment with creating your own instance, to fully customise the category label positions. 24.12 CategoryLabelWidthType 24.12.1 Overview This class defines tokens that are used to specify how the maximum category label width ratio—a setting that limits the width of category labels relative to the size of the plot—is applied. See table 24.5 for the tokens that are defined. 24.12.2 Usage This class is used for the creation of CategoryLabelPosition instances. ID: Description: CategoryLabelWidthType.CATEGORY The maximum width is a percentage of the category width (for example, 0.90 for 90 percent). The maximum width is a percentage of the length of the range axis (typically used when the labels are displayed perpendicular to the category axis). CategoryLabelWidthType.RANGE Table 24.5: Tokens defined by CategoryLabelWidthType CHAPTER 24. PACKAGE: ORG.JFREE.CHART.AXIS 24.12.3 192 Notes Some points to note: • the maximum category label width ratio is set using the setMaximumCategoryLabelWidthRatio() method in the CategoryPlot class (or, if this is 0.0, the ratio is taken from the CategoryLabelPosition instance); • when a category label reaches its maximum width, it will wrap to another line (up to the maximum number of lines allowed). If the full label cannot be displayed within the maximum number of lines allowed, the label is truncated. 24.13 CategoryTick 24.13.1 Overview A class used to represent a single tick on a CategoryAxis. This class is used internally and it is unlikely that you should ever need to use it directly. 24.14 ColorBar 24.14.1 Overview A color bar is used with a ContourPlot. This class is deprecated as of version 1.0.4. 24.15 CompassFormat 24.15.1 Overview A custom NumberFormat class that can be used to display numerical values as compass directions— see figure 24.5 for an example. In the example, the range axis on the left side of the chart displays Figure 24.5: A chart that uses the CompassFormat class compass directions in place of numerical values. 24.15.2 Usage There is a demo (CompassFormatDemo1.java) included in the JFreeChart demo collection. CHAPTER 24. PACKAGE: ORG.JFREE.CHART.AXIS 24.15.3 193 Methods To convert an angle (in degrees) to a compass direction (for example, “NE”): å public String getDirectionCode(double direction); Returns the compass direction (as a String) that corresponds to the given direction (which is expressed in degrees). The return value is one of: N, NNE, NE, ENE, E, ESE, SE, SSE, S, SSW, SW, WSW, W, WNW, NW, NNW. The following methods perform the required formatting, but are usually not called directly (see Java’s NumberFormat class for more details): å public StringBuffer format(double number, StringBuffer toAppendTo, FieldPosition pos); Converts the given number to a string containing the corresponding direction. å public StringBuffer format(long number, StringBuffer toAppendTo, FieldPosition pos); Converts the given number to a string containing the corresponding direction. Parsing is not supported: å public Number parse(String source, ParsePosition parsePosition); This method always returns null, which means this formatter cannot be used for parsing. 24.15.4 Notes Some points to note: • this class cannot be used for parsing numbers; • a demo application (CompassFormatDemo1.java) is included in the JFreeChart demo collection. 24.16 CyclicNumberAxis 24.16.1 Overview An extension of the NumberAxis class that is used to generate cyclic plots. 24.16.2 Constructors To create a new axis: å public CyclicNumberAxis(double period); Creates a new axis with the specified period and a zero offset. No label is set for the axis. å public CyclicNumberAxis(double period, double offset); Creates a new axis with the specified period and offset. No label is set for the axis. å public CyclicNumberAxis(double period, String label); Creates a new axis with the specified period and axis label. The offset is zero. å public CyclicNumberAxis(double period, double offset, String label); Creates a new axis with the specified period, offset and label. 24.16.3 Methods To control the visibility of the “advance line”: å public boolean isAdvanceLineVisible(); Returns the flag that controls whether or not the advance line is displayed. å public void setAdvanceLineVisible(boolean visible); Sets the flag that controls whether or not the advance line is displayed. å public Paint getAdvanceLinePaint(); Returns the paint used to draw the advance line (never null). CHAPTER 24. PACKAGE: ORG.JFREE.CHART.AXIS 194 å public void setAdvanceLinePaint(Paint paint); Sets the paint used to draw the advance line (null not permitted). å public Stroke getAdvanceLineStroke(); Returns the stroke used to draw the advance line (never null). å public void setAdvanceLineStroke(Stroke stroke); Sets the stroke used to draw the advance line (null not permitted). å public boolean isBoundMappedToLastCycle(); To be documented. å public void setBoundMappedToLastCycle(boolean boundMappedToLastCycle); To be documented. 24.17 DateAxis 24.17.1 Overview An axis that displays date/time values—extends ValueAxis. This class is designed to be flexible about the range of dates/times that it can display—anything from a few milliseconds to several centuries can be handled. A date axis can be used for the domain and/or range axis in an XYPlot. In a CategoryPlot, a date axis can only be used for the range axis. 24.17.2 Usage To change the attributes of the axis, you need to obtain a DateAxis reference—because of the way JFreeChart is designed, this usually involves a “cast”: XYPlot plot = (XYPlot) chart.getPlot(); ValueAxis domainAxis = plot.getDomainAxis(); if (domainAxis instanceof DateAxis) { DateAxis axis = (DateAxis) domainAxis; // customise axis here... } Given a DateAxis reference, you can change: • the axis range, see section 24.17.5; • the size and formatting of the tick labels, see section 24.17.7; • other inherited attributes, see section 24.44.4. 24.17.3 Constructors The default constructor creates a new axis with no label: å public DateAxis(); Creates a new date axis with no label. You can specify the label using: å public DateAxis(String label); Creates a new axis with the specified label (null permitted, in which case no label is displayed for the axis). Sometimes it is useful to be able to specify the time zone used for the tick marks and labels on the axis: å public DateAxis(String label, TimeZone zone); Creates a new date axis where the tick marks and labels are calculated for the specified time zone. CHAPTER 24. PACKAGE: ORG.JFREE.CHART.AXIS 24.17.4 195 Attributes The following attributes are defined, in addition to those inherited from the ValueAxis class: Attribute: Description: dateFormatOverride A date formatter that, if set, overrides the format of the tick labels displayed on the axis. Controls the size and formatting of the tick labels on the axis (an instance of DateTickUnit). The minimum date/time visible on the axis. The maximum date/time visible on the axis. A flag that controls whether or not the tick labels on the axis are displayed “vertically” (that is, rotated 90 degrees from horizontal). tickUnit minimumDate maximumDate verticalTickLabels Refer to section 24.44.3 for information about the attributes inherited by this class. 24.17.5 The Axis Range The range of dates displayed by the axis is controlled with the following methods: å public Date getMinimumDate(); Returns the earliest date along the axis range. å public void setMinimumDate(Date date); Sets the earliest date for the axis. å public Date getMaximumDate(); Returns the latest date along the axis range. å public void setMaximumDate(Date maximumDate); Sets the latest date for the axis. To set the axis range:2 å public void setRange(Range range); Sets the range of values to be displayed by the axis and sends an AxisChangeEvent to all registered listeners. å public void setRange(Range range, boolean turnOffAutoRange, boolean notify); Sets the range of values to be displayed by the axis. The turnOffAutoRange flag controls whether the auto range calculation is disabled or not (usually you want to disable it) and the notify flag controls whether or not an AxisChangeEvent is sent to all registered listeners. å public void setRange(Date lower, Date upper); Sets the range of values to be displayed by the axis. å public void setRange(double lower, double upper); Sets the range of values to be displayed by the axis and sends an AxisChangeEvent to all registered listeners. For example: // start and end are instances of java.util.Date axis.setRange(start, end); 24.17.6 Time Zone To control the time zone for the axis (which affects the conversion of date values to string labels): å public TimeZone getTimeZone(); [1.0.4] Returns the time zone for the axis (normally specified in the constructor). å public void setTimeZone(TimeZone zone); [1.0.4] Sets the time zone for the axis and sends an AxisChangeEvent to all registered listeners. 2 Note that when you set the axis range in this way, the auto-range attribute is set to false. It is assumed that by setting a range manually, you do not want that subsequently overridden by the auto-range calculation. CHAPTER 24. PACKAGE: ORG.JFREE.CHART.AXIS 24.17.7 196 Tick Units The tick units on the date axis are controlled by a similar “auto tick unit selection” mechanism to that used in the NumberAxis class. This mechanism relies on a collection of “standard” tick units (stored in an instance of TickUnits). The axis will try to select the smallest tick unit that doesn’t cause the tick labels to overlap. If you want to specify a fixed tick size and format, you can use code similar to this: // set the tick size to one week, with formatting... DateFormat formatter = new SimpleDateFormat("d-MMM-yyyy"); DateTickUnit unit = new DateTickUnit(DateTickUnit.DAY, 7, formatter); axis.setTickUnit(unit); Note that setting a tick unit manually in this way disables the “auto” tick unit selection mechanism. You may find that the tick size you have requested results in overlapping labels. If you just want to control the tick label format, one option is to specify an override format: // specify an override format... DateFormat formatter = new SimpleDateFormat("d-MMM"); axis.setDateFormatOverride(formatter); This is a simple and effective approach in some situations, but has the limitation that the same format is applied to all tick sizes. A final approach to controlling the formatting of tick labels is to create your own TickUnits collection. The collection can contain any number of DateTickUnit objects, and should be registered with the axis as follows: // supply a new tick unit collection... axis.setStandardTickUnits(myCollection); 24.17.8 Tick Label Orientation To control the orientation of the tick labels on the axis: axis.setVerticalTickLabels(true); This code survives from the early days of JFreeChart development when there were separate classes HorizontalDateAxis and VerticalDateAxis...it needs to be changed to be more generic for axes that could have either a horizontal or vertical orientation. 24.17.9 Timelines This class uses a Timeline to provide an opportunity for the axis to map from Java time (measured in milliseconds since 1 January 1970, 00:00:00 GMT), to some other time scale. The default time line performs an “identity” mapping—that is, the millisecond values are not changed. Use the following methods to change the time line: å public Timeline getTimeline(); Returns the current time line. å public void setTimeline(Timeline timeline); Sets the time line and sends an AxisChangeEvent to all registered listeners. CHAPTER 24. PACKAGE: ORG.JFREE.CHART.AXIS 24.17.10 197 Other Methods You can specify a fixed tick unit for the axis: å public DateTickUnit getTickUnit(); Returns the tick unit (possibly null, in which case a tick unit will be selected automatically.) å public void setTickUnit(DateTickUnit unit); Sets the fixed tick unit for the axis and sends an AxisChangeEvent to all registered listeners. å public void setTickUnit(DateTickUnit unit, boolean notify, boolean turnOffAutoSelection); Sets the fixed tick unit for the axis. You can specify an override formatter for the tick labels: å public DateFormat getDateFormatOverride(); Returns the formatter for the tick labels. If this is non-null, it is used to override any other formatter. å public void setDateFormatOverride(DateFormat formatter) Sets the formatter and sends an AxisChangeEvent to all registered listeners. You should be careful using this method, it overrides the date formatting without consideration for the size of the tick units. If you choose an inappropriate date format you will get bad axis labelling. Tick marks and labels are displayed at regular intervals along the axis. You can control whether the marks are positioned at the start, middle or end of the interval: å public DateTickMarkPosition getTickMarkPosition(); Returns the position for the tick marks within each interval along the axis. å public void setTickMarkPosition(DateTickMarkPosition position); Sets the position for the tick marks within each interval along the axis and sends an AxisChangeEvent to all registered listeners. å public void configure(); Configures the axis which involves recalculating the axis range (if the autoRange flag is switched on). å public boolean isHiddenValue(long millis); Returns true if the specified millisecond is hidden by the Timeline, and false otherwise. å public double valueToJava2D(double value, Rectangle2D area, RectangleEdge edge); Converts a data value to Java2D coordinates, assuming that the axis lies along one edge of the specified area. å public double dateToJava2D(Date date, Rectangle2D area, RectangleEdge edge); Converts a date to Java2D coordinates, assuming that the axis lies along one edge of the specified area. å public double java2DToValue(double java2DValue, Rectangle2D area, RectangleEdge edge); Translates a Java2D coordinate into a data value. å public Date calculateLowestVisibleTickValue(DateTickUnit unit); Calculates the value of the first tick mark on the axis. å public Date calculateHighestVisibleTickValue(DateTickUnit unit); Calculates the value of the last tick mark on the axis. å public static TickUnitSource createStandardDateTickUnits(); Creates a set of standard tick units for a date axis. å public static TickUnitSource createStandardDateTickUnits(TimeZone zone); Creates a set of standard tick units for a date axis. å public List refreshTicks(Graphics2D g2, AxisState state, Rectangle2D plotArea, Rectangle2D dataArea, RectangleEdge edge); Returns a list of ticks for the axis. You can override this method to customise the list of ticks displayed on the axis—see YieldCurveDemo.java in the JFreeChart demo collection for an example. CHAPTER 24. PACKAGE: ORG.JFREE.CHART.AXIS 198 å public AxisState draw(Graphics2D g2, double cursor, Rectangle2D plotArea, Rectangle2D dataArea, RectangleEdge edge, PlotRenderingInfo plotState); Draws the axis. Normally, this method is called by the plot that owns the axis—you shouldn’t need to call this method yourself. å public void zoomRange(double lowerPercent, double upperPercent); Changes the axis range to simulate a “zoom” function. å public boolean equals(Object obj); Tests for equality with an arbitrary object. 24.17.11 Notes Some points to note: • although the axis displays dates for tick labels, at the lowest level it is still working with double primitives obtained from the Number objects supplied by the plot’s dataset. The values are interpreted as the number of milliseconds since 1 January 1970 (that is, the same encoding used by java.util.Date). • a DateAxis is typically used as the domain axis (or x-axis) in a chart, but it can also be used as the range axis (or y-axis)—for example, see the EventFrequencyDemo1.java application included in the JFreeChart demo collection. 24.18 DateTickMarkPosition 24.18.1 Overview A simple enumeration of the possible tick mark positions for a DateAxis. The positions are: • DateTickMarkPosition.START; • DateTickMarkPosition.MIDDLE; • DateTickMarkPosition.END. Use the setTickMarkPosition() method in the DateAxis class to change this setting. 24.19 DateTick 24.19.1 Overview A class used to represent a single tick on a DateAxis. 24.19.2 Usage This class is used internally and it is unlikely that you should ever need to use it directly. 24.19.3 Constructor To create a new instance: å public DateTick(Date date, String label, TextAnchor textAnchor, TextAnchor rotationAnchor, double angle); Creates a new tick representing the specified date. CHAPTER 24. PACKAGE: ORG.JFREE.CHART.AXIS 24.19.4 199 General Methods To get the date for this tick: å public Date getDate(); Returns the date for this tick. 24.19.5 Equals, Cloning and Serialization This class overrides the equals() method: å public boolean equals(Object obj); Tests this tick for equality with an arbitrary object. 24.20 DateTickUnit 24.20.1 Overview A date tick unit for use by subclasses of DateAxis (extends the TickUnit class). The unit size can be specified as a multiple of one of the following time units: Time Unit: Constant: Year Month Day Hour Minute Second Millisecond DateTickUnit.YEAR DateTickUnit.MONTH DateTickUnit.DAY DateTickUnit.HOUR DateTickUnit.MINUTE DateTickUnit.SECOND DateTickUnit.MILLISECOND Note that these constants are not the same as those defined by Java’s Calendar class. 24.20.2 Usage There are two ways to make use of this class. The first is where you know the exact tick size that you want for your axis. In this case, you create a new date tick unit then call the setTickUnit() method in the DateAxis class. For example, to set the tick unit size on the axis to one week: XYPlot plot = myChart.getXYPlot(); ValueAxis axis = plot.getDomainAxis(); axis.setTickUnit(new DateTickUnit(DateTickUnit.DAY, 7)); The second usage is to create a collection of tick units using the TickUnits class, and then allow the DateAxis to automatically select an appropriate unit. See the setStandardTickUnits() method for more details. 24.20.3 Constructors To create a new date tick unit: å public DateTickUnit(int unit, int count); Creates a new tick unit with a default date formatter for the current locale. Alternatively, you can supply your own date formatter: å public DateTickUnit(int unit, int count, DateFormat formatter); Creates a new date tick unit with the specified date formatter. For both constructors, the unit argument should be defined using one of the constants listed in section 24.20.1. The count argument specifies the multiplier (often just 1). CHAPTER 24. PACKAGE: ORG.JFREE.CHART.AXIS 24.20.4 200 Methods To get the units used to specify the tick size: å public int getUnit(); Returns a constant representing the units used to specify the tick size. The constants are listed in section 24.20.1. To get the number of units: å public int getCount(); Returns the number of units. To format a date using the tick unit’s internal formatter: å public String dateToString(Date date); Formats the date as a String. The following method is used for simple date addition: å public Date addToDate(Date base); Creates a new Date that is calculated by adding this DateTickUnit to the base date. 24.20.5 Notes This class is immutable, a requirement for all subclasses of TickUnit. See Also NumberTickUnit. 24.21 ExtendedCategoryAxis 24.21.1 Overview An extension of the CategoryAxis class that allows sublabels to be displayed with the categories. 24.21.2 Notes Some points to note: • a couple of demos (SurveyResultsDemo2.java and SurveyResultsDemo3.java) are included in the JFreeChart demo collection. 24.22 LogAxis 24.22.1 Overview An axis that displays a logarithmic scale. This class was first introduced in JFreeChart version 1.0.7. 24.22.2 Constructors To create a new axis instance: å public LogAxis(); [1.0.7] Equivalent to LogAxis(null)—see the next constructor. å public LogAxis(String label); [1.0.7] Creates a new axis with the specified label. If label is null, the axis will be drawn without a label. CHAPTER 24. PACKAGE: ORG.JFREE.CHART.AXIS 24.22.3 201 General Attributes To control the base of the logarithm calculation used by the axis: å public double getBase(); [1.0.7] Returns the base for the logarithm calculation. The default value is 10.0. å public void setBase(double base); [1.0.7] Sets the base for the logarithm calculation, and sends an AxisChangeEvent to all registered listeners. If base is less than or equal to 1.0, this method throws an IllegalArgumentException. This axis can only display positive values. The smallest positive value that will be displayed on the axis is controlled by: å public double getSmallestValue(); [1.0.7] Returns the smallest (positive) value that will be displayed on the axis. The default value is 1E-100. å public void setSmallestValue(double value); [1.0.7] Sets the smallest value that will be displayed on the axis, and sends an AxisChangeEvent to all registered listeners. If value is less than or equal to 0.0, this method throws an IllegalArgumentException. To control the tick unit for the axis: å public NumberTickUnit getTickUnit(); [1.0.7] Returns the current tick unit for the axis. å public void setTickUnit(NumberTickUnit unit); [1.0.7] Equivalent to setTickUnit(unit, true, true)—see the next method. å public void setTickUnit(NumberTickUnit unit, boolean notify, boolean turnOffAutoSelect); [1.0.7] Sets the current tick unit and, if requested, sends an AxisChangeEvent to all registered listeners. å public NumberFormat getNumberFormatOverride(); [1.0.7] Returns the override formatter for the tick labels on the axis. The default value is null. å public void setNumberFormatOverride(NumberFormat formatter); [1.0.7] Sets the override formatter (null is permitetd) for the tick labels on the axis, and sends an AxisChangeEvent to all registered listeners. To control the number of minor tick marks shown between each major tick mark: å public int getMinorTickCount(); [1.0.7] Returns the minor tick count. The default value is 10. å public void setMinorTickCount(int count); [1.0.7] Sets the minor tick count and sends an AxisChangeEvent to all registered listeners. 24.22.4 Other Methods This class provides a number of methods that are typically called by JFreeChart rather than by user code. å public double calculateLog(double value); [1.0.7] Returns x, where value = Math.pow(base, x). å public double calculateValue(double log); [1.0.7] Returns y, where y = Math.pow(base, log). To convert from data-space to Java2D-space and back again: å public double java2DToValue(double java2DValue, Rectangle2D area, RectangleEdge edge); [1.0.7] Converts a Java2D coordinate into data-space, assuming the axis lies along the specified edge of the given area. CHAPTER 24. PACKAGE: ORG.JFREE.CHART.AXIS 202 å public double valueToJava2D(double value, Rectangle2D area, RectangleEdge edge); [1.0.7] Converts a data value into Java2D space, assuming the axis lies along the specified edge of the given area. There are a couple of methods related to the auto-range calculation: å public void configure(); [1.0.7] Updates the axis bounds if the autoRange flag is set. This method is usually called when an axis is first assigned to a plot. å protected void autoAdjustRange(); [1.0.7] Updates the axis bounds to match the available data. To draw the axis: å public AxisState draw(Graphics2D g2, double cursor, Rectangle2D plotArea, Rectangle2D dataArea, RectangleEdge edge, PlotRenderingInfo plotState); [1.0.7] Draws ths axis along one edge of the specified dataArea. Some methods relating to the tick units on the axis: å public List refreshTicks(Graphics2D g2, AxisState state, Rectangle2D dataArea, RectangleEdge edge); [1.0.7] Returns a list of tick marks and labels for the axis. å protected void selectAutoTickUnit(Graphics2D g2, Rectangle2D dataArea, RectangleEdge edge); [1.0.7] Selects a tick unit from the current TickUnitSource in such a way that the tick labels will not overlap. å public double exponentLengthToJava2D(double length, Rectangle2D area, RectangleEdge edge); [1.0.7] Returns the length, in Java2D units, of a value given in the linear scale for the axis. å public static TickUnitSource createLogTickUnits(Locale locale); [1.0.7] Creates a default set of tick units for the axis. The following method is overridden to support zooming: å public void zoomRange(double lowerPercent, double upperPercent); [1.0.7] Adjusts the axis range to show the interval specified. 24.22.5 Equals, Cloning and Serialization This class overrides the equals() method: å public boolean equals(Object obj); [1.0.7] Tests this axis for equality with an arbitrary object. Instances of this class are Cloneable and Serializable. 24.22.6 Notes A demo (LogAxisDemo1.java) is included in the JFreeChart demo collection. See Also: LogarithmicAxis. CHAPTER 24. PACKAGE: ORG.JFREE.CHART.AXIS 24.23 LogarithmicAxis 24.23.1 Overview 203 A numerical axis that displays values using a logarithmic scale (with base 10). This class extends NumberAxis and can be used anywhere that a NumberAxis can be used, including: • as the range axis on a CategoryPlot; • as the domain and/or range axis on an XYPlot; • as the range axis on a ThermometerPlot. Note: This class has some quirks and isn’t quite as flexible as it could be. There’s now an alternative axis that you might want to try—LogAxis. 24.23.2 Constructors This class has a single constructor: å public LogarithmicAxis(String label); Creates a new axis with the specified label. If the label is null, the axis is displayed without a label. The default tick label format for the axis will be regular numeric labels, rather than the scientific or power notations. 24.23.3 The Axis Range By default, the axis range is automatically calculated to match the range of values plotted against the axis. If you prefer to set the axis range manually, the following method will do this: å public void setRange(Range range); Sets the bounds of the axis to the given range. Once a range has been manually set, changes to the dataset do not alter the axis range. You can restore the automatic range calculation using: axis.setAutoRange(true); A flag is used to control whether the automatically calculated range is expanded to include the next “power of ten” value: å public boolean getAutoRangeNextLogFlag(); Returns true if the next power of ten is included in the automatic range, and false otherwise. å public void setAutoRangeNextLogFlag(boolean flag); Sets the flag that controls whether the next “power of ten” is included in the automatic range calculation. The default value is false. The following method updates the axis bounds according to the values in the dataset (it is usually called by JFreeChart, you shouldn’t need to call this method directly): å public void autoAdjustRange(); Updates the axis bounds to reflect the range of values in the dataset. 24.23.4 Negative Values A logarithmic axis can only display positive values. However, the JFreeChart implementation provides an option to allow negative values to be plotted on a logarithmic scale. å public boolean getAllowNegativesFlag(); Returns true if the axis is configured to display negative values, and false otherwise. å public void setAllowNegativesFlag(boolean flgVal); Sets the flag that controls whether or not the axis will display negative values. CHAPTER 24. PACKAGE: ORG.JFREE.CHART.AXIS 204 The strictValues flag controls whether or not a RuntimeException is thrown when a negative value is encountered and the allowNegativeValues flag is false. Note: setting this flag to false appears to be equivalent to setting the allowNegativesFlag to true. å public boolean getStrictValuesFlag(); Returns the value of the strictValuesFlag. å public void setStrictValuesFlag(boolean flgVal); Sets the flag that controls whether or not a RuntimeException is thrown when the allowNegativesFlag is false and a negative value is encountered. 24.23.5 Tick Label Formatting The axis can display tick labels in several formats: • as a regular number (the default); • in the form 10^x; • using scientific notation (for example, 1E8 which is 1 x 10^8). The log10TickLabelsFlag flag controls the selection of the “10^x” format: å public boolean getLog10TickLabelsFlag(); Returns true if the tick labels are displayed in the form “10^x”, and false otherwise. å public void setLog10TickLabelsFlag(boolean flag); Sets the flag that controls whether the tick labels are displayed in the form “10^x”. This flag takes precedence over the expTickLabelsFlag flag. The expTickLabelsFlag flag controls the selection of the scientific format: å public boolean getExpTickLabelsFlag(); Returns true if the tick labels are displayed using scientific notation (for example, 1E2, which is equivalent to 1 x 10^2), and false otherwise. å public void setExpTickLabelsFlag(boolean flgVal); Sets a flag that controls whether the tick labels are displayed in scientific notation. This flag is ignored if the log10TickLabelsFlag is true. 24.23.6 Other Methods The remaining methods in this class are used to convert data values to Java2D coordinates and vice-versa: å public double valueToJava2D(double value, Rectangle2D plotArea, RectangleEdge edge); Converts value to a Java2D coordinate along the edge of the given PlotArea. å public double java2DToValue(double java2DValue, Rectangle2D plotArea, RectangleEdge edge); Converts java2DValue to an axis value. å public double adjustedLog10(double val); To be documented. 24.23.7 Notes An alternative to this class is the LogAxis class. 24.24 MarkerAxisBand 24.24.1 Overview A band that can be added to a NumberAxis to highlight certain value ranges. NOTE: this facility is broken at present, so this class should not be used. CHAPTER 24. PACKAGE: ORG.JFREE.CHART.AXIS 24.25 ModuloAxis 24.25.1 Overview 205 This axis is a special extension of NumberAxis that presents a fixed range of values in a “circular” or “cyclic” fashion. It was originally developed to display directional measurements (that is, values in the range 0 to 360 degrees), but should be general enough to be applied for other uses. The CompassFormatDemo2 application (included in the JFreeChart demo collection) provides one example of this axis in use—see figure 24.6. Figure 24.6: A chart that uses a ModuloAxis 24.25.2 Constructor There is a single constructor: å public ModuloAxis(String label, Range fixedRange); Creates a new axis with the specified label and fixedRange. 24.25.3 The Display Range The display range is the subset (of the fixed range) that is currently displayed by the axis. It is defined by a start value and an end value. It is possible for the start value to be greater than the end value—in this case, the displayed range is formed from two parts: (1) the start value to the upper bound of the fixed range, and (2) the lower bound of the fixed range to the end value. To find the current display range: å public double getDisplayStart(); Returns the start value of the range being displayed by the axis. This value will always fall within the fixed range specified in the constructor. å public double getDisplayEnd(); Returns the end value of the range being displayed by the axis. This value will always fall within the fixed range specified in the constructor. To set the display range: å public void setDisplayRange(double start, double end); Sets the display range for the axis. If either start or end fall outside the fixed range specified in the constructor, they will first be mapped to the fixed range (using a modulo-like calculation). It is possible for start to be greater than end—in this case, the displayed range is formed from two parts: (1) the start value to the upper bound of the fixed range, and (2) the lower bound of the fixed range to the end value. CHAPTER 24. PACKAGE: ORG.JFREE.CHART.AXIS 24.25.4 206 Other Methods Other methods defined for this class are mainly for internal use: å public double valueToJava2D(double value, Rectangle2D area, RectangleEdge edge); Converts a data value to a Java2D coordinate, assuming that the axis lies along the specified edge of the given area. This method overrides the method provided by NumberAxis to account for the fact that the display range may be in two pieces. å public double java2DToValue(double java2DValue, Rectangle2D area, RectangleEdge edge); Converts a Java2D coordinate into a data value, assuming that the axis lies along the specified edge of the given area. This method overrides the method provided by NumberAxis to account for the fact that the display range may be in two pieces. å public void resizeRange(double percent); Resizes the display range, about its central value, by the specified percentage (values less that 1.0 or 100% will shrink the range, while values greater than 1.0 will expand the range). å public void resizeRange(double percent, double anchorValue); Resizes the display range by the specified percentage about the anchorValue. Percentage values less that 1.0 or 100% will shrink the range, while values greater than 1.0 will expand the range). å public double lengthToJava2D(double length, Rectangle2D area, RectangleEdge edge); Converts a length (specified in data space) into Java2D units. This method overrides the method specified in NumberAxis to account for the fact that the displayed range on the axis may be in two pieces. 24.26 MonthDateFormat 24.26.1 Overview A custom date formatter that displays the month and, optionally, the year. This formatter is typically used with the PeriodAxis class. An example of the sequence of date strings that can be generated with this formatter is: Jan06 Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec Notice how the first month has the year appended to it (this is configurable for every month). 24.26.2 Constructors There are a range of constructors that allow you to configure the formatter as appropriate: å public MonthDateFormat(); Creates a new formatter for the default time zone. This is equivalent to: new MonthDateFormat(TimeZone.getDefault()); å public MonthDateFormat(TimeZone zone); Creates a new formatter for the given time zone. This is equivalent to: new MonthDateFormat(zone, Locale.getDefault(), 1, true, false); This means that months are labelled with a single letter, and a two-digit year indicator is added to January only. å public MonthDateFormat(TimeZone zone, int chars); Creates a new formatter for the given time zone, with the specified number of characters for each month. This is equivalent to: new MonthDateFormat(zone, Locale.getDefault(), chars, true, false); A two-digit year indicator is added to January only. å public MonthDateFormat(Locale locale); Creates a new formatter for the given locale. This is equivalent to: CHAPTER 24. PACKAGE: ORG.JFREE.CHART.AXIS 207 new MonthDateFormat(TimeZone.getDefault(), locale, 1, true, false); This means that months are labelled with a single letter, and a two-digit year indicator is added to January only. å public MonthDateFormat(Locale locale, int chars); Creates a new formatter for the given locale, with the specified number of characters for each month. This is equivalent to: new MonthDateFormat(TimeZone.getDefault(), locale, chars, true, false); A two-digit year indicator is added to January only. å public MonthDateFormat(TimeZone zone, Locale locale, int chars, boolean showYearForJan, boolean showYearForDec); Creates a new formatter for the given time zone and locale. The chars argument specifies the number of characters to display for each month name. The remaining flags control whether or not the year is displayed for the months January and December (the year is NOT displayed for the other months). The year is formatted using new SimpleDateFormat("yy"). The remaining constructor allows every attribute to be customised: å public MonthDateFormat(TimeZone zone, Locale locale, int chars, boolean[] showYear, DateFormat yearFormatter); Creates a new formatter for the given time zone and locale. The time zone determines which month a given date falls into, while the locale determines the labels used for the months. The chars argument specifies the number of characters to display for each month name. The showYear array should contain 12 flags that determine whether the year is appended to each month label (sometimes you will want the year appended to every month, sometimes you may just want the first month (January) of each year to have the year displayed. The final argument controls the formatting of the year. 24.26.3 Methods The following methods from DateFormat are required to be overridden—you won’t normally call these methods directly: å public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition); Formats the given date. å public Date parse(String source, ParsePosition pos); This method returns null always, which means this formatter cannot be used to parse text into dates. This class overrides the equals() method: å public boolean equals(Object obj); Tests this formatter for equality with an arbitrary object. 24.27 NumberAxis 24.27.1 Overview An axis that displays numerical data along a linear scale. This class extends ValueAxis. You can create your own subclasses if you have special requirements. 24.27.2 Usage A NumberAxis can be used for: • the range axis in a CategoryPlot. • the domain and/or range axes in an XYPlot; CHAPTER 24. PACKAGE: ORG.JFREE.CHART.AXIS 208 The methods for obtaining a reference to the axis typically return a ValueAxis, so you will need to “cast” the reference to a NumberAxis before using any of the methods specific to this class. For example: ValueAxis rangeAxis = plot.getRangeAxis(); if (rangeAxis instanceof NumberAxis) { NumberAxis axis = (NumberAxis) rangeAxis; axis.setAutoRangeIncludesZero(true); } This casting technique is used often in JFreeChart.3 24.27.3 Constructors To create a new axis: å public NumberAxis(); Creates a new axis with no label. å public NumberAxis(String label); Creates a new axis with the specified label. If label is null, the axis will be displayed without a label. 24.27.4 Attributes The following table lists the properties maintained by NumberAxis, in addition to those inherited from ValueAxis. Attribute: Description: rangeType Defines the permitted range for the axis: RangeType.FULL, RangeType.POSITIVE and RangeType.NEGATIVE. A flag that indicates whether or not zero is always included when the axis range is determined automatically. A flag that controls the behaviour of the auto-range calculation when zero falls within the lower or upper margin for the axis. If true, the margin will be truncated at zero. A NumberFormat that, if set, overrides the formatting of the tick labels for the axis. A flag that indicates whether or not the tick labels are rotated to vertical. An optional band that highlights ranges along the axis (see MarkerAxisBand). autoRangeIncludesZero autoRangeStickyZero numberFormatOverride verticalTickLabels markerBand The following default values are used for attributes wherever necessary: Name: DEFAULT DEFAULT DEFAULT DEFAULT 24.27.5 Value: MINIMUM AXIS VALUE MAXIMUM AXIS VALUE MINIMUM AUTO RANGE TICK UNIT 0.0 1.0 new Double(0.0000001); new NumberTickUnit(new Double(1.0), new DecimalFormat("0")); The Axis Range You can control most aspects of the axis range using methods inherited from the ValueAxis class— see section 24.44.5 for details. Some additional controls are added by this class. To restrict the axis to display only positive values, or only negative values, you can set the rangeType attribute: å public RangeType getRangeType(); Returns the range type (never null). 3 If you are sure of what you are doing, you can drop the instanceof check. CHAPTER 24. PACKAGE: ORG.JFREE.CHART.AXIS 209 å public void setRangeType(RangeType rangeType); Sets the range type and sends an AxisChangeEvent to all registered listeners. If you have set the autoRange flag to true (so that the axis range automatically adjusts to fit the current data), you may also want to set the autoRangeIncludesZero flag to ensure that the axis range always includes zero: å public boolean getAutoRangeIncludesZero(); Returns true if the auto-range calculation ensures that zero is included in the range, and false otherwise. å public void setAutoRangeIncludesZero(boolean flag); Sets the autoRangeIncludesZero flag and sends an AxisChangeEvent to all registered listeners. Note that some renderers (for example, BarRenderer) have a flag to control the inclusion of some “base” value in the axis range—since the base value often defaults to zero, you may need to set the flag in the renderer also, to get the required range for the axis. If the autoRangeIncludesZero flag is set to true, then you can further control how the axis margin is calculated when zero falls within the axis margin. By setting the autoRangeStickyZero flag to true you can truncate the margin at zero: å public boolean getAutoRangeStickyZero(); Returns true if the axis margin should be truncated at zero if the zero value falls within the margin. å public void setAutoRangeStickyZero(boolean flag); Sets the flag that controls whether or not the axis margin is truncated if the zero value falls within the margin. An AxisChangeEvent is sent to all registered listeners. 24.27.6 Auto Tick Unit Selection The NumberAxis class contains a mechanism for automatically selecting a tick unit from a collection of “standard” tick units. The aim is to display as many ticks as possible, without the tick labels overlapping. The appropriate tick unit will depend on the axis range (which is often a function of the available data) and the amount of space available for displaying the chart. The default standard tick unit collection contains about 50 tick units ranging in size from 0.0000001 to 1,000,000,000. The collection is created and returned by the createStandardTickUnits() method. You can replace the default collection with any other collection of tick units you care to create. One common situation where this is necessary is the case where your data consists of integer values only. In this case, you only want the axis to display integer tick values, but sometimes the axis will show values like 0.00, 2.50, 5.00. 7.50, 10.00, when you might prefer 0, 2, 4, 6, 8, 10. For this situation, a set of standard integer tick units has been created. Use the following code: NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis(); TickUnits units = NumberAxis.createIntegerTickUnits(); rangeAxis.setStandardTickUnits(units); For greater control over the tick sizes or formatting, create your own TickUnits object. 24.27.7 Specifying a Formatting Override For convenience, you can supply a NumberFormat instance as an override for the tick label formatting. å public NumberFormat getNumberFormatOverride(); Returns the override formatter for the tick labels on the axis. The default value is null (no override). å public void setNumberFormatOverride(NumberFormat formatter); Sets the override formatter for the tick labels on the axis and sends an AxisChangeEvent to all registered listeners. You can set this to null to revert to using the standard formatters. For example, to format the tick labels along the axis as percentages, you could use the following: NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis(); rangeAxis.setNumberFormatOverride(new DecimalFormat(0̈.00%¨ )); CHAPTER 24. PACKAGE: ORG.JFREE.CHART.AXIS 24.27.8 210 Methods When the auto-tick-unit-selection flag is set to true, the axis will select a tick unit from a set of standard tick units. You can define your own standard tick units for an axis with the following method: å public void setStandardTickUnits(TickUnits units); Sets the standard tick units for the axis. You don’t have to use the auto tick units mechanism. To specify a fixed tick size (and format): å public void setTickUnit(NumberTickUnit unit); Sets a fixed tick unit for the axis. This allows you to control the size and format of the ticks, but you need to be sure to choose a tick size that doesn’t cause the tick labels to overlap. å public void setTickUnit(NumberTickUnit unit, boolean notify, boolean turnOffAutoSelect); Sets the current tick unit for the axis and, if notify is true, sends an AxisChangeEvent to all registered listeners. If turnOffAutoSelect is true, this method sets autoTickUnitSelection to false. å public NumberTickUnit getTickUnit(); Returns the current tick unit for the axis. This controls the spacing between tick marks along the axis, and also the format of the tick labels. The following methods provide access to marker bands for the axis (these are currently broken, so you should not use these methods): å public MarkerAxisBand getMarkerBand(); Returns the marker band for the axis, or null if no band is installed. å public void setMarkerBand(MarkerAxisBand band); Sets the marker band for the axis and sends an AxisChangeEvent to all registered listeners. 24.27.9 Coordinate Translation A core function of the axis is to translate values between data space (axis coordinates) and Java2D space (for rendering on the screen or some other output target). This is handled via the following methods: å public double valueToJava2D(double value, Rectangle2D area, RectangleEdge edge); Translates a value along the axis scale to a value in Java2D space, assuming that the axis runs along the specified edge of the given area. å public double java2DToValue(double java2DValue, Rectangle2D area, RectangleEdge edge); Tranlates a Java2D coordinate to a value on the axis scale, assuming that the axis runs along the specified edge of the given area. 24.27.10 Other Methods The remaining methods are typically used by other JFreeChart components—you won’t normally call these methods yourself: å public void configure(); Reconfigures the axis—this updates the axis range if the auto-range calculation flag is set. å public List refreshTicks(Graphics2D g2, AxisState state, Rectangle2D dataArea, RectangleEdge edge); Creates and returns a list of ticks for display along the axis. This list is refreshed every time the axis is drawn. You can override this method to take full control of the values along the axis that will display tick labels. å public AxisState draw(Graphics2D g2, double cursor, Rectangle2D plotArea, Rectangle2D dataArea, RectangleEdge edge, PlotRenderingInfo plotState); Draws the axis alogn the given edge of the specified dataArea. CHAPTER 24. PACKAGE: ORG.JFREE.CHART.AXIS 24.27.11 211 Standard Tick Units å public static TickUnitSource createStandardTickUnits(); Returns a collection of standard sizes (and label formats) for the ticks along the axis. å public static TickUnitSource createStandardTickUnits(Locale locale); As for the previous method, except the standard number format for the given locale is used to format the tick labels. å public static TickUnitSource createIntegerTickUnits(); Returns a collection of (integer-only) standard sizes (and associated label formats) for the ticks along the axis. å public static TickUnitSource createIntegerTickUnits(Locale locale); As for the previous method, except the standard integer format for the given locale is used to format the tick labels. 24.27.12 Equals, Cloning and Serialization This class overrides the equals() method: å public boolean equals(Object obj); Tests this axis for equality with an arbitrary object. å public int hashCode(); Returns a hash code for the axis. 24.27.13 Notes Some points to note: • you can reverse the direction of the values on the axis by calling setInverted(true)—this method is inherited from the ValueAxis class; • this class defines a default set of standard tick units. You can override the default settings by calling the setStandardTickUnits() method. See Also ValueAxis, TickUnits. 24.28 NumberAxis3D 24.28.1 Overview An extension of the NumberAxis class that adds a 3D effect. The offset for the 3D effect is obtained from the plot’s main renderer, assuming that it implements the Effect3D interface. 24.28.2 Constructors There are two constructors: å public NumberAxis3D(); Creates a new axis with no label. å public NumberAxis3D(String label); Creates a new axis with the specified label (null is permitted). CHAPTER 24. PACKAGE: ORG.JFREE.CHART.AXIS 24.28.3 212 Methods The 3D effect is implemented by overriding the drawing method: å public AxisState draw(Graphics2D g2, double cursor, Rectangle2D plotArea, Rectangle2D dataArea, RectangleEdge edge, PlotRenderingInfo plotState); Draws the axis with a 3D effect (the offsets for the 3D effect are obtained from the plot’s main renderer). 24.28.4 Notes Ideally, this class will be combined with the NumberAxis class. See Also CategoryAxis3D. 24.29 NumberTick 24.29.1 Overview A class used to represent a single tick on a NumberAxis. 24.29.2 Usage This class is used internally and it is unlikely that you should ever need to use it directly. 24.29.3 Constructors To create a new instance: å public NumberTick(Number number, String label, TextAnchor textAnchor, TextAnchor rotationAnchor, double angle); Creates a new instance. å public NumberTick(TickType tickType, double value, String label, TextAnchor textAnchor, TextAnchor rotationAnchor, double angle); [1.0.7] Creates a new instance with the specified type.4 24.29.4 Methods In addition to the methods inherited from ValueTick, this class defines the following method: å public Number getNumber(); Returns the numerical value associated with this tick. 24.29.5 Notes Instances of this class are created on-the-fly during the chart rendering process—they’re never used to represent a chart structure, so there’s no need to support cloning and serialization (although it probably wouldn’t hurt to add this). See Also: ValueTick 4 For now, the tick type is used to support major and minor tick marks in the LogAxis class. CHAPTER 24. PACKAGE: ORG.JFREE.CHART.AXIS 24.30 NumberTickUnit 24.30.1 Overview 213 A number tick unit for use by subclasses of NumberAxis (extends the TickUnit class). 24.30.2 Usage There are two ways that this class is typically used. The first is where you know the exact tick size that you want for an axis. In this case, you create a new tick unit then call the setTickUnit() method in the ValueAxis class. For example: XYPlot plot = (XYPlot) chart.getPlot(); ValueAxis axis = plot.getRangeAxis(); axis.setTickUnit(new NumberTickUnit(25.0)); The second is where you prefer to leave the axis to automatically select a tick unit. In this case, you should create a collection of tick units (see the TickUnits class for details). 24.30.3 Constructors To create a new number tick unit: å public NumberTickUnit(double size); Creates a new number tick unit with a default number formatter for the current locale. Alternatively, you can supply your own number formatter: å public NumberTickUnit(double size, NumberFormat formatter); Creates a new number tick unit with the specified number formatter. å public NumberTickUnit(double size, NumberFormat formatter, int minorTickCount); Creates a new number tick unit with the specified number formatter and minor tick count. 24.30.4 Methods To format a value using the tick unit’s internal formatter: å public String valueToString(double value); Formats the value as a String using the internal number formatter. This method is usually called by code in one of the axis classes (for example, NumberAxis). 24.30.5 Equals, Cloning and Serialization To test this object for equality: å public boolean equals(Object obj); Tests this object for equality with an arbitrary object. If obj is null, this method returns false. Instances of this class are immutable, so the class does not implement Cloneable. The class is Serializable. 24.30.6 Notes This class is immutable, a requirement for all subclasses of TickUnit. See Also DateTickUnit. CHAPTER 24. PACKAGE: ORG.JFREE.CHART.AXIS 24.31 PeriodAxis 24.31.1 Overview 214 A date/time axis with the following features: • supports multiple label bands, where each band is divided up into time periods; • automatic range calculation based on (whole unit) time periods; • a user specified time zone; See figure 24.7 for an example. You can use this axis in place of a DateAxis, it does a similar job but with a slightly different set of features. Legal & General Unit Trust Prices 180 170 Price Per Unit 160 150 140 130 120 110 100 Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec Jan Feb Mar Apr May 2001 Jun Jul 2002 Date L&G European Index Trust L&G UK Index Trust Figure 24.7: A chart that uses a PeriodAxis (see PeriodAxisDemo1.java) 24.31.2 Constructors To create a new axis: å public PeriodAxis(String label, RegularTimePeriod first, RegularTimePeriod last); Creates a new axis—calls the next constructor, passing it the default time zone. å public PeriodAxis(String label, RegularTimePeriod first, RegularTimePeriod last, TimeZone timeZone); Creates a new axis that displays data from the first to the last time periods. All time periods are evaluated within the specified timeZone. 24.31.3 The Axis Range The axis range is defined by two time periods: å public RegularTimePeriod getFirst(); Returns the time period that defines the start of the range of values displayed by the axis. å public RegularTimePeriod getLast(); Returns the time period that defines the end of the range of values displayed by the axis. Alternatively, you can get the range (bounds specified in milliseconds): CHAPTER 24. PACKAGE: ORG.JFREE.CHART.AXIS 215 å public Range getRange(); Returns the current axis range. The lower bound of the range is set to the first millisecond of the first time period, and the upper bound of the range is set to the last millisecond of the last time period. The time zone is taken into account when pegging the first and last time periods to the millisecond time line. The axis range can be specified manually or automatically calculated by JFreeChart to “fit” the available data values. To specify a manual range, use the following methods: å public void setFirst(RegularTimePeriod first); Sets the time period that defines the start of the range of values displayed by the axis, and sends an AxisChangeEvent to all registered listeners. å public void setLast(RegularTimePeriod last); Sets the time period that defines the end of the range of values displayed by the axis, and sends an AxisChangeEvent to all registered listeners. To have the axis range calculated automatically, use the setAutoRange() method inherited from the ValueAxis class. In addition, you may want to specify the time period class used by the auto-range calculation—the axis range will always include a whole number of time periods of the class specified: å public Class getAutoRangeTimePeriodClass(); Returns the time period class used when the axis range is calculated automatically. å public void setAutoRangeTimePeriodClass(Class c); Sets the time period class used when the axis range is calculated automatically. The axis range will always be a whole number of periods. Valid classes include: Year.class, Quarter.class, Month.class, Week.class, Day.class, Hour.class. Minute.class, Second.class and Millisecond.class. 24.31.4 Axis Labelling The axis supports one or more “bands” of labels, where each band is represented by an instance of PeriodAxisLabelInfo. Use the following methods to get/set the band definitions: å public PeriodAxisLabelInfo[] getLabelInfo(); Returns an array of objects where each object defines the format for one band of labels along the axis. å public void setLabelInfo(PeriodAxisLabelInfo[] info); Sets an array of objects where each object defines the format for one band of labels along the axis. Examples of specifying label bounds can be found in the PeriodAxisDemo1 and PeriodAxisDemo2 classes, included in the JFreeChart Demo distribution. 24.31.5 Time Zones In order to “peg” time periods to the absolute time line (in Java, measured in milliseconds since 1-Jan-1970 GMT), you need to specify a time zone. Use the following methods: å public TimeZone getTimeZone(); Returns the TimeZone used to “peg” time periods to the absolute time line. å public void setTimeZone(TimeZone zone); Sets the TimeZone that is used to “peg” time periods to the absolute time line. 24.31.6 Other Methods The remaining methods defined by this class are mostly for internal use: å public double valueToJava2D(double value, Rectangle2D area, RectangleEdge edge); Converts a data value to a Java2D coordinate, assuming that the axis lies along the specified edge of the given area. CHAPTER 24. PACKAGE: ORG.JFREE.CHART.AXIS 216 å public double java2DToValue(double java2DValue, Rectangle2D area, RectangleEdge edge); Converts a Java2D coordinate back into a data value, assuming that the axis lies along the specified edge of the given area. å public void configure(); Configures the axis for use. This method is usually called by the plot when the axis is first assigned to the plot, because a new plot means a new set of data and therefore the axis range may need to be updated. You won’t normally need to call this method yourself. å public AxisSpace reserveSpace(Graphics2D g2, Plot plot, Rectangle2D plotArea, RectangleEdge edge, AxisSpace space); Reserves additional space in space to allow room for this axis to be displayed. This method is called by the plot during the process of laying out and drawing the chart, you won’t normally need to call this method yourself. å public AxisState draw(Graphics2D g2, double cursor, Rectangle2D plotArea, Rectangle2D dataArea, RectangleEdge edge, PlotRenderingInfo plotState); Draws the axis. This method is called by the plot, you won’t normally need to call it yourself. å public List refreshTicks(Graphics2D g2, AxisState state, Rectangle2D plotArea, Rectangle2D dataArea, RectangleEdge edge); For this axis, this method returns an empty list. 24.31.7 Equals, Cloning and Serialization This class overrides the equals() method from the Object class: å public boolean equals(Object obj); Tests this axis for equality with an arbitrary object. Another object is considered equal if it is a PeriodAxis with the same attributes as this axis. The axis is Cloneable and PublicCloneable: å public Object clone() throws CloneNotSupportedException; Returns a clone of the axis. The axis is Serializable. 24.31.8 Notes Some points to note: • two demos (PeriodAxisDemo1.java and PeriodAxisDemo2.java) are included in the JFreeChart demo collection. See Also DateAxis, PeriodAxisLabelInfo. 24.32 PeriodAxisLabelInfo 24.32.1 Overview A helper class that records the information for one “band” of labels on a PeriodAxis. When you are specifying the label bands for the axis, you create an array of PeriodAxisLabelInfo objects—for example: PeriodAxisLabelInfo[] info = new PeriodAxisLabelInfo[2]; info[0] = new PeriodAxisLabelInfo(Month.class, new SimpleDateFormat("MMM")); info[1] = new PeriodAxisLabelInfo(Year.class, new SimpleDateFormat("yyyy")); domainAxis.setLabelInfo(info); In the above example, there are two bands. The first band is split into 1 month time periods and the second band is split into 1 year time periods. The sample code comes from the PeriodAxisDemo1.java file that is included in the JFreeChart Demo distribution. CHAPTER 24. PACKAGE: ORG.JFREE.CHART.AXIS 24.32.2 217 Constructors To create a new instance: å public PeriodAxisLabelInfo(Class periodClass, DateFormat dateFormat); Creates a new instance based on the specified periodClass (see below). The dateFormat used to format the labels for each time period. å public PeriodAxisLabelInfo(Class periodClass, DateFormat dateFormat, RectangleInsets padding, Font labelFont, Paint labelPaint, boolean drawDividers, Stroke dividerStroke, Paint dividerPaint); Creates a new instance based on the specified periodClass (see below). The dateFormat is used to format the labels for each time period. The padding controls the minimum gap between time period labels. The remaining arguments control the appearance of the labels and the (optional) dividing lines between labels. When constructing an instance of this class, you need to specify the class of time period that you want to use for labelling purposes. This is usually one of the following: Year.class, Quarter.class, Month.class, Week.class, Day.class, Hour.class, Minute.class, Second.class or Millisecond.class. 24.32.3 Methods The following methods are defined: å public Class getPeriodClass(); Returns the specific class used to represent time periods—it should be some subclass of RegularTimePeriod. å public DateFormat getDateFormat(); Returns the formatter for the date labels. å public RectangleInsets getPadding(); Returns the padding that controls the minimum space between labels. å public Font getLabelFont(); Returns the Font used to display labels for each time period. å public Paint getLabelPaint(); Returns the Paint that is used as the foreground color when displaying labels for each time period. å public boolean getDrawDividers(); Returns a flag that determines whether or not dividers are drawn between time periods. å public Stroke getDividerStroke(); Returns the Stroke used to draw dividers between time periods. å public Paint getDividerPaint(); Returns the Paint used to draw dividers between time periods. å public RegularTimePeriod createInstance(Date millisecond, TimeZone zone); Creates a time period that includes the specified millisecond, taking into account the time zone. The time period will be an instance of the class returned by the getPeriodClass() method. 24.32.4 Equals, Cloning and Serialization To test this instance for equality with another object: å public boolean equals(Object obj); Tests this instance for equality with an arbitrary object. This method will return true if obj is an instance of PeriodAxisLabelInfo with equivalent settings to this instance. To make a clone of this instance: å public Object clone() throws CloneNotSupportedException; Creates a clone of this object. This class is Serializable. CHAPTER 24. PACKAGE: ORG.JFREE.CHART.AXIS 24.33 QuarterDateFormat 24.33.1 Overview 218 A subclass of DateFormat that is used to convert a Date to a String. The default format is “YYYY Q” where “YYYY” is replaced by the year and “Q” is replaced by a symbol representing the quarter (symbols can be defined via the constructor). Any symbols can be used to represent the four quarters in a year, but the following default symbol sets are provided: • REGULAR QUARTERS – the symbols “1”, “2”, “3” and “4”; • ROMAN QUARTERS – the symbols “I”, “II”, “III”, and “IV”; • GREEK QUARTERS – greek symbols (since 1.0.6). 24.33.2 Constructors The following constructors are available: å public QuarterDateFormat(); Equivalent to QuarterDateFormat(TimeZone.getDefault())—see the next constructor. å public QuarterDateFormat(TimeZone zone); Equivalent to QuarterDateFormat(zone, REGULAR QUARTERS)—see the next constructor. å public QuarterDateFormat(TimeZone zone, String[] quarterSymbols); Equivalent to QuarterDateFormat(zone, quarterSymbols, false)—see the next constructor. å public QuarterDateFormat(TimeZone zone, String[] quarterSymbols, boolean quarterFirst); [1.0.6] Creates a new date formatter linked to the specified zone using the supplied symbols for the four quarters (the array should have four entries). The quarterFirst flag controls whether the quarter is displayed before or after the year (for example, “2007-IV” or “IV-2007”). 24.33.3 Methods The format method is overridden to create the formatted version of the given date: å public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition); Returns a string representing the given date. The string contains the year followed by a space followed by the symbol corresponding to the quarter in which the date falls (the symbols are supplied in the constructor). The parse method is overridden but not implemented: å public Date parse(String source, ParsePosition pos); This method has not been implemented, it simply returns null. 24.33.4 Notes Some points to note: • a demo (QuarterDateFormatDemo.java) showing this class being used with a PeriodAxis is included in the JFreeChart demo collection. 24.34 SegmentedTimeline 24.34.1 Overview A segmented timeline for use with a DateAxis. CHAPTER 24. PACKAGE: ORG.JFREE.CHART.AXIS 24.34.2 219 Usage Please refer to the Javadocs. 24.35 StandardTickUnitSource 24.35.1 Overview A TickUnitSource that dynamically creates tick units where the tick size is an integer power of 10, and the number format is DecimalFormat("0.0E0"). The primary advantage of this source is that the tick size is calculated dynamically, so it can handle very large and very small axis ranges (unlike the TickUnits class which contains a finite collection of tick sizes). 24.35.2 Usage To use this TickUnitSource with a NumberAxis, create a new instance and install it as follows: NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis(); TickUnitSource units = new StandardTickUnitSource(); rangeAxis.setStandardTickUnits(units); 24.35.3 Constructor This class has a single constructor: å public StandardTickUnitSource(); Creates a new instance. There are no customisable attributes for this class. 24.35.4 Methods This class implements the three methods defined in the TickUnitSource method. These methods are called by the axis, you won’t normally need to call these methods directly: å public TickUnit getLargerTickUnit(TickUnit unit); Returns the next larger tick unit relative to unit. å public TickUnit getCeilingTickUnit(TickUnit unit); Returns a tick unit that is either equal to unit or the next larger tick unit. å public TickUnit getCeilingTickUnit(double size); Returns a tick unit that is equal in size to size, or the next larger tick unit. 24.35.5 Equals, Cloning and Serialization This class overrides the equals() method:5 å public boolean equals(Object obj); Tests this tick unit source for equality with an arbitrary object. Instances of this class are Serializable but not Cloneable (cloning is unnecessary, since instances of this class are immutable). 24.35.6 Notes Some points to note: • this class is not used by default, but can be installed in an axis if necessary—see SmallNumberDemo.java in the JFreeChart demo collection for an example. 5 Since version 1.0.7. CHAPTER 24. PACKAGE: ORG.JFREE.CHART.AXIS 24.36 SubCategoryAxis 24.36.1 Overview 220 An extension of the CategoryAxis class that allows subcategories to be displayed along the domain axis for a CategoryPlot. This type of axis can be usefully employed along with the GroupedStackedBarRenderer class. 24.36.2 Constructors To create a new instance: å public SubCategoryAxis(String label); Creates a new axis with the specified label (which may be null). 24.36.3 General Attributes To control the font used to display the sub-labels: å public Font getSubLabelFont(); Returns the sub-label font (never null). The default value is Font("SansSerif", Font.PLAIN, 10). å public void setSubLabelFont(Font font); Sets the sub-label font and sends an AxisChangeEvent to all registered listeners. If font is null, this method throws an IllegalArgumentException. å public Paint getSubLabelPaint(); Returns the paint used to draw the sub-labels (never null). The default value is Color.black. å public void setSubLabelPaint(Paint paint); Sets the sub-label paint and sends an AxisChangeEvent to all registered listeners. If paint is null, this method throws an IllegalArgumentException. 24.36.4 Subcategories The subcategories for the axis need to be specified manually. All the subcategories are displayed within each category along the axis. The categories are driven by the content of the dataset, while the subcategories are just arbitrary labels with no formal connection to the dataset. å public void addSubCategory(Comparable subCategory); Adds a subcategory to the axis. 24.36.5 Other Methods The remaining methods are used internally: å public AxisSpace reserveSpace(...); Calculates the amount of space required to draw the axis. This overrides the method defined in the CategoryAxis class, because additional space is required to draw the subcategory labels. å public AxisState draw(...); Overrides the draw() method in the CategoryAxis class to include the sublabels in the axis. å protected AxisState drawSubCategoryLabels(...); Draws the subcategory labels. 24.36.6 Equals, Cloning and Serialization This class overrides the equals() method: å public boolean equals(Object obj); Tests this axis for equality with an arbitrary object. Instances of this class are Cloneable and Serializable. CHAPTER 24. PACKAGE: ORG.JFREE.CHART.AXIS 24.36.7 221 Notes A couple of demos (SubCategoryAxisDemo1.java and StackedBarChartDemo4.java) are included in the JFreeChart demo collection. See Also GroupedStackedBarRenderer. 24.37 SymbolAxis 24.37.1 Overview A ValueAxis that maps integer values (starting at zero) to symbols (strings). This can be used to present: • a CategoryPlot with pseudo-categories displayed along the range axis (y-axis); • an XYPlot with pseudo-categories displayed along the domain axis (x-axis) and/or range axis (y-axis). 24.37.2 Constructors To create a new axis: å public SymbolAxis(String label, String[] sv); Creates a new axis with the specified label. The sv array contains the strings that are displayed along the axis for the integer values. 24.37.3 Attributes To access the symbols used for the integer values along the axis: å public String[] getSymbols(); Returns the symbols used by the axis. These are the symbols that were specified in the constructor. The returned array is a copy, so modifying it will not change the axis. To access the flag that controls whether or not grid bands are painted for alternate tick values: å public boolean isGridBandsVisible(); Returns the flag that controls whether or not the alternating grid bands are drawn for the axis. The default value is true. å public void setGridBandsVisible(boolean flag); Sets the flag that controls whether or not the alternating grid bands are drawn for the axis, and sends an AxisChangeEvent to all registered listeners. To access the grid band paint: å public Paint getGridBandPaint(); Returns the paint used to color alternate bands within the plot area. The default value is Color(232, 234, 232, 128) (a light gray with partial transparency). å public void setGridBandPaint(Paint paint); Sets the paint used to color alternate bands within the plot area, and sends a AxisChangeEvent to all registered listeners. An IllegalArgumentException will be thrown if paint is null. From version 1.0.7 onwards, you can specify the alternate grid band colour as well: å public Paint getGridBandAlternatePaint(); [1.0.7] Returns the paint (never null) used fill alternate bands within the plot area. The default value is Color(0, 0, 0, 0) (that is, completely transparent). See also getGridBandPaint(). å public void setGridBandAlternatePaint(Paint paint); [1.0.7] Sets the paint used to fill alternate bands within the plot area, and sends an AxisChangeEvent to all registered listeners. If paint is null, this method throws an IllegalArgumentException. CHAPTER 24. PACKAGE: ORG.JFREE.CHART.AXIS 24.37.4 222 Other Methods Most of the other methods in this class are used internally: å public String valueToString(double value); Returns the symbol for the given value. The value is rounded to an integer, then the symbol is obtained from the array of symbols defined for the axis. If value is out of range, an empty string is returned. This method is called by the refreshTicks() code. å public AxisState draw(Graphics2D g2, double cursor, Rectangle2D plotArea, Rectangle2D dataArea, RectangleEdge edge, PlotRenderingInfo plotState); Called by the plot to draw the axis. You won’t normally call this method yourself. å protected void autoAdjustRange(); Adjusts the axis range to fit the data. In this case, the axis range is fixed, so this method should not do anything. å public List refreshTicks(Graphics2D g2, AxisState state, Rectangle2D dataArea, RectangleEdge edge); Returns a list of ticks for display on the axis. This method is called by internal code, you won’t normally call it yourself. å protected List refreshTicksHorizontal(Graphics2D g2, Rectangle2D dataArea, RectangleEdge edge); Creates a list of ticks for the axis when it is displayed “horizontally”. That is, at the top or bottom of the plot. å protected List refreshTicksVertical(Graphics2D g2, Rectangle2D dataArea, RectangleEdge edge); Creates a list of ticks for the axis when it is displayed “vertically”. That is, at the left or right of the plot. å protected void drawGridBands(Graphics2D g2, Rectangle2D plotArea, Rectangle2D dataArea, RectangleEdge edge, List ticks); Draws the grid bands. å protected void drawGridBandsHorizontal(Graphics2D g2, Rectangle2D plotArea, Rectangle2D dataArea, boolean firstGridLineIsDark, List ticks); Draws the grid bands for a horizontal axis. å protected void drawGridBandsVertical(Graphics2D g2, Rectangle2D drawArea, Rectangle2D plotArea, boolean firstGridLineIsDark, List ticks); Draws the grid bands for a vertical axis. å protected void selectAutoTickUnit(Graphics2D g2, Rectangle2D dataArea, RectangleEdge edge); Throws an UnsupportedOperationException. 24.37.5 Equals, Cloning and Serialization This class overrides the equals() method: å public boolean equals(Object obj); Tests this axis for equality with an arbitrary object. To be considered equal, obj must be nonnull, an instance of SymbolAxis, have the same list of symbols as this axis, and super.equals(obj) must return true. Instances of this class are Cloneable and Serializable. 24.37.6 Notes Some points to note: • a demo for a CategoryPlot (LineChartDemo8.java) is included in the JFreeChart demo distribution; • a demo for an XYPlot (SymbolAxisDemo1.java) is included in the JFreeChart demo distribution. CHAPTER 24. PACKAGE: ORG.JFREE.CHART.AXIS 24.38 Tick 24.38.1 Overview 223 A utility class representing a tick on an axis. Used temporarily during the drawing process only— you won’t normally use this class yourself. See Also TickUnit. 24.39 TickType 24.39.1 Overview This class defines tokens representing the tick type for an axis (see the NumberTick class). This class was introduced in JFreeChart version 1.0.7. • TickType.MAJOR; • TickType.MINOR; 24.39.2 Notes The TickType tokens are used by the NumberTick class to support major and minor tick marks on the LogAxis class. Eventually, this support will be rolled out to the NumberAxis class also. 24.40 TickUnit 24.40.1 Overview An abstract class representing a tick unit, with subclasses including: • DateTickUnit – for use with a DateAxis; • NumberTickUnit – for use with a NumberAxis. 24.40.2 Constructors The standard constructor: å public TickUnit(double size); Equivalent to TickUnit(size, 0)—see the next constructor. å public TickUnit(double size, int minorTickCount); [1.0.7] Creates a new tick unit with the specified size and minor tick count. 24.40.3 General Methods To get the tick size: å public double getSize(); Returns the size of the tick unit—that is, the gap (in data units) between consecutive tick marks along the axis. The value is specified in the constructor. To get the minor tick count: å public int getMinorTickCount(); Returns the number of minor tick units between consecutive major tick units. To convert a data value to a string: CHAPTER 24. PACKAGE: ORG.JFREE.CHART.AXIS 224 å public String valueToString(double value); Returns a string representing the specified data value. Subclasses may override this method to provide custom formatting. å public int compareTo(Object object); Compares this instance to an arbitrary object. This method is defined by the Comparable interface, and is used to order tick units by size. 24.40.4 Equals, Cloning and Serialization This class overrides the equals() method: å public boolean equals(Object obj); Tests this unit for equality with an arbitrary object. Instances of this class are immutable and Serializable. 24.40.5 Notes Implements the Comparable interface, so that a collection of tick units can be sorted easily using standard Java methods. In particular, the StandardTickUnitSource class makes use of this feature. See Also TickUnits. 24.41 TickUnits 24.41.1 Overview A collection of tick units. This class is used by the DateAxis and NumberAxis classes to store a list of “standard” tick units. The auto-tick-unit-selection mechanism chooses one of the standard tick units in order to maximise the number of ticks displayed without having the tick labels overlap. 24.41.2 Constructors The default constructor: å public TickUnits(); Creates a new collection of tick units, initially empty. 24.41.3 Methods To add a new tick unit to the collection: å public void add(TickUnit unit); Adds the tick unit to the collection. To find the tick unit in the collection that is the next largest in size compared to the specified tick unit: å public TickUnit getLargerTickUnit(TickUnit unit); Returns the tick unit that is one size larger than the specified unit. 24.41.4 Notes The NumberAxis class has a static method createStandardTickUnits() that generates a tick unit collection (of standard tick sizes) for use by numerical axes. See Also TickUnit. CHAPTER 24. PACKAGE: ORG.JFREE.CHART.AXIS 24.42 TickUnitSource 24.42.1 Overview 225 The interface through which a ValueAxis finds a suitable tick unit. Classes that implement this interface include: • TickUnits; • StandardTickUnitSource; 24.42.2 Methods The following methods allow a TickUnit to be obtained from the source: å public TickUnit getLargerTickUnit(TickUnit unit); Returns a tick unit that is larger than the supplied unit. å public TickUnit getCeilingTickUnit(TickUnit unit); Returns a tick unit that is equal to or larger in size than the specified unit. å public TickUnit getCeilingTickUnit(double size); Returns a tick unit with size equal to or larger than the specified size. 24.43 Timeline 24.43.1 Overview The interface that defines the methods for a timeline that can be used with a DateAxis. 24.43.2 Methods The interface declares the following methods: å public long toTimelineValue(long millisecond); Translates a millisecond (as defined by java.util.Date) into an index along this timeline. å public long toTimelineValue(Date date); Translates a Date into an index along the timeline. å public long toMillisecond(long timelineValue); Converts a timeline index back into a millisecond. Note that many timeline index values can map to a single millisecond. å public boolean containsDomainValue(long millisecond); Returns true if the millisecond is contained within the timeline, and false otherwise. å public boolean containsDomainValue(Date date); Returns true if the date is contained within the timeline, and false otherwise. å public boolean containsDomainRange(long fromMillisecond, long toMillisecond); Returns true if the range of millisecond values is contained within the timeline, and false otherwise. å public boolean containsDomainRange(Date fromDate, Date toDate); Returns true if the range of dates is contained within the timeline, and false otherwise. 24.43.3 Notes The SegmentedTimeline class implements this interface. CHAPTER 24. PACKAGE: ORG.JFREE.CHART.AXIS 24.44 ValueAxis 24.44.1 Overview 226 The base class for all axes that display “values”, with the two key subclasses being NumberAxis and DateAxis. At the lowest level, the axis values are manipulated as double primitives, obtained from the Number objects supplied by the plot’s dataset. 24.44.2 Constructors The constructors for this class are protected, you cannot create a ValueAxis directly—you must use a subclass. 24.44.3 Attributes The attributes maintained by this class, in addition to those that it inherits from the Axis class, are listed in Table 24.6. There are methods to read and update most of these attributes. In general, updating an axis attribute will result in an AxisChangeEvent being sent to all (or any) registered listeners. The default values used to initialise the axis attributes (when necessary) are listed in Table 24.7. Attribute: Description: inverted autoRange A flag that is used to “invert” the axis scale. A flag controlling whether or not the axis range is automatically adjusted to fit the range of data values. The default range when there is no data (since 1.0.5). If specified, the auto-range is calculated by subtracting this value from the maximum domain value in the dataset. The smallest axis range allowed when it is automatically calculated. The margin to allow at the lower end of the axis scale (expressed as a percentage of the total axis range). The margin to allow at the upper end of the axis scale (expressed as a percentage of the total axis range). A flag controlling whether or not the tick units are selected automatically. A collection of the “standard” tick units that can be used by this axis. A flag that controls whether or not the tick labels are rotated 90 degrees. A flag that controls whether or not an arrow is drawn at the positive end of the scale. A flag that controls whether or not an arrow is drawn at the negative end of the scale. The shape used to draw an arrow at the end of an axis pointing upwards. The shape used to draw an arrow at the end of an axis pointing downwards. The shape used to draw an arrow at the end of an axis pointing leftwards. The shape used to draw an arrow at the end of an axis pointing rightwards. defaultAutoRange fixedAutoRange autoRangeMinimumSize lowerMargin upperMargin autoTickUnitSelection standardTickUnits verticalTickLabels positiveArrowVisible negativeArrowVisible upArrow downArrow leftArrow rightArrow Table 24.6: Attributes for the ValueAxis class 24.44.4 Usage To modify the attributes of a ValueAxis, you first need to obtain a reference to the axis. For a CategoryPlot, you can use the following code: CHAPTER 24. PACKAGE: ORG.JFREE.CHART.AXIS Name: DEFAULT DEFAULT DEFAULT DEFAULT DEFAULT 227 Value: AUTO RANGE LOWER BOUND UPPER BOUND UPPER MARGIN LOWER MARGIN true; 0.0; [Deprecated, 1.0.5] 1.0; [Deprecated, 1.0.5] 0.05 (5 percent) 0.05 (5 percent) Table 24.7: ValueAxis class default attribute values CategoryPlot plot = (CategoryPlot) chart.getPlot(); ValueAxis rangeAxis = plot.getRangeAxis(); // modify the axis here... The code for an XYPlot is very similar, except that the domain axis is also a ValueAxis in this case: XYPlot plot = (XYPlot) chart.getPlot(); ValueAxis domainAxis = plot.getDomainAxis(); ValueAxis rangeAxis = plot.getRangeAxis(); // modify the axes here... Having obtained an axis reference, you can: • control the axis range, see section 24.44.5; • invert the axis scale, see section 24.44.6; 24.44.5 The Axis Range The axis range defines the highest and lowest values that will be displayed on axis. On a chart, it is typically the case that data values outside the axis range are clipped, and therefore not visible on the chart. Automatic Bounds Calculation By default, JFreeChart is configured to automatically calculate axis ranges so that all of the data in your dataset is visible. It does this by determining the highest and lowest values in your dataset, adding a small margin (to prevent the data being plotted right up to the edge of a chart), and setting the axis range. To control whether or not the axis range is automatically adjusted to fit the available data: å public boolean isAutoRange(); Returns the flag that controls whether the axis range is automatically updated to reflect the data values. å public void setAutoRange(boolean auto); Sets the flag that controls whether or not the axis range is automatically adjusted to fit the available data values, and sends an AxisChangeEvent to all registered listeners. å protected void setAutoRange(boolean auto, boolean notify); An alternative version of the above method that lets you specify whether or not the listeners are notified. When the axis range is calculated automatically, a margin is added to the lower and upper bounds (the default is 0.05 or 5 percent): å public double getLowerMargin(); Returns the lower margin as a percentage of the overall axis length (the default is 0.05 or 5 percent). å public void setLowerMargin(double margin); Sets the lower margin (specified as a percentage of the overall axis length) and sends an AxisChangeEvent to all registered listeners. CHAPTER 24. PACKAGE: ORG.JFREE.CHART.AXIS 228 å public double getUpperMargin(); Returns the upper margin as a percentage of the overall axis length (the default is 0.05 or 5 percent). å public void setUpperMargin(double margin); Sets the upper margin (specified as a percentage of the overall axis length) and sends an AxisChangeEvent to all registered listeners. Note that the margins are only applied when the axis bounds are automatically calculated. If you set the axis bounds manually (see the next section) then the margins are ignored. If the plot has no data, then the auto range is set to the default: å public Range getDefaultAutoRange(); [1.0.5] Returns the default auto range (never null). å public void setDefaultAutoRange(Range range); [1.0.5] Sets the default auto range and sends an AxisChangeEvent to all registered listeners. If range is null, this method throws an IllegalArgumentException. Setting the Range Manually To manually set the axis range (which automatically disables the auto-range flag): å public void setRange(double lower, double upper); Equivalent to setRange(new Range(lower, upper))—see below. å public void setRange(Range range); Equivalent to setRange(range, true, true)—see below. å public void setRange(Range range, boolean turnOffAutoRange, boolean notify); Sets the bounds of the axis so that it will display the range of values specified by range. If notify is true, an AxisChangeEvent is sent to all registered listeners. If turnOffAutoRange is true, the autoRange flag is set to false (which is what you want if you intend to control the axis range manually). To set the lower bound for the axis: å public void setLowerBound(double value); Sets the lower bound for the axis. If the auto-range attribute is true it is automatically switched to false. Registered listeners are notified of the change. To set the upper bound for the axis: å public void setUpperBound(double value); Sets the upper bound for the axis. If the auto-range attribute is true it is automatically switched to false. Registered listeners are notified of the change. 24.44.6 Inverting the Axis Scale There is a flag that can be used to “invert” the axis scale: å public boolean isInverted(); Returns the flag that controls whether or not the axis scale is inverted. å public void setInverted(boolean flag); Sets the flag that controls whether or not the axis scale is inverted and sends an AxisChangeEvent to all registered listeners. CHAPTER 24. PACKAGE: ORG.JFREE.CHART.AXIS 24.44.7 229 Tick Labels Tick labels can be rotated 90 degrees (typically to fit more labels in) by setting the following flag: å public boolean isVerticalTickLabels(); Returns the flag that controls whether or not the tick labels are rotated by 90 degrees. The default value is false. å public void setVerticalTickLabels(boolean flag); Sets the flag that controls whether or not the tick labels are rotated by 90 degrees, and, if the flag value changes, sends a RendererChangeEvent to all registered listeners. For other tick label settings, see section 24.2.7. 24.44.8 Other Methods A key function for a ValueAxis is to convert a data value to an output (Java2D) coordinate for plotting purposes. The output coordinate will be dependent on the area into which the data is being drawn: å public double valueToJava2D(double dataValue, Rectangle2D dataArea, RectangleEdge edge); Converts a data value into a co-ordinate along one edge of the dataArea rectangle. The caller can pass in an arbitrary rectangle, but typically it should match the rectangle defined by the interior of the chart’s axes. The inverse function converts a Java2D coordinate back to a data value: å public double java2DToValue(double java2DValue, Rectangle2D dataArea, RectangleEdge edge); Converts a Java2D coordinate (defined relative to one edge of the specified dataArea) back to a data value. To set a flag that controls whether or not the axis tick units are automatically selected: å public void setAutoTickUnitSelection(boolean flag); Sets a flag (commonly referred to as the auto-tick-unit-selection flag) that controls whether or not the tick unit for the axis is automatically selected from a collection of standard tick units. 24.44.9 Notes Some points to note: • in a CategoryPlot, the range axis is required to be a subclass of ValueAxis. • in an XYPlot, both the domain and range axes are required to be a subclass of ValueAxis. See Also Axis, DateAxis, NumberAxis. 24.45 ValueTick 24.45.1 Overview The base class for the NumberTick and DateTick classes. Instances of these classes are created in the refreshTicks() method of the various axis classes. CHAPTER 24. PACKAGE: ORG.JFREE.CHART.AXIS 24.45.2 Constructors To create a new instance: å public ValueTick(double value, String label, TextAnchor textAnchor, TextAnchor rotationAnchor, double angle); Creates a new tick with the specified value. å public ValueTick(TickType tickType, double value, String label, TextAnchor textAnchor, TextAnchor rotationAnchor, double angle); [1.0.7] Creates a new tick with the specified type and value. 24.45.3 General Methods To get the tick type: å public TickType getTickType(); [1.0.7] Returns the tick type (MAJOR or MINOR). To get the value for the tick: å public double getValue(); Returns the value for this tick. 24.45.4 Equals, Cloning and Serialization This class overrides the equals() method: å public boolean equals(Object obj); Tests this tick for equality with an arbitrary object. 24.45.5 Notes The minor tick type is used only by the LogAxis class at present. See Also DateTick, NumberTick. 230 Chapter 25 Package: org.jfree.chart.block 25.1 Introduction The org.jfree.chart.block package contains classes that are used for laying out rectangular items (blocks) within containers. Primarily, the classes in this package are used by the LegendTitle class. 25.2 AbstractBlock 25.2.1 Overview A base class for implementing a Block, which is used as a layout unit in JFreeChart (particularly for the LegendTitle class). Subclasses include: • BlockContainer; • ColorBlock; • EmptyBlock; • LabelBlock; • LegendGraphic; • Title. 25.2.2 Constructor To create a new block: å protected AbstractBlock(); Creates a new block. 25.2.3 General Attributes The block has an identifier: å public String getID(); Returns the block id. The default value is null. å public void setID(String id); Sets the block id (null is permitted). You can specify the preferred height and width for the block: å public double getHeight(); Returns the block height. 231 CHAPTER 25. PACKAGE: ORG.JFREE.CHART.BLOCK 232 å public void setHeight(double height); Sets the block height. This is a “preferred” height which may or may not be observed by the layout manager. å public double getWidth(); Returns the block width. å public void setWidth(double width); Sets the block width. This is a “preferred” width which may or may not be observed by the layout manager. The margin is the space around the outside of the block’s border: å public RectangleInsets getMargin(); Returns the margin around the outside of the block’s border. The default value is RectangleInsets.ZERO INSETS. å public void setMargin(RectangleInsets margin); Sets the margin around the outside of the block’s border. You can specify a frame (or border) for the block: å public BlockFrame getFrame(); [1.0.5] Returns the border that will be drawn around the block. The default value is BlockBorder.NONE. å public void setFrame(BlockFrame frame); [1.0.5] Sets the border that will be drawn around the block. If frame is null, this method throws an IllegalArgumentException. The padding is an area of whitespace inside the block’s frame: å public RectangleInsets getPadding(); Returns the padding between the block’s content and its border. The default value is RectangleInsets.ZERO INSETS. å public void setPadding(RectangleInsets padding); Sets the padding between the block’s content and its border. If padding is null, this method throws an IllegalArgumentException. 25.2.4 Layout For layout purposes, a block can be asked to arrange itself subject to some constraint, and return the space required by the block: å public Size2D arrange(Graphics2D g2); Arranges the block without constraint, and returns its size. Keep in mind that the block may be a BlockContainer that contains other blocks. å public Size2D arrange(Graphics2D g2, RectangleConstraint constraint); Arranges the block subject to the specified constraint and returns its size. Keep in mind that the block may be a BlockContainer that contains other blocks. To control the current bounds for the block: å public Rectangle2D getBounds(); Returns the bounds for the block. å public void setBounds(Rectangle2D bounds); Sets the bounds for the block. This method is often called by a layout manager. The following utility methods are provided for subclasses to use: å protected double trimToContentWidth(double fixedWidth); Reduces the given width to account for the margin, border and padding. å protected double trimToContentHeight(double fixedHeight); Reduces the given height to account for the margin, border and padding. CHAPTER 25. PACKAGE: ORG.JFREE.CHART.BLOCK 233 å protected RectangleConstraint toContentConstraint(RectangleConstraint c); Translates a bounds constraint into a content constraint. å protected double calculateTotalWidth(double contentWidth); Calculates the bounds width from the content width. å protected double calculateTotalHeight(double contentHeight); Calculates the bounds height from the content height. å protected Rectangle2D trimMargin(Rectangle2D area); Trims the block’s margin from area. å protected Rectangle2D trimBorder(Rectangle2D area); Trims the block’s border from area. å protected Rectangle2D trimPadding(Rectangle2D area); Trims the block’s padding from area. 25.2.5 Drawing This class is abstract, so it doesn’t have a draw() method implemented. However, it does provide a method to draw the current border/frame: å protected void drawBorder(Graphics2D g2, Rectangle2D area); Draws the border for the block. 25.2.6 Equals, Cloning and Serialization To test a block for equality with an arbitrary object: å public boolean equals(Object obj); Returns true if this block is equal to obj, and false otherwise. Instances of this class are Cloneable and Serializable. 25.2.7 Notes Some points to note: • the get/setBorder() methods have been deprecated in favour of the get/setFrame() methods; 25.3 Arrangement 25.3.1 Overview A layout manager that can arrange blocks. 25.3.2 Methods This interface defines the following methods: å public void add(Block block, Object key); Adds a block to the layout, with the specified key. The layout manager has an opportunity to record the key associated with any block (or it can choose to ignore this information). å public void arrange(BlockContainer container, RectangleConstraint constraint, Graphics2D g2); Arranges the blocks within the given container, subject to the specified constraint. å public void clear(); Clears any cached layout information. CHAPTER 25. PACKAGE: ORG.JFREE.CHART.BLOCK 25.3.3 234 Notes Some points to note: • classes that implement this interface include: – BorderArrangement; – CenterArrangement; – ColumnArrangement; – FlowArrangement; and – GridArrangement. 25.4 Block 25.4.1 Overview This interface defines methods that allow a rectangular graphical object (referred to generically as a “block”) to: • identify itself; • provide information about its size, perhaps subject to an external constraint; • set its bounds. Some blocks draw their own content, while other blocks act as containers for yet more blocks. 25.4.2 Methods To access the block’s ID: å public String getID(); Returns the ID for the block (depending on the application, this might be null). å public void setID(String id); Sets the id for the block. To layout the contents of the block: å public Size2D arrange(Graphics2D g2); Arranges the block without any constraints and returns the block size. å public Size2D arrange(Graphics2D g2, RectangleConstraint constraint); Arranges the block, subject to the given constraint, and returns the resulting size. To access the current bounds for the block: å public Rectangle2D getBounds(); Gets the bounds for the block. å public void setBounds(Rectangle2D bounds); Sets the bounds for the block. 25.5 BlockBorder 25.5.1 Overview A simple border that can be assigned to any subclass of AbstractBlock (via that class’s setFrame() method). This class implements the BlockFrame interface. CHAPTER 25. PACKAGE: ORG.JFREE.CHART.BLOCK 25.5.2 235 Constructors There are two constructors: å public BlockBorder(); Equivalent to BlockBorder(Color.black)—see below. å public BlockBorder(Paint paint); Equivalent to BlockBorder(new RectangleInsets(1, 1, 1, 1), paint)—see below. å public BlockBorder(double top, double left, double bottom, double right); Equivalent to BlockBorder((new RectangleInsets(top, left, bottom, right), Color.black))— see below. å public BlockBorder(double top, double left, double bottom, double right, Paint paint); Equivalent to BlockBorder((new RectangleInsets(top, left, bottom, right), paint))—see be- low. å public BlockBorder(RectangleInsets insets, Paint paint); Creates a new block border using the specified insets and paint. If insets or paint is null, this constructor throws an IllegalArgumentException. 25.5.3 General Attributes The following read-only attributes are defined: å public RectangleInsets getInsets(); Returns the insets that define the available drawing space for the border (never null). å public Paint getPaint(); Returns the paint that is used to draw the border. The initial value is specified in the constructor for this class. This method never returns null. 25.5.4 Other Methods JFreeChart calls the following method to draw the border: å public void draw(Graphics2D g2, Rectangle2D area); Draws the border around the edges of the specified area, always staying within the area. 25.5.5 Equals, Cloning and Serialization This class overrides the equals() method: å public boolean equals(Object obj); Tests this border for equality with an arbitrary object. See Also BlockFrame. 25.6 BlockContainer 25.6.1 Overview A container for blocks that uses an Arrangement to organise the layout of the blocks. The container is itself a Block, which makes it possible to nest block containers to arbitrary levels. CHAPTER 25. PACKAGE: ORG.JFREE.CHART.BLOCK 25.6.2 Constructors To create a new container: å public BlockContainer(); Creates a new container using a BorderArrangement. å public BlockContainer(Arrangement arrangement); Creates a new container using the specified arrangement. 25.6.3 Methods To get or set the layout manager: å public Arrangement getArrangement(); Returns the object responsible for the block layout. å public void setArrangement(Arrangement arrangement); Sets the object responsible for the block layout. To check if the container has an content: å public boolean isEmpty(); Returns true if the container is empty (contains no blocks), and false otherwise. To get a list of the blocks within the container: å public List getBlocks(); Returns an unmodifiable list of the blocks in the container. To add a block: å public void add(Block block); Adds a block to the container. å public void add(Block block, Object key); Adds a block to the container along with the given key (which is intended for the use of the layout manager). To remove all blocks from the container: å public void clear(); Clears all the blocks in the container. To arrange the blocks within the container (this will set the bounds for all the blocks): å public Size2D arrange(Graphics2D g2, RectangleConstraint constraint); Arranges the blocks in the container, subject to the specified constraint. To draw the contents of the container: å public void draw(Graphics2D g2, Rectangle2D area); Draws the blocks within the specified area. 25.6.4 Equals, Cloning and Serialization This class overrides the equals() method: å public boolean equals(Object obj); Returns true if this container is equal to obj and false otherwise. This class is Cloneable and Serializable. 236 CHAPTER 25. PACKAGE: ORG.JFREE.CHART.BLOCK 25.7 BlockFrame 25.7.1 Overview 237 An interface that defines the API for a border that can be assigned to any AbstractBlock (via that class’s setFrame() method). This interface is implemented by: • BlockBorder; • LineBorder. 25.7.2 Interface Methods This interface defines two methods: å public RectangleInsets getInsets(); [1.0.5] Returns the space used to draw the frame. å public void draw(Graphics2D g2, Rectangle2D area); [1.0.5] Draws the frame within the specified area. 25.7.3 Notes This interface was introduced in JFreeChart version 1.0.5. See Also AbstractBlock. 25.8 BlockParams 25.8.1 Overview A carrier for the (optional) parameters passed to a Block in its draw() method. 25.8.2 Methods To access the flag that controls whether or not entities are being generated: å public boolean getGenerateEntities(); Returns true if entities should be generated. å public void setGenerateEntities(boolean generate); Sets the flag that controls whether or not entities are generated. The translation from the local coordinates of the block to the container’s coordinates: å public double getTranslateX(); Returns the x-translation. å public void setTranslateX(double x); Sets the x-translation. å public double getTranslateY(); Returns the y-translation. å public void setTranslateY(double y); Sets the y-translation. 25.9 BlockResult 25.9.1 Overview A carrier for the result from the draw() method in the BlockContainer class. CHAPTER 25. PACKAGE: ORG.JFREE.CHART.BLOCK 25.9.2 238 Methods å public EntityCollection getEntityCollection(); Returns the entity collection from the block drawing. å public void setEntityCollection(EntityCollection entities); Sets the entity collection. 25.10 BorderArrangement 25.10.1 Overview A layout manager (Arrangement) that is similar to the BorderLayout class in AWT. 25.10.2 Constructor To create a new instance: å public BorderArrangement(); Creates a new layout manager. 25.10.3 Methods The layout manager records the “key” for each block in the following method, which is usually called by the BlockContainer: å public void add(Block block, Object key); Records the block and its key (valid keys are defined by the RectangleEdge class). å public Size2D arrange(BlockContainer container, RectangleConstraint constraint, Graphics2D g2); Arranges the blocks within the container, subject to the given constraint, and returns the overall size of the container. å public void clear(); Clears any cached layout information. 25.11 CenterArrangement 25.11.1 Overview An Arrangement that places a single block at the center of its container. 25.12 ColorBlock 25.12.1 Overview A simple block that is filled with a color. This is a useful class for visual testing of layout classes. 25.12.2 Constructor To create a new block: å public ColorBlock(Paint paint, double width, double height); Creates a new block with the specified “preferred” dimensions. If paint is null, this method throws an IllegalArgumentException. CHAPTER 25. PACKAGE: ORG.JFREE.CHART.BLOCK 25.12.3 239 Methods To get the color for the block: å public Paint getPaint(); [1.0.5] Returns the paint specified in the constructor. This is never null. To draw the block: å public void draw(Graphics2D g2, Rectangle2D area); Draws the block inside the given area. 25.12.4 Equals, Cloning and Serialization This class overrides the equals() method: å public boolean equals(Object obj); Tests this ColorBlock for equality with an arbitrary object. Instances of this class are Cloneable and Serializable. 25.13 ColumnArrangement 25.13.1 Overview An Arrangement that lays out the blocks in a container into columns. This is the “vertical” equivalent of the FlowArrangement class. 25.13.2 Constructors å public ColumnArrangement(); Creates a new arrangement. å public ColumnArrangement(HorizontalAlignment hAlign, VerticalAlignment vAlign, double hGap, double vGap); Creates a new arrangement with the specified horizontal and vertical alignments and gaps. 25.13.3 Methods To arrange the blocks within a container: å public void arrange(BlockContainer container, RectangleConstraint constraint, Graphics2D g2); Arranges the blocks in container, subject to the given constraint. To add a block to the layout: å public void add(Block block, Object key); Adds a block to the layout. The key is ignored. To clear the blocks: å public void clear(); Clears any cached information. In this case, the method does nothing. 25.13.4 Equals, Cloning and Serialization This class overrides the equals() method: å public boolean equals(Object obj); Tests this arrangement for equality with an arbitrary object. This class is immutable, so it doesn’t need to be Cloneable. CHAPTER 25. PACKAGE: ORG.JFREE.CHART.BLOCK 25.14 EmptyBlock 25.14.1 Overview 240 An empty block, which can be useful for inserting fixed amounts of white space into a layout. å public EmptyBlock(double width, double height); Creates a new empty block with the specified “preferred” dimensions. 25.14.2 Methods To draw the block: å public void draw(Graphics2D g2, Rectangle2D area); Draws the block (since the block is empty, this does nothing). å public Object clone() throws CloneNotSupportedException; Returns a clone of the block. 25.15 EntityBlockParams 25.15.1 Overview To be documented. 25.16 EntityBlockResult 25.16.1 Overview To be documented. 25.17 FlowArrangement 25.17.1 Overview An Arrangement that lays out blocks horizontally from left to right (with wrapping if necessary). 25.17.2 Constructors To create a new arrangement: å public FlowArrangement(); Creates a new arrangement with default settings. å public FlowArrangement(HorizontalAlignment hAlign, VerticalAlignment vAlign, double hGap, double vGap); Creates a new arrangement with the given alignment and gap settings. 25.17.3 Methods To perform an arrangement on a container: å public void arrange(BlockContainer container, RectangleConstraint constraint, Graphics2D g2); Arranges the blocks in the specified container according to the given constraint. The following methods are also defined: å public void add(Block block, Object key); Adds a block to the arrangement. This method does nothing. å public void clear(); Clears any cached information held by this instance. CHAPTER 25. PACKAGE: ORG.JFREE.CHART.BLOCK 25.17.4 241 Equals, Cloning and Serialization å public boolean equals(Object obj); Tests this arrangement for equality with an arbitrary object. 25.18 GridArrangement 25.18.1 Overview A layout manager (Arrangement) that places blocks within a fixed size grid. 25.18.2 Constructor To create a new instance: å public GridArrangement(int rows, int columns); Creates a new instance with the specified number of rows and columns. 25.18.3 Methods å public void add(Block block, Object key); Adds a block to the layout. This method does nothing, because the grid layout doesn’t require any information about the blocks. å public Size2D arrange(BlockContainer container, RectangleConstraint constraint, Graphics2D g2); Arranges the blocks in the specified container subject to the given constraint. See Also FlowArrangement 25.19 LabelBlock 25.19.1 Overview A label that can be incorporated into a block layout. For example, the series labels in a LegendTitle are displayed using instances of this class. 25.19.2 Constructors To create a new instance: å public LabelBlock(String text); Creates a new label block with the given (non-null) text and a default font (Sans Serif, PLAIN, 10) and color (black). å public LabelBlock(String text, Font font); Creates a new label block with the specified text, font and a default color (black). Both text and font should be non-null. å public LabelBlock(String text, Font font, Paint paint); Creates a new label block with the specified text, font and paint (all of which must be nonnull). CHAPTER 25. PACKAGE: ORG.JFREE.CHART.BLOCK 25.19.3 242 Attributes To get/set the font used for the label: å public Font getFont(); Returns the font used for the label (never null). å public void setFont(Font font); Sets the font for the label (null is not permitted). To get/set the paint used for the label text: å public Paint getPaint(); Returns the paint used for the label text (never null). The default value is Color.BLACK. å public void setPaint(Paint paint); Sets the paint for the label text (null is not permitted). To get/set the tooltip text for the label (if any): å public String getToolTipText(); Returns the tooltip text (possibly null). å public void setToolTipText(String text); Sets the tooltip text (null permitted). To get/set the URL text for the label (if any): å public String getURLText(); Returns the URL text for the label block. This may be null. å public void setURLText(String text); Sets the tooltip text (null permitted). 25.19.4 Other Methods The following methods are used by the layout and drawing mechanism in JFreeChart. You won’t normally call them yourself. å public Size2D arrange(Graphics2D g2, RectangleConstraint constraint); Fits the label block to the specified constraints, and returns the dimensions. å public void draw(Graphics2D g2, Rectangle2D area); Draws the label within the specified area. å public Object draw(Graphics2D g2, Rectangle2D area, Object params); Draws the label within the specified area. 25.19.5 Equals, Cloning and Serialization To test an instance for equality with an arbitrary object: å public boolean equals(Object obj); Tests this instance for equality with obj. Returns true if and only if: • obj is not null; • obj is an instance of LabelBlock; • each field in this instance is the same as the corresponding field in obj. Instances of this class are Cloneable and Serializable. 25.19.6 Notes Some points to note: • this class implements the Block interface, and thus supports margins, borders and padding as do all blocks. CHAPTER 25. PACKAGE: ORG.JFREE.CHART.BLOCK 25.20 LengthConstraintType 25.20.1 Overview 243 This class defines three constraint types: • LengthConstraintType.NONE; • LengthConstraintType.FIXED; • LengthConstraintType.RANGE; These types are used when creating RectangleConstraint instances. 25.20.2 Methods The following methods are implemented: å public String toString(); Returns a string representation of the instance, primarily used for debugging. å public boolean equals(Object obj); Tests this instance for equality with an arbitrary object. å public int hashCode(); Returns a hash code for the instance. 25.21 LineBorder 25.21.1 Overview A simple border that can be assigned to any subclass of AbstractBlock (via that class’s setFrame() method). This class implements the BlockFrame interface. 25.21.2 Constructors There are two constructors: å public LineBorder(); Equivalent to LineBorder(Color.black, new BasicStroke(1.0f), new RectangleInsets(1.0, 1.0, 1.0, 1.0))—see the next constructor. å public LineBorder(Paint paint, Stroke stroke, RectangleInsets insets); Creates a new line border using the specified paint, stroke and insets. The insets deter- mines how much space is reserved for the border (but note that the border is drawn regardless of the size of the insets). If any of the arguments is null, this constructor throws an IllegalArgumentException. 25.21.3 General Attributes The following read-only attributes are defined: å public Paint getPaint(); [1.0.5] Returns the paint that is used to draw the border. The initial value is specified in the constructor for this class. This method never returns null. å public Stroke getStroke(); [1.0.5] Returns the stroke that is used to draw the border. The initial value is specified in the constructor for this class. This method never returns null. å public RectangleInsets getInsets(); [1.0.5] Returns the insets that define the drawing space reserved for the border (never null). CHAPTER 25. PACKAGE: ORG.JFREE.CHART.BLOCK 25.21.4 244 Other Methods JFreeChart calls the following method to draw the border: å public void draw(Graphics2D g2, Rectangle2D area); Draws the border around the edges of the specified area, always staying within the area. 25.21.5 Equals, Cloning and Serialization This class overrides the equals() method: å public boolean equals(Object obj); Tests this border for equality with an arbitrary object. Instances of this class are immutable (so this class doesn’t implement Cloneable) and Serializable. See Also BlockFrame. 25.22 RectangleConstraint 25.22.1 Overview A specification of the constraints that a rectangular shape must meet. For each dimension (width and height) there are three possible constraints: NONE, FIXED and RANGE—refer to the constant class LengthConstraintType. These constraints are used by the layout code implemented by JFreeChart. 25.22.2 Constructors There are several constructors: å public RectangleConstraint(double w, double h); Creates a new constraint where both the width and height are fixed at the given dimensions. å public RectangleConstraint(Range w, Range h); Creates a new constraint where the width and height must fall within the given ranges. å public RectangleConstraint(double w, Range widthRange, LengthConstraintType widthConstraintType, double h, Range heightRange, LengthConstraintType heightConstraintType); Creates a new constraint with the specified attributes (this method gives you full control over all attributes). Note that the width and height ranges may be specified as null. 25.22.3 Accessor Methods To access the attributes of this class: å public double getWidth(); Returns the fixed width. å public Range getWidthRange(); Returns the width range (possibly null). å public LengthConstraintType getWidthConstraintType(); Returns the width constraint type (never null). å public double getHeight(); Returns the fixed height. å public Range getHeightRange(); Returns the height range (possibly null). å public LengthConstraintType getHeightConstraintType(); Returns the height constraint type (never null). CHAPTER 25. PACKAGE: ORG.JFREE.CHART.BLOCK 25.22.4 Other Methods Other methods include: å public RectangleConstraint toUnconstrainedWidth(); Returns a new instance with the same height constraint and NO width constraint. å public RectangleConstraint toUnconstrainedHeight(); Returns a new instance with the same width constraint and NO height constraint. å public RectangleConstraint toFixedWidth(double width); Returns a new instance with the same height constraint and a FIXED width constraint. å public RectangleConstraint toFixedHeight(double height); Returns a new instance with the same width constraint and a FIXED height constraint. å public Size2D calculateConstrainedSize(Size2D base); Applies the constraint to the supplied dimensions and returns the “constrained” dimensions. å public String toString(); Returns a string representing this class, primarily for debugging purposes. 245 Chapter 26 Package: org.jfree.chart.editor 26.1 Introduction This package contains a framework for editing chart properties. At present, the implementation is incomplete. The API is minimalistic, in the hope that it will be possible to plug in a more complete implementation later on without requiring major changes to the API. 26.2 ChartEditor 26.2.1 Overview An interface that defines the API that needs to be supported by a chart editor. A chart editor should be a subclass of JComponent. 26.2.2 Methods This interface defines a single method: å public void updateChart(JFreeChart chart); Applies the updates that the user has made via the chart editor to the given chart. 26.2.3 Notes To obtain a chart editor, use the getChartEditor() method in the ChartEditorManager class. 26.3 ChartEditorFactory 26.3.1 Overview An interface that defines the API that needs to be supported by a chart editor factory, a class that creates new instances of ChartEditor. The ChartEditorManager class maintains a factory for creating new editors—you can replace the default factory with your own custom factory if you want to install your own chart editor. 26.3.2 Methods This interface defines a single method: å public ChartEditor createEditor(JFreeChart chart); Creates a new editor for the given chart. 246 CHAPTER 26. PACKAGE: ORG.JFREE.CHART.EDITOR 26.3.3 247 Notes The DefaultChartEditorFactory class provides the default implementation of this interface. 26.4 ChartEditorManager 26.4.1 Overview This class is the central source for new ChartEditor instances. You can use the default chart editor (which is incomplete at this time) or install your own ChartEditorFactory class to return your own custom chart editor. 26.4.2 Methods This class defines several static methods: å public static ChartEditorFactory getChartEditorFactory(); Returns the current chart editor factory. å public static void setChartEditorFactory(ChartEditorFactory f); Sets the chart editor factory. This allows you to install a custom chart editor implementation, since the getChartEditor() method will return an editor created by the installed factory. å public static ChartEditor getChartEditor(JFreeChart chart); Returns a chart editor for the given chart. The editor is created by the installed chart editor factory (which you can change via the setChartEditorFactory() method. 26.4.3 Notes This package contains default implementations of ChartEditorFactory and ChartEditor. These classes are not publicly visible and are subject to change. 26.5 DefaultAxisEditor 26.5.1 Overview A panel for editing the properties of an axis. The code for this panel is out of date. Many features are missing, and some of the existing features may not work. It is planned to rewrite this class. 26.6 DefaultChartEditor 26.6.1 Overview A panel that displays all the properties of a chart, and allows the user to edit the properties. The panel uses a JTabbedPane to display three sub-panels: • a DefaultTitleEditor; • a DefaultPlotEditor; • a panel containing “other” properties (such as the anti-alias setting and the background paint for the chart). The constructors for this class require a reference to a Dialog or a Frame. Whichever one is specified is passed on to the DefaultTitleEditor and is used if and when a sub-dialog is required for editing titles. CHAPTER 26. PACKAGE: ORG.JFREE.CHART.EDITOR 26.6.2 248 Notes This class is not publicly visible and its API is subject to change. 26.7 DefaultChartEditorFactory 26.7.1 Overview A default factory used by the ChartEditorManager class. 26.7.2 Constructors To create a new instance: å public DefaultChartEditorFactory(); Creates a new factory instance. 26.7.3 Methods To create a new chart editor: å public ChartEditor createEditor(JFreeChart chart); Creates a new editor for the given chart. 26.7.4 Notes The ChartEditorManager class installs an instance of this class as the default chart editor factory. 26.8 DefaultColorBarEditor 26.8.1 Overview A panel for editing the properties of a ColorBar. This class is deprecated as of version 1.0.4. CHAPTER 26. PACKAGE: ORG.JFREE.CHART.EDITOR 26.9 DefaultNumberAxisEditor 26.9.1 Overview 249 A panel for displaying and editing the properties of a NumberAxis. 26.10 DefaultPlotEditor 26.10.1 Overview A panel for displaying and editing the properties of a plot. Figure 26.1: The plot property editor The code for this panel is out of date. Many features are missing, and some of the existing features may not work. It is planned to rewrite this class. 26.11 DefaultTitleEditor 26.11.1 Overview A panel for displaying and editing the properties of a chart title. The code for this panel is out of date. Many features are missing, and some of the existing features may not work. It is planned to rewrite this class. 26.12 PaletteChooserPanel 26.12.1 Overview A panel for selecting a color palette. This class is deprecated as of version 1.0.4. CHAPTER 26. PACKAGE: ORG.JFREE.CHART.EDITOR 26.13 PaletteSample 26.13.1 Overview This class is deprecated as of version 1.0.4. 250 Chapter 27 Package: org.jfree.chart.encoders 27.1 Introduction The org.jfree.chart.encoders package provides a mechanism to allow encoders from Java’s Image IO framework to be used where they are available (JDK 1.4 onwards) while ensuring that alternative encoders are provided as a fallback in other cases (that is, on JDK 1.3). This mechanism is employed by several methods in the ChartUtilities class, for example writeChartAsPNG() and writeChartAsJPEG(). 27.2 EncoderUtil 27.2.1 Overview A utility class containing static methods for encoding images in several formats (PNG and JPEG are supported in most cases). The methods in this class are called by the ChartUtilities class, and make use of encoders pre-configured in the ImageEncoderFactory class. 27.2.2 Methods To encode an image: å public static byte[] encode(BufferedImage image, String format); Returns a byte array containing an encoded version of the image in the specified format. å public static byte[] encode(BufferedImage image, String format, boolean encodeAlpha) throws IOException; Returns a byte array containing an encoded version of the image in the specified format. The encodeAlpha flag determines whether or not an alpha channel is included in the encoded image (assuming the format supports this). å public static byte[] encode(BufferedImage image, String format, float quality) throws IOException; Returns a byte array containing an encoded version of the image in the specified format. The quality argument controls the image quality (for encoders that support this). å public static byte[] encode(BufferedImage image, String format, float quality, boolean encodeAlpha); Returns a byte array containing an encoded version of the image in the specified format. The encodeAlpha flag determines whether or not an alpha channel is included in the encoded image (assuming the format supports this). The quality argument controls the image quality (for encoders that support this). To write an image to an output stream: 251 CHAPTER 27. PACKAGE: ORG.JFREE.CHART.ENCODERS 252 å public static void writeBufferedImage(BufferedImage image, String format, OutputStream outputStream) throws IOException; Writes an image to the given output stream in the specified format. å public static void writeBufferedImage(BufferedImage image, String format, OutputStream outputStream, float quality) throws IOException; Writes an image to the given output stream in the specified format. å public static void writeBufferedImage(BufferedImage image, String format, OutputStream outputStream, boolean encodeAlpha) throws IOException; Writes an image to the given output stream in the specified format. å public static void writeBufferedImage(BufferedImage image, String format, OutputStream outputStream, float quality, boolean encodeAlpha) throws IOException; Writes an image to the given output stream in the specified format. See Also ChartUtilities. 27.3 ImageEncoderFactory 27.3.1 Overview A factory class for image encoders. The static initialisation code in this class checks if we are running on JRE 1.4.2 or later. If yes, then the following encoders are pre-configured: • “png”: org.jfree.chart.encoders.SunPNGEncoderAdapter; • “jpeg”: org.jfree.chart.encoders.SunJPEGEncoderAdapter; Otherwise, JRE 1.3.1 must be the runtime. In that case, Java’s ImageIO library is not available and we register the KeyPoint PNG encoder: • “png”: org.jfree.chart.encoders.KeypointPNGEncoderAdapter; 27.3.2 Methods The following method is used to register an encoder with the factory (note that JFreeChart preinstalls PNG and JPEG encoders): å public static void setImageEncoder(String format, String imageEncoderClassName); Adds a mapping between a format name (for example, “png”) and an encoder class name (for example, “org.jfree.chart.encoders.SunPNGEncoderAdapter”). Use the following methods to obtain an encoder: å public static ImageEncoder newInstance(String format); Returns a new instance of an encoder for the given format. å public static ImageEncoder newInstance(String format, float quality); Returns a new instance of the encoder for the given format and the specified quality setting (in the range 0.0f (lowest quality) to 1.0f (highest quality). å public static ImageEncoder newInstance(String format, boolean encodingAlpha); Returns a new instance of the encoder for the given format and the specified encodeAlpha flag. å public static ImageEncoder newInstance(String format, float quality, boolean encodingAlpha); Returns a new instance of the encoder for the given format and the specified quality and encodeAlpha flag settings. See Also EncoderUtil. CHAPTER 27. PACKAGE: ORG.JFREE.CHART.ENCODERS 27.4 ImageEncoder 27.4.1 Overview 253 An interface that provides an abstract view of the image encoders supported by this package. Classes that implement this interface include: • KeypointPNGEncoderAdapter; • SunJPEGEncoderAdapter; • SunPNGEncoderAdapter. 27.4.2 Methods To encode an image: å public byte[] encode(BufferedImage bufferedImage) throws IOException; Returns a byte array containing an encoded version of the given image. å public void encode(BufferedImage bufferedImage, OutputStream outputStream) throws IOException; Writes an encoded version of an image to the given output stream. To control the quality for the encoding (typically there is a trade-off between image size and quality): å public float getQuality(); Returns the image quality setting. å public void setQuality(float quality); Sets the quality. Note that some encoders ignore the quality setting. To control whether or not the encoding should support an alpha-transparency channel: å public boolean isEncodingAlpha(); Returns the flag that controls whether or not the alpha channel is encoded with the image (note that some encoders ignore this setting). å public void setEncodingAlpha(boolean encodingAlpha); Sets the flag that controls whether or not the alpha channel is encoded with the image. See Also ImageEncoderFactory. 27.5 ImageFormat 27.5.1 Overview An interface that defines string constants used to identify several common image formats: • ImageFormat.PNG for the PNG format, • ImageFormat.JPEG for the JPEG format, • ImageFormat.GIF for the GIF format. You can use these constants in the methods provided by the EncoderUtil class. 27.6 KeyPointPNGEncoderAdapter 27.6.1 Overview An adapter for the com.keypoint.PNGEncoder included in the JCommon distribution. This adapter will be used when JFreeChart is compiled or run with JDK/JRE 1.3.1 (in this case, the ImageIO framework is not available). CHAPTER 27. PACKAGE: ORG.JFREE.CHART.ENCODERS 27.6.2 254 Methods To set the image quality: å public float getQuality(); Returns the quality setting for the encoder. The default value is 9. å public void setQuality(float quality); Sets the quality setting for the encoder. Since PNG is a “lossless” format, the image is always encoded without loss of quality. This setting in fact controls the amount of compression achieved. The underlying encoder uses integer codes as follows: • 0 – no compression, • 1 – best speed, • 9 – best compression. Note that any value between 1 and 9 is also permitted. To set the flag that controls whether or not the alpha channel is encoded: å public boolean isEncodingAlpha(); Returns the flag that controls whether or not the alpha channel is included in the encoded image. å public void setEncodingAlpha(boolean encodingAlpha); Sets the flag that controls whether or not the alpha channel is included in the encoded image. To encode an image to a byte array: å public byte[] encode(BufferedImage bufferedImage) throws IOException; Returns a byte array containing an encoded version of the given image. The encoding uses the current quality and encodeAlpha settings. To write an encoded version of an image to an output stream: å public void encode(BufferedImage bufferedImage, OutputStream outputStream) throws IOException; Writes a byte array (containing an encoded version of the given image) to the specified output stream. The encoding uses the current quality and encodeAlpha settings. Note that the entire image is encoded to a byte array first, before writing the bytes to the output stream—for large images this can use a lot of memory. See Also SunPNGEncoderAdapter. 27.7 SunJPEGEncoderAdapter 27.7.1 Overview An encoder for the JPEG image file format that uses Java’s ImageIO framework to perform the encoding. This encoder is only available when JFreeChart is compiled and run using JDK/JRE 1.4.2 or later. The Ant build script excludes it from the build when using JDK 1.3.1, in which case the methods that write charts to JPEG format will throw exceptions. Since JPEG is such a rotten format for charts, this is no great loss. 27.7.2 Methods The quality setting is ignored by this encoder: å public float getQuality(); Returns the quality setting. å public void setQuality(float quality); Sets the quality setting. CHAPTER 27. PACKAGE: ORG.JFREE.CHART.ENCODERS 255 The alpha encoding flag is ignored by this encoder: å public boolean isEncodingAlpha(); Returns false always. å public void setEncodingAlpha(boolean encodingAlpha); Any value passed to this method is ignored. To encode an image: å public byte[] encode(BufferedImage bufferedImage) throws IOException; Returns a byte array containing a version of the given image encoded in JPEG format by Java’s ImageIO framework. å public void encode(BufferedImage bufferedImage, OutputStream outputStream) throws IOException; Writes an image to the given output stream (in JPEG format) using Java’s ImageIO framework. 27.8 SunPNGEncoderAdapter 27.8.1 Overview An encoder for the PNG image file format that uses Java’s ImageIO framework to perform the encoding. This encoder is only available when JFreeChart is compiled and run using JDK/JRE 1.4.2 or later. The Ant build script excludes it from the build when using JDK 1.3.1, in which case the KeypointPNGEncoderAdapter is used instead. 27.8.2 Methods The quality setting is ignored by this encoder: å public float getQuality(); Returns 0.0f always, the encoder does not support the quality setting. å public void setQuality(float quality); Any value passed to this method is ignored, the encoder does not support the quality setting. The alpha encoding flag is ignored by this encoder: å public boolean isEncodingAlpha(); Returns false always. å public void setEncodingAlpha(boolean encodingAlpha); Any value passed to this method is ignored. To encode an image: å public byte[] encode(BufferedImage bufferedImage) throws IOException; Returns a byte array containing a version of the given image encoded in PNG format by Java’s ImageIO framework. å public void encode(BufferedImage bufferedImage, OutputStream outputStream) throws IOException; Writes an image to the given output stream (in PNG format) using Java’s ImageIO framework. See Also KeypointPNGEncoderAdapter. Chapter 28 Package: org.jfree.chart.entity 28.1 Introduction The org.jfree.chart.entity package contains classes that represent entities in a chart. Entities provide information about the physical location of items in a chart that has been drawn, as well as optional data such as tool tip text and URL strings. 28.2 Background Recall that when you render a chart to a Graphics2D using the draw() method in the JFreeChart class, you have the option of supplying a ChartRenderingInfo object to collect information about the chart’s dimensions. Most of this information is represented in the form of ChartEntity objects, stored in an EntityCollection. You can use the entity information in any way you choose. For example, the ChartPanel class makes use of the information for: • displaying tool tips; • handling chart mouse events. It is more than likely that other applications for this information will be found. 28.3 CategoryItemEntity 28.3.1 Overview This class is used to convey information about an item within a category plot. The information captured includes the dataset containing the item, the series and category identifying the item, area occupied by the item (at the time the chart was rendered), and the tool tip and URL text (if any) generated for the item. 28.3.2 Constructors To construct a new instance: å public CategoryItemEntity(Shape area, String toolTipText, String urlText, CategoryDataset dataset, Comparable rowKey, Comparable columnKey); [1.0.6] Creates a new entity instance. The original constructor has been deprecated as of JFreeChart 1.0.6, and will be removed in a future release. 256 CHAPTER 28. PACKAGE: ORG.JFREE.CHART.ENTITY 28.3.3 Methods In addition to the methods inherited from the ChartEntity class: å public CategoryDataset getDataset(); Returns a reference to the dataset (never null). å public void setDataset(CategoryDataset dataset); Sets the dataset reference for this entity (null is not permitted). To identify the data item: å public Comparable getRowKey(); [1.0.6] Returns the row key for the data item. å public void setRowKey(Comparable rowKey); [1.0.6] Sets the row key for the data item. å public Comparable getColumnKey(); [1.0.6] Returns the column key for the data item. å public void setColumnKey(Comparable columnKey); [1.0.6] Sets the column key for the data item. The original index-based methods for identifying the data item have been deprecated: å public int getSeries(); [Deprecated, 1.0.6] Returns the index of the series containing the item that this entity represents. å public void setSeries(int series); [Deprecated, 1.0.6] Sets the index of the series containing the item that this entity represents. å public Object getCategory(); [Deprecated, 1.0.6] Returns the category containing the item that this entity represents. This may be null. å public void setCategory(Object category); [Deprecated, 1.0.6] Sets the category containing the item that this entity represents. å public int getCategoryIndex(); [Deprecated, 1.0.6] Returns the index of the category containing the item that this entity represents. å public void setCategoryIndex(int index); [Deprecated, 1.0.6] Sets the index of the category containing the item that this entity represents. For debugging purposes, this class overrides the toString() method: å public String toString(); Returns a string representation of this CategoryItemEntity, typically used when debugging. 28.3.4 Equals, Cloning and Serialization This class overrides the equals(Object) method: å public boolean equals(Object obj); Tests this entity for equality with an arbitrary object. Instances of this class are cloneable (PublicCloneable is implemented) and serializable. 28.3.5 Notes Most CategoryItemRenderer implementations will generate entities using this class, as required. See Also ChartEntity, CategoryPlot. 257 CHAPTER 28. PACKAGE: ORG.JFREE.CHART.ENTITY 28.4 ChartEntity 28.4.1 Overview 258 This class is used to convey information about an entity within a chart. The information captured includes the area occupied by the item and the tool tip text generated for the item. There are a number of subclasses that can be used to provide additional information about a chart entity. ChartEntity #area: Shape #toolTipText: String PieSectionEntity #category: Object CategoryItemEntity #series: int #category: Object XYItemEntity #series: int #item: int Figure 28.1: Chart entity classes 28.4.2 Constructors To construct a new instance: å public ChartEntity(Shape area, String toolTipText); Creates a new chart entity object. The area is specified in Java 2D space. Chart entities are created by other classes in the JFreeChart library, you don’t usually need to create them yourself. 28.4.3 Methods Accessor methods are implemented for the area and toolTipText attributes. To support the generation of HTML image maps, the getShapeType() method returns a String containing either RECT or POLY, and the getShapeCoords() method returns a String containing the coordinates of the shape’s outline. See the ChartUtilities class for more information about HTML image maps. 28.4.4 Notes The ChartEntity class records where an entity has been drawn using a Graphics2D instance. Changing the attributes of an entity won’t change what has already been drawn. See Also CategoryItemEntity, PieSectionEntity, XYItemEntity. 28.5 ContourEntity 28.5.1 Overview This class is deprecated as of JFreeChart version 1.0.4. See Also ContourPlot. CHAPTER 28. PACKAGE: ORG.JFREE.CHART.ENTITY 28.6 EntityCollection 28.6.1 Overview 259 An interface that defines the API for a collection of chart entities. This is used by the ChartRenderingInfo class to record where items have been drawn when a chart is rendered using a Graphics2D instance. Each ChartEntity can also record tool tip information (for displaying tool tips in a Swing user interface) and/or URL information (for generating HTML image maps). 28.6.2 Methods The interface defines three methods. To clear a collection: å public void clear(); Clears the collection. All entities in the collection are discarded. To add an entity to a collection: å public void addEntity(ChartEntity entity); Adds an entity to the collection. To retrieve an entity based on Java 2D coordinates: å public ChartEntity getEntity(double x, double y); Returns an entity whose area contains the specified coordinates. If the coordinates fall within the area of multiple entities (the entities overlap) then only one entity is returned. 28.6.3 Notes The StandardEntityCollection class provides a basic implementation of this interface (but one that won’t scale to large numbers of entities). See Also ChartEntity, StandardEntityCollection. 28.7 LegendItemEntity 28.7.1 Overview An entity that records information about a legend item. 28.7.2 Constructor To create a new LegendItemEntity: å public LegendItemEntity(Shape area); Creates a new legend item with the specified hotspot. 28.7.3 Methods The legend item is associated with a dataset and a series key: å public Dataset getDataset(); [1.0.6] Returns the dataset for the legend item. å public void setDataset(Dataset dataset); [1.0.6] Sets the dataset for the legend item. å public Comparable getSeriesKey(); [1.0.6] Returns the series key for the legend item. CHAPTER 28. PACKAGE: ORG.JFREE.CHART.ENTITY 260 å public void setSeriesKey(Comparable key); [1.0.6] Sets the series key for the legend item. To access the index of the series that the legend item relates to: å public int getSeriesIndex(); [Deprecated, 1.0.6] Returns the index of the series that the legend item entity relates to. å public void setSeriesIndex(int index); [Deprecated, 1.0.6] Sets the index of the series that the legend item entity relates to. 28.7.4 Equals, Cloning and Serialization This class overrides the equals() method: å public boolean equals(Object obj); Tests this entity for equality with an arbitrary object. To obtain a clone of the entity: å public Object clone() throws CloneNotSupportedException; Returns a clone of the entity. 28.8 PieSectionEntity 28.8.1 Overview This class is used to convey information about an item within a pie plot. The information captured includes the area occupied by the item, the dataset, pie and section indices, and the tool tip and URL text (if any) generated for the item. 28.8.2 Constructors To construct a new instance: å public PieSectionEntity(Shape area, PieDataset dataset, int pieIndex, int sectionIndex, Comparable sectionKey, String toolTipText, String urlText); Creates a new entity object. 28.8.3 Methods Accessor methods are implemented for the dataset, pieIndex, sectionIndex and sectionKey attributes. Other methods are inherited from the ChartEntity class. 28.8.4 Notes The PiePlot class generates pie section entities as required. See Also ChartEntity, PiePlot. 28.9 StandardEntityCollection 28.9.1 Overview A basic implementation of the EntityCollection interface. This class can be used (optionally, by the ChartRenderingInfo class) to store a collection of chart entity objects from one rendering of a chart. The entities can be used to support tool-tips, drill-down charts and HTML image maps. CHAPTER 28. PACKAGE: ORG.JFREE.CHART.ENTITY 28.9.2 261 Constructor To create a new collection: å public StandardEntityCollection(); Creates a new (empty) collection. 28.9.3 Methods The following methods are supported by this class: å public void add(ChartEntity entity); Adds a chart entity to the collection. This method throws an IllegalArgumentException if entity is null. å public void addAll(EntityCollection collection); Adds all the entities from the specified collection to this collection. This method throws a NullPointerException if collection is null. å public int getEntityCount(); Returns the number of entities stored in the collection. å public ChartEntity getEntity(int index); Returns a chart entity from the specified position in the collection. å public void clear(); Clears all the entities from the collection. å public ChartEntity getEntity(double x, double y); Returns an entity from the collection that has a “hot-spot” that contains the specified (x, y) location (in Java2D space). å public Collection getEntities(); Returns an unmodifiable collection containing the entities. å public Iterator iterator(); Returns an iterator for the entities in the collection. 28.9.4 Equals, Cloning and Serialization This class overrides the equals() method: å public boolean equals(Object obj); Tests this entity collection for equality with an arbitrary object. å public Object clone() throws CloneNotSupportedException Returns a deep clone of this collection (each entity in the collection is cloned). 28.9.5 Notes The getEntity() method iterates through the entities searching for one that contains the specified coordinates. For charts with a large number of entities, a more efficient approach will be required.1 See Also ChartEntity, EntityCollection. 28.10 TickLabelEntity 28.10.1 Overview An entity that records information about a tick label. 1 This is on the to-do list but, given the size of the to-do list, I’m hopeful that someone will contribute code to address this. CHAPTER 28. PACKAGE: ORG.JFREE.CHART.ENTITY 28.11 XYAnnotationEntity 28.11.1 Overview 262 An entity that represents an XYAnnotation. 28.11.2 Constructor To create a new instance: å public XYAnnotationEntity(Shape hotspot, int rendererIndex, String toolTipText, String urlText); Creates a new entity with the specified hotspot. The renderer index denotes the renderer to which the annotation belongs. 28.11.3 Methods In addition to the methods inherited from ChartEntity, this class defines the following: å public int getRendererIndex(); Returns the index of the renderer to which the annotation is assigned. å public void setRendererIndex(int index); Sets the index of the renderer to which the annotation is assigned. 28.11.4 Equals, Cloning and Serialization This class overrides the equals() method: å public boolean equals(Object obj); Tests this entity for equality with an arbitrary object. 28.12 XYItemEntity 28.12.1 Overview This class is used to convey information about an item within an XY plot. The information captured includes the area occupied by the item, the tool tip text generated for the item, and the series and item index. 28.12.2 Constructors To construct a new instance: å public XYItemEntity(Shape area, XYDataset dataset, int series, int item, String toolTipText, String urlText); Creates a new entity object. 28.12.3 Methods Accessor methods are implemented for the dataset, series and item attributes. Other methods are inherited from the ChartEntity class. 28.12.4 Notes Most XYItemRenderer implementations will generate entities using this class, as required. See Also ChartEntity, XYPlot. Chapter 29 Package: org.jfree.chart.event 29.1 Introduction This package contains classes and interfaces that are used to broadcast and receive events relating to changes in chart properties. By default, some of the classes in the library will automatically register themselves with other classes, so that they receive notification of any changes and can react accordingly. For the most part, you can simply rely on this default behaviour. 29.2 AxisChangeEvent 29.2.1 Overview An event that can be sent to an AxisChangeListener to provide information about a change to an axis. Almost every axis update will trigger an AxisChangeEvent. 29.2.2 Notes Some points to note: • often, the only information provided by the event is that some change has been made to the axis (that is, the specific change is not identified); • when a chart is displayed in a ChartPanel, any AxisChangeEvent will trigger a chain of events that results in the chart on the panel being repainted. 29.3 AxisChangeListener 29.3.1 Overview An interface through which axis change event notifications are posted. 29.3.2 Methods The interface defines a single method: å public void axisChanged(AxisChangeEvent event); Receives notification of a change to an axis. 263 CHAPTER 29. PACKAGE: ORG.JFREE.CHART.EVENT 29.3.3 264 Notes Some points to note: • if a class needs to receive notification of changes to an axis, then it needs to implement this interface and register itself with the axis; • the plot classes that manage axes (for example, CategoryPlot and XYPlot) implement this interface to listen for changes to the axes, and typically respond by generating a PlotChangeEvent. 29.4 ChartChangeEvent 29.4.1 Overview An event that is used to provide information about changes to a chart. You can register an object with a JFreeChart instance, provided that the object implements the ChartChangeListener interface, and it will receive a notification whenever the chart changes. 29.4.2 Constructors The following constructors are defined: å public ChartChangeEvent(Object source); Creates a new event generated by the given source. å public ChartChangeEvent(Object source, JFreeChart chart); Creates a new event generated by the given source for the given chart (the source and chart may be the same). å public ChartChangeEvent(Object source, JFreeChart chart, ChartChangeEventType type); Creates a new event with the specified type. 29.4.3 Methods The following methods are defined: å public JFreeChart getChart(); Returns the chart that the event relates to. å public void setChart(JFreeChart chart); Sets the chart for the event. å public ChartChangeEventType getType(); Returns the event type. å public void setType(ChartChangeEventType type); Sets the event type. 29.4.4 Notes The ChartPanel class automatically registers itself with the chart it is displaying. When it receives a ChartChangeEvent, it repaints the chart. 29.5 ChartChangeEventType 29.5.1 Overview This class defines the tokens that can be used to specify the “type” for a ChartChangeEvent. The intent behind specifying event types is to allow JFreeChart to react in special ways to particular events. For example, an updated dataset may not require a chart redraw if the data that changed is outside the visible data range. However, there is currently no code in JFreeChart that takes advantage of the event type. CHAPTER 29. PACKAGE: ORG.JFREE.CHART.EVENT Token: Description: ChartChangeEventType.GENERAL ChartChangeEventType.NEW DATASET A general event. An event that signals that a new dataset has been added to the chart. An event that signals that a dataset has been updated. ChartChangeEventType.DATASET UPDATED 265 Table 29.1: ChartChangeEventType tokens 29.6 ChartChangeListener 29.6.1 Overview An interface through which chart change event notifications are posted. 29.6.2 Methods The interface defines a single method: å public void chartChanged(ChartChangeEvent event); Receives notification of a change to a chart. 29.6.3 Notes Some points to note: • if a class needs to receive notification of changes to a chart, then it needs to implement this interface and register itself with the chart; • the ChartPanel class implements this interface, and repaints the chart whenever a change event is received. 29.7 ChartProgressEvent 29.7.1 Overview An event that contains information about the progress made during the rendering of a chart. Any class that implements the ChartProgressListener interface can register with the JFreeChart class and receive these events during chart rendering. 29.7.2 Constructor To create a new event: å public ChartProgressEvent(Object source, JFreeChart chart, int type, int percent); Creates a new event with the given attributes. The source may be the chart, or some subcomponent of the chart. The type identifies the event type, defined values include DRAWING STARTED and DRAWING FINISHED (others may be added in the future). The percent is an estimate of the amount of progress, in the range 0 to 100. Typically, user code will receive events that have been constructed by JFreeChart, and won’t need to create new event instances. 29.7.3 Methods Accessor methods are provided for the event’s attributes: å public JFreeChart getChart(); Returns the chart that the event relates to. CHAPTER 29. PACKAGE: ORG.JFREE.CHART.EVENT 266 å public void setChart(JFreeChart chart); Sets the chart that the event belongs to (this should not be null). å public int getType(); Returns the event type, one of DRAWING STARTED and DRAWING FINISHED. Additional types may be defined in the future. å public void setType(int type); Sets the drawing type, which should be one of DRAWING STARTED and DRAWING FINISHED. Additional types may be defined in the future. This event provides a mechanism for finding out what percentage of the chart rendering has been completed. Unfortunately, this isn’t fully implemented, so you cannot rely on it: å public int getPercent(); Returns the percentage complete for the chart’s rendering. This should be a value in the range 0 to 100. å public void setPercent(int percent); Sets the percentage complete for the chart’s rendering. This should be a value in the range 0 to 100. 29.7.4 Notes This mechanism is intended to provide the ability to report progress on the rendering of slow drawing charts, but is not yet complete. It still serves a purpose in that it allows code to determine the point at which chart rendering is complete. 29.8 ChartProgressListener 29.8.1 Overview A listener that can receive progress updates from a chart. The listener will receive an event (DRAWING STARTED) when the chart drawing commences, and another event (DRAWING FINISHED) when the chart drawing is finished.1 29.8.2 Method This interface defines a single method that receives notification (from a JFreeChart instance) of the chart drawing progress: å public void chartProgress(ChartProgressEvent event); Receives notification of the progress of chart rendering. 29.9 MarkerChangeEvent 29.9.1 Overview An event that is used to signal that some change has been made to a Marker. In JFreeChart, the plot classes listen for changes to any markers they manage, and notify the chart when such changes occur. 29.9.2 Constructors There is a single constructor: å public MarkerChangeEvent(Marker marker); [1.0.3] Creates a new event with marker as the source. If marker is null, this constructor throws an IllegalArgumentException. 1 Originally it was planned that the listener should receive interim events during chart drawing, but this hasn’t been implemented yet. CHAPTER 29. PACKAGE: ORG.JFREE.CHART.EVENT 29.9.3 267 Methods The following method is defined: å public Marker getMarker(); [1.0.3] Returns the marker that triggered the event. This will never be null. 29.9.4 Notes This class was introduced in version 1.0.3. See Also MarkerChangeListener. 29.10 MarkerChangeListener 29.10.1 Overview The interface through which MarkerChangeEvent notifications are posted. This interface is implemented by CategoryPlot and XYPlot. 29.10.2 Methods The interface defines a single method: å public void markerChanged(MarkerChangeEvent event); [1.0.3] Receives notification of a change to a marker. 29.10.3 Notes Some points to note: • this interface was introduced in JFreeChart version 1.0.3 (prior to this version, markers did not generate change events); • if a class needs to receive notification of changes to a marker, then it needs to implement this interface and register itself with the legend. See Also MarkerChangeEvent. 29.11 PlotChangeEvent 29.11.1 Overview An event that is used to provide information about changes to a plot. You can register an object with a Plot instance, provided that the object implements the PlotChangeListener interface, and it will receive a notification whenever the plot changes. 29.11.2 Notes A JFreeChart object will automatically register itself with the Plot that it manages, and receive notification whenever the plot changes. The chart usually responds by raising a ChartChangeEvent, which other listeners may respond to (for example, the ChartPanel if the chart is displayed in a GUI). CHAPTER 29. PACKAGE: ORG.JFREE.CHART.EVENT 29.12 PlotChangeListener 29.12.1 Overview 268 An interface through which plot change event notifications are posted. 29.12.2 Methods The interface defines a single method: å public void plotChanged(PlotChangeEvent event); Receives notification of a change to a plot. 29.12.3 Notes Some points to note: • if a class needs to receive notification of changes to a plot, then it needs to implement this interface and register itself with the plot. • the JFreeChart class implements this interface and automatically registers itself with the plot it manages. 29.13 RendererChangeEvent 29.13.1 Overview An event that is used to provide information about changes to a renderer. If an object needs to receive notification of these events, its class should implement the RendererChangeListener interface so the object can register itself with the renderer via the addChangeListener() method. 29.13.2 Usage Typically, you won’t need to use this class directly. By default, JFreeChart’s plot classes will automatically register (as a RendererChangeListener) with each renderer that is assigned to the plot. As a result, (most) changes to a renderer will cause the plot to receive notification of the change. The plot will usually respond by firing a PlotChangeEvent which, in turn, gets passed on to the chart and results in a ChartChangeEvent being fired. This chain of events is used to ensure that charts are automatically updated whenever a change is made to any component of the chart. 29.13.3 Notes In the current implementation, the event just signals a change without specifying exactly what changed. A possible future enhancement would be to include information about the nature of the change, so that the listener(s) can decide what action to take in response to the event. 29.14 RendererChangeListener 29.14.1 Overview An interface through which renderer change event notifications are posted. The CategoryPlot and XYPlot classes implement this interface so they can receive notification of changes to their renderer(s). CHAPTER 29. PACKAGE: ORG.JFREE.CHART.EVENT 29.14.2 269 Methods The interface defines a single method: å public void rendererChanged(RendererChangeEvent event); Receives notification of a change to a renderer. 29.14.3 Notes If an Object needs to receive notification of changes to a renderer, then its class needs to implement this interface so the object can register itself with the renderer. 29.15 TitleChangeEvent 29.15.1 Overview An event that is used to provide information about changes to a chart title (any subclass of Title). 29.15.2 Notes This event is part of the overall mechanism that JFreeChart uses to automatically update charts whenever changes are made to components of the chart. See Also Title, TitleChangeListener. 29.16 TitleChangeListener 29.16.1 Overview An interface through which title change event notifications are posted. 29.16.2 Methods The interface defines a single method: å public void titleChanged(TitleChangeEvent event); Receives notification of a change to a title. 29.16.3 Notes If a class needs to receive notification of changes to a title, then it needs to implement this interface and register itself with the title. See Also TitleChangeEvent. Chapter 30 Package: org.jfree.chart.imagemap 30.1 Overview This package contains classes and interfaces that support the creation of HTML image maps. These image maps can be created using the ImageMapUtilities class, typically from a servlet. 30.2 DynamicDriveToolTipTagFragmentGenerator 30.2.1 Overview A tool-tip fragment generator that generates tool-tips that are designed to work with the Dynamic Drive DHTML Tip Message library: http://www.dynamicdrive.com This class implements the ToolTipTagFragmentGenerator interface. 30.3 ImageMapUtilities 30.3.1 Overview This class contains some utility methods that are useful for creating HTML image maps. A range of demos (ImageMapDemo1-6.java) are included in the JFreeChart demo collection. 30.3.2 Methods Several methods provide the ability to write an image map directly to a stream:1 å public static void writeImageMap(PrintWriter writer, String name, ChartRenderingInfo info); Writes an image map using info as the source of chart entity information. This is equivalent to writeImageMap(writer, name, info, new StandardToolTipTagFragmentGenerator(), new StandardURLTagFragmentGenerator()); å public static void writeImageMap(PrintWriter writer, String name, ChartRenderingInfo info, boolean useOverLibForToolTips); Writes an image map using info as the source of chart entity information. This will use an instance of OverLIBToolTipTagFragmentGenerator to format the tooltip output, if requested. 1 Note that in the current implementation, the image map is created entirely in memory and then written to the stream, which is not as efficient as it could be. 270 CHAPTER 30. PACKAGE: ORG.JFREE.CHART.IMAGEMAP 271 å public static void writeImageMap(PrintWriter writer, String name, ChartRenderingInfo info, ToolTipTagFragmentGenerator toolTipTagFragmentGenerator, URLTagFragmentGenerator urlTagFragmentGenerator) throws IOException; Writes an image map using info as the source of chart entity information. This method first calls getImageMap() to create the image map text, then writes it to write. The tooltip and URL fragment generators provide the option to customize the imagemap output. To create an HTML image map string: å public static String getImageMap(String name, ChartRenderingInfo info); Returns an image map based on the chart entity information in info. This is equivalent to getImageMap(name, info, new StandardToolTipTagFragmentGenerator(), new StandardURLTagFragmentGenerator()); å public static String getImageMap(String name, ChartRenderingInfo info, ToolTipTagFragmentGenerator toolTipTagFragmentGenerator, URLTagFragmentGenerator urlTagFragmentGenerator); Returns an HTML image map based on the chart entity information in info. The following method creates standard escape sequences for “unsafe” characters in a string that will be embedded in HTML output: å public static String htmlEscape(String input); [1.0.9] Returns a string that corresponds to the input string after replacing certain characters with standard HTML escape sequences. If input is null, this method throws an IllegalArgumentException. 30.3.3 Notes Some points to note: • tooltip and URL content is controlled by generators defined in the packages: – org.jfree.chart.labels.* for tooltips; – org.jfree.chart.urls.* for URLs. ...whereas the tooltip and URL fragment generators defined in this package are concerned with variation in the HTML tags that get incorporated into the HTML image map. 30.4 OverLIBToolTipTagFragmentGenerator 30.4.1 Overview A tool-tip generator that generates tool-tips for use with the OverLIB library. See this URL for details: http://www.bosrup.com/web/overlib/ This class implements the ToolTipTagFragmentGenerator interface. 30.5 StandardToolTipTagFragmentGenerator 30.5.1 Overview A tool-tip generator that generates tool-tips using the HTML title attribute. This class implements the ToolTipTagFragmentGenerator interface. CHAPTER 30. PACKAGE: ORG.JFREE.CHART.IMAGEMAP 30.6 StandardURLTagFragmentGenerator 30.6.1 Overview 272 A default implementation of the URLTagFragmentGenerator interface. Instances of this class are created by some methods in the ImageMapUtilities class, to create the href elements in the HTML image map. You can supply an alternative implementation if you want greater control over the hyperlinks in the image map. 30.6.2 Constructor This class has only the default constructor. Instances are stateless, so there are no attributes to define. 30.6.3 Methods This class implements a single method: å public String generateURLFragment(String urlText); Returns a URL fragment containing the specified URL text. The implementation is very simple: return " href=\"" + urlText + "\""; 30.6.4 Equals, Cloning and Serialization This class has no state, and is typically used for a single call to the getImageMap() or writeImageMap() methods in the ImageMapUtilities class. Therefore, it does not override the equals() method, and is neither cloneable nor serializable. See Also URLTagFragmentGenerator. 30.7 ToolTipTagFragmentGenerator 30.7.1 Overview The interface that must be implemented by a class that generates tooltip tag fragments for an HTML image map. Classes that implement this interface include: • StandardToolTipTagFragmentGenerator; • DynamicDriveToolTipTagFragmentGenerator; • OverLIBToolTipTagFragmentGenerator; 30.7.2 Methods This interface defines a single method: å public String generateToolTipFragment(String toolTipText); Returns a tooltip fragment based on the supplied tool-tip text. CHAPTER 30. PACKAGE: ORG.JFREE.CHART.IMAGEMAP 30.8 URLTagFragmentGenerator 30.8.1 Overview 273 The interface that must be implemented by a class that generates the URL tag fragment for an HTML image map. For example, in the following area element, the URL fragment is shown underlined: The URL content is created elsewhere, but this generator is responsible for generating the surrounding text (the href tag in this case). The StandardURLTagFragmentGenerator class is the only implementation of this interface provided by JFreeChart. 30.8.2 Methods This interface defines a single method: å public String generateURLFragment(String urlText); Returns a URL fragment based on the supplied URL text. 30.8.3 Notes You can pass an instance of a class that implements this interface to the getImageMap() and writeImageMap() methods in the ImageMapUtilities class. Chapter 31 Package: org.jfree.chart.labels 31.1 Introduction This package contains interfaces and classes for generating labels for the individual data items in a chart. There are two label types: • item labels – text displayed in, on or near to each data item in a chart; • tooltips – text that is displayed when the mouse pointer “hovers” over a data item in a chart. Section 11 contains information about using tool tips and section 12 contains information about using item labels. 31.2 AbstractCategoryItemLabelGenerator 31.2.1 Overview An abstract base class for creating item labels for a CategoryItemRenderer. Known subclasses include: • StandardCategoryToolTipGenerator; • StandardCategoryItemLabelGenerator. The generator uses Java’s MessageFormat class to construct labels by substituting any or all of the objects listed in table 31.1. The data value is formatted before it is passed to the MessageFormat—you can specify the NumberFormat or DateFormat that is used to preformat the value via the constructor. 31.2.2 Constructors Two (protected) constructors are provided, the difference between them is the type of formatter (number or date) for the data values. In both cases, the labelFormat parameter determines the overall structure of the generated label—you can use the substitutions listed in table 31.1. Code: Description: {0} {1} {2} The series name. The category label. The (preformatted) data value. Table 31.1: MessageFormat substitutions 274 CHAPTER 31. PACKAGE: ORG.JFREE.CHART.LABELS 275 å protected AbstractCategoryItemLabelGenerator(String labelFormat, NumberFormat formatter); Creates a new generator that formats the data values using the supplied NumberFormat instance. å protected AbstractCategoryItemLabelGenerator(String labelFormat, DateFormat formatter); Creates a new generator that formats the data values using the supplied DateFormat instance. Methods To generate a label string: å protected String generateLabelString(CategoryDataset dataset, int row, int column); Generates a label string. This method first calls the createItemArray() function, then passes the result to Java’s MessageFormat to build the required label. The following function builds the array (Object[]) that contains the items that can be substituted by the MessageFormat code: å protected Object[] createItemArray(CategoryDataset dataset, int row, int column); Returns an array containing three items, the series name, the category label and the formatted data value. 31.2.3 Notes Some points to note: • the StandardCategoryToolTipGenerator and StandardCategoryItemLabelGenerator classes are extensions of this class; • instances of this class are Cloneable and Serializable. 31.3 AbstractPieItemLabelGenerator 31.3.1 Overview A base class used to create label generators for pie charts. Subclasses include: • StandardPieSectionLabelGenerator; • StandardPieToolTipGenerator. 31.3.2 Constructor The following constructor is provided for use by subclasses: å protected AbstractPieItemLabelGenerator(String labelFormat, NumberFormat numberFormat, NumberFormat percentFormat); Creates a new instance with the specified formatting attributes. The labelFormat is a string that is used by an internal MessageFormat instance to compose a section label for an item in the dataset—see the generateSectionLabel() method. If any of the arguments is null, this constructor will throw an IllegalArgumentException. 31.3.3 Methods The following methods are defined: å public String getLabelFormat(); Returns the formatting string that is used by the internal MessageFormat instance. CHAPTER 31. PACKAGE: ORG.JFREE.CHART.LABELS Token: Description: {0} {1} {2} The series name. The (preformatted) x-value. The (preformatted) y-value. 276 Table 31.2: MessageFormat substitutions å public NumberFormat getNumberFormat(); Returns the number formatter used to preformat each dataset value before incorporating it into a section label. Note that the label format string (see getLabelFormat()) may or may not include the dataset value. å public NumberFormat getPercentFormat(); Returns the number formatter used to preformat each percentage value1 before incorporating it into a section label. Note that the label format string (see getLabelFormat()) may or may not include the percentage value. å protected Object[] createItemArray(PieDataset dataset, Comparable key); Creates an array of objects to pass to the internal MessageFormat instance used to create the section label. The array contains four String objects: • item 0: key.toString(); • item 1: the dataset value formatted using getNumberFormat(), or null; • item 2: the dataset value as a percentage formatted using getPercentFormat(); • item 3: the total of all the dataset values, formatted using getNumberFormat(). å protected String generateSectionLabel(PieDataset dataset, Comparable key); Returns a section label for the specified item in the given dataset. This method is called by JFreeChart, it typically won’t be called by external code. 31.3.4 Equals, Cloning and Serialization This class overrides the equals() method: å public boolean equals(Object obj); Tests this generator for equality with an arbitrary object. Instances of this class are Cloneable and Serializable. 31.4 AbstractXYItemLabelGenerator 31.4.1 Overview An abstract base class that creates item labels (on demand) for an XYItemRenderer. Subclasses include: • StandardXYToolTipGenerator; and • StandardXYItemLabelGenerator. Internally, the generator uses Java’s MessageFormat class to construct labels by substituting any or all of the tokens listed in table 31.2. The x and y values are formatted before they are passed to MessageFormat—you can specify the NumberFormat or DateFormat that is used to preformat the values via the constructor. 1 The percentage value is the dataset value expressed as a percentage of the sum of all dataset values. CHAPTER 31. PACKAGE: ORG.JFREE.CHART.LABELS 31.4.2 277 Constructors All the constructors for this class are protected and provided for use by subclasses only. The provided constructors give you control over the formatters (number or date) used for the x and y data values. In all cases, the labelFormat parameter determines the overall structure of the generated label—you can use the substitutions listed in table 31.2. å protected AbstractXYItemLabelGenerator(); Creates a new generator that formats the data values using the default number formatter for the current locale. å protected AbstractXYItemLabelGenerator(String formatString, NumberFormat xFormat, NumberFormat yFormat); Creates a new generator that formats the data values using the supplied NumberFormat instances. å protected AbstractXYItemLabelGenerator(String formatString, DateFormat xFormat, NumberFormat yFormat); Creates a new generator that formats the x-values as dates and the y-values as numbers. å protected AbstractXYItemLabelGenerator(String formatString, DateFormat xFormat, NumberFormat yFormat); [1.0.4] Creates a new generator that formats the x-values as numbers and the y-values as dates. å protected AbstractXYItemLabelGenerator(String formatString, DateFormat xFormat, DateFormat yFormat); Creates a new generator that formats both the x and y values as dates. Attributes To obtain the format string that was specified in the constructor: å public String getFormatString(); Returns the format string that will be passed to a MessageFormat instance when creating the item label. In the typical case, the x and y values are formatted as numbers: å public NumberFormat getXFormat(); Returns the formatter for the x-values (never null). Note that if the getXDateFormat() method returns a non-null formatter, it will be used instead. å public NumberFormat getYFormat(); Returns the formatter for the y-values (never null). Note that if the getYDateFormat() method returns a non-null formatter, it will be used instead. These formatters can be (optionally) overridden by date formatters: å public DateFormat getXDateFormat(); Returns the (date) formatter for the x-values. If this is null, the x-values will be formatted as numbers—see getXFormat(). å public DateFormat getYDateFormat(); Returns the (date) formatter for the y-values. If this is null, the y-values will be formatted as numbers—see getYFormat(). Other Methods The following methods are called by JFreeChart—you won’t normally call them directly from your own code: å protected String generateLabelString(XYDataset dataset, int series, int item); Generates a label string. This method first calls the createItemArray() method, then passes the result to Java’s MessageFormat to build the required label. The following function builds the array (Object[]) that contains the items that can be substituted by the MessageFormat code: å protected Object[] createItemArray(XYDataset dataset, int series, int item); Returns an array containing three items, the series name, the formatted x and y data values. CHAPTER 31. PACKAGE: ORG.JFREE.CHART.LABELS 31.4.3 278 Equals, Cloning and Serialization This class overrides the equals() method: å public boolean equals(Object obj); Tests this generator for equality with an arbitrary object. This method returns true if and only if: • obj is not null; • obj is an instance of AbstractXYItemLabelGenerator; • obj has the same attributes as this generator. Instances of this class are Cloneable and Serializable. 31.4.4 Notes Some points to note: • the StandardXYToolTipGenerator and StandardXYItemLabelGenerator classes are extensions of this class. 31.5 BoxAndWhiskerToolTipGenerator 31.5.1 Overview A tool tip generator for a box-and-whisker chart. BoxAndWhiskerRenderer class. This is the default generator used by the 31.6 BoxAndWhiskerXYToolTipGenerator 31.6.1 Overview A tool tip generator for a box-and-whisker chart. This is the default generator used by the XYBoxAndWhiskerRenderer class. 31.7 CategoryItemLabelGenerator 31.7.1 Overview A category item label generator is an object that assumes responsibility for creating the text strings that will be used for item labels in a chart. A generator is assigned to a renderer using the setItemLabelGenerator() method in the CategoryItemRenderer interface. This interface defines the API through which the renderer will communicate with the generator. 31.7.2 Usage Chapter 12 contains information about using item labels. 31.7.3 Methods The renderer will call this method to obtain an item label: å public String generateLabel(CategoryDataset data, int series, int category); Returns a string that will be used to label the specified item. Classes that implement this method are permitted to return null for the result, in which case no label will be displayed for that item. CHAPTER 31. PACKAGE: ORG.JFREE.CHART.LABELS 279 Additional methods: å public String generateRowLabel(CategoryDataset dataset, int row); Returns a label for the given row in the dataset. å public String generateColumnLabel(CategoryDataset dataset, int column); Returns a label for the given column in the dataset. 31.7.4 Notes Some points to note: • the StandardCategoryItemLabelGenerator class provides one implementation of this interface, but you can also write your own class that implements this interface, and take complete control over the generation of item labels. 31.8 CategorySeriesLabelGenerator 31.8.1 Overview An interface defining the API that a caller (typically a CategoryItemRenderer) can use to obtain a label for a series in a dataset. This interface is implemented by the StandardCategorySeriesLabelGenerator class. 31.8.2 Methods The renderer will call this method to obtain an item label: å public String generateLabel(CategoryDataset dataset, int series); Returns a string that will be used to label the specified series. 31.8.3 Notes Some points to note: • by convention, all classes that implement this interface should be either: – immutable; or – implement the PublicCloneable interface. This provides a mechanism for a referring class to determine whether or not it needs to clone the generator, and access to the clone() method in the case that the generator is cloneable. 31.9 CategoryToolTipGenerator 31.9.1 Overview A category tool tip generator is an object that assumes responsibility for creating the text strings that will be used for tooltips in a chart. A generator is assigned to a renderer using the setToolTipGenerator() method in the CategoryItemRenderer interface. This interface defines the API through which the renderer will communicate with the generator. 31.9.2 Methods The renderer will call this method to obtain the tooltip text for an item: å public String generateToolTip(CategoryDataset data, int series, int category); Returns a string that will be used as the tooltip text for the specified item. If null is returned, no tool tip will be displayed. CHAPTER 31. PACKAGE: ORG.JFREE.CHART.LABELS 31.9.3 280 Notes Some points to note: • the StandardCategoryToolTipGenerator provides one implementation of this interface, but you can also write your own class that implements this interface, and take complete control over the generation of item labels and tooltips; • refer to chapter 11 for information about using tool tips. 31.10 ContourToolTipGenerator 31.10.1 Overview The interface that must be implemented by all contour tool tip generators. When a ContourPlot requires tooltip text for a data item, it will obtain it via this interface. This interface is deprecated as of JFreeChart version 1.0.4. 31.10.2 Methods The interface defines a single method for obtaining the tooltip text for a data item: å public String generateToolTip(ContourDataset data, int item); Returns a string that can be used as the tooltip text for a data item. See Also ContourPlot. 31.11 CustomXYToolTipGenerator 31.11.1 Overview A tool tip generator (for use with an XYItemRenderer) that returns a predefined tool tip for each data item. 31.11.2 Methods To specify the text to use for the tool tips: å public void addToolTipSeries(List toolTips); Adds the list of tool tips (for one series) to internal storage. These tool tips will be returned (without modification) by the generator for each data item. 31.11.3 Notes See section 11 for information about using tool tips with JFreeChart. 31.12 HighLowItemLabelGenerator 31.12.1 Overview A label generator that is intended for use with the HighLowRenderer class. The generator will only return tooltips for a dataset that is an implementation of the OHLCDataset interface. CHAPTER 31. PACKAGE: ORG.JFREE.CHART.LABELS 31.12.2 281 Constructors To create a new label generator: å public HighLowItemLabelGenerator(DateFormat dateFormatter, NumberFormat numberFormatter); Creates a new label generator that uses the specified date and number formatters. 31.12.3 Methods The key method constructs a String to be used as the tooltip text for a particular data item: å public String generateToolTip(XYDataset dataset, int series, int item); Returns a string containing the date, value, high value, low value, open value and close value for the data item. This method will return null if the dataset does not implement the OHLCDataset interface. The following method is intended to generate an item label for display in a chart, but since the renderer does not yet support this the method simply returns null: å public String generateItemLabel(XYDataset dataset, int series, int category); Returns null. To be implemented. 31.12.4 Notes See section 11 for an overview of tool tips with JFreeChart. 31.13 IntervalCategoryItemLabelGenerator 31.13.1 Overview An label generator that can be used with any CategoryItemRenderer. This generator will detect if the dataset supplied to the renderer is an implementation of the IntervalCategoryDataset interface, and will generate labels that display both the start value and the end value for each item. 31.13.2 Constructors The default constructor will create a label generator that formats the data values as numbers, using the platform default number format: å public IntervalCategoryItemLabelGenerator(); Creates a new label generator with a default number formatter. If you prefer to set the number format yourself, use the following constructor: å public IntervalCategoryItemLabelGenerator(NumberFormat formatter); Creates a new label generator with a specific number formatter. In some cases, the data values in the dataset will represent dates (encoded as milliseconds since midnight, 1-Jan-1970 GMT, as for java.util.Date). In this case, you can create a label generator using the following constructor: å public IntervalCategoryItemLabelGenerator(DateFormat formatter); Creates a new label generator that formats the start and end data values as dates. 31.13.3 Notes The createGanttChart() in the ChartFactory class uses this type of label generator (with date formatting). CHAPTER 31. PACKAGE: ORG.JFREE.CHART.LABELS 31.14 IntervalCategoryToolTipGenerator 31.14.1 Overview 282 An tool tip generator that can be used with any CategoryItemRenderer. This generator will detect if the dataset supplied to the renderer is an implementation of the IntervalCategoryDataset interface, and will generate labels that display both the start value and the end value for each item. 31.14.2 Constructors The default constructor will create a label generator that formats the data values as numbers, using the platform default number format: å public IntervalCategoryToolTipGenerator(); Creates a new tool tip generator with a default number formatter. If you prefer to set the number format yourself, use the following constructor: å public IntervalCategoryToolTipGenerator(NumberFormat formatter); Creates a new tool tip generator with a specific number formatter. In some cases, the data values in the dataset will represent dates (encoded as milliseconds since midnight, 1-Jan-1970 GMT, as for java.util.Date). In this case, you can create a label generator using the following constructor: å public IntervalCategoryToolTipGenerator(DateFormat formatter); Creates a new tool tip generator that formats the start and end data values as dates. 31.14.3 Notes The createGanttChart() in the ChartFactory class uses this type of label generator (with date formatting). 31.15 ItemLabelAnchor 31.15.1 Overview An item label anchor is used by a renderer to calculate a fixed point (the item label anchor point) relative to a data item on a chart. This point becomes a reference point that an item label can be aligned to. This class defines 25 anchors. The numbers 1 to 12 are used and roughly correspond to the positions of the hours on a clock face. In addition, positions are defined relative to an “inside” ring and an “outside” ring - see figure 31.1 for an illustration. With 12 points on the inside circle, 12 points on the outside circle, plus a “center” anchor point, in all there are 25 possible anchor points. For some renderers, the circular arrangement of anchor points doesn’t make sense, so the renderer is free to modify the anchor positions (see the BarRenderer class for an example). 31.15.2 Usage The ItemLabelPosition class includes an item label anchor as one of the attributes that define the location of item labels drawn by a renderer. CHAPTER 31. PACKAGE: ORG.JFREE.CHART.LABELS 283 OUTSIDE_12 OUTSIDE_1 OUTSIDE_11 OUTSIDE_10 INSIDE_12 OUTSIDE_2 OUTSIDE_9 OUTSIDE_3 CENTER OUTSIDE_8 INSIDE_6 OUTSIDE_7 OUTSIDE_4 OUTSIDE_5 OUTSIDE_6 Figure 31.1: The Item Label Anchors 31.16 ItemLabelPosition 31.16.1 Overview This class is used to specify the position of item labels on a chart. Four attributes are used to specify the position: • the item label anchor - the renderer will use this to calculate an ( x, y) anchor point on the chart near to the data item that the item label corresponds to (see ItemLabelAnchor); • the text anchor - this is a point relative to the item label text which will be aligned with the item label anchor point above; • the rotation anchor - this is another point somewhere on the item label about which the text will be rotated (if there is a rotation); • the rotation angle - this specifies the amount of rotation about the rotation point. These four attributes provide a lot of scope for placing item labels in interesting ways. 31.16.2 Usage The AbstractRenderer class provides methods for specifying the item label position for positive and negative data values separately: å public void setPositiveItemLabelPosition(ItemLabelPosition position); Sets the item label position for positive data values. å public void setNegativeItemLabelPosition(ItemLabelPosition position); Sets the item label position for negative data values. 31.16.3 Constructors This class defines three constructors: å public ItemLabelPosition(); Creates a default instance. Equivalent to this(ItemLabelAnchor.OUTSIDE12, TextAnchor.BOTTOM CENTER)— see below. CHAPTER 31. PACKAGE: ORG.JFREE.CHART.LABELS 284 å public ItemLabelPosition(ItemLabelAnchor itemLabelAnchor, TextAnchor textAnchor); Creates a position with no text rotation. Equivalent to this(itemLabelAnchor, textAnchor, TextAnchor.CENTER, 0.0). å public ItemLabelPosition(ItemLabelAnchor itemLabelAnchor, TextAnchor textAnchor, TextAnchor rotationAnchor, double angle); Creates a new ItemLabelPosition instance. None of the arguments can be null. 31.16.4 Methods Accessor methods are defined for the attributes specified via the constructor. å public ItemLabelAnchor getItemLabelAnchor(); Returns the anchor point for the item label (never null). This defines a location relative to the data value on the chart to which the item label will be aligned. å public TextAnchor getTextAnchor(); Returns the reference point on the label text that will be aligned to the anchor point on the chart. This method never returns null. å public TextAnchor getRotationAnchor(); Returns the reference point on the label text about which any rotation will be performed. This method never returns null. å public double getAngle(); Returns the angle of rotation for the text (in radians). None of the above attributes can be modified post-construction, because instances of this class are immutable. 31.16.5 Equals, Cloning and Serialization This class overrides the equals() method: å public boolean equals(Object obj); Tests this ItemLabelPosition for equality with an arbitrary object. Returns true if and only if: • obj is not null; • obj is an instance of ItemLabelPosition; • obj has the same attributes as this instance. Instances of this class are immutable, so they don’t need to be Cloneable. Instances of this class are Serializable. 31.17 MultipleXYSeriesLabelGenerator 31.17.1 Overview A series label generator that can return multiple labels (separated by a newline character) for a single series. You might use this generator to show legend items in two or more languages, for example. 31.17.2 Constructors This class defines two constructors: å public MultipleXYSeriesLabelGenerator(); Equivalent to MultipleXYSeriesLabelGenerator("{0}")—see the next constructor. å public MultipleXYSeriesLabelGenerator(String format); Creates a new generator where the main label is generated with the specified format string. At label generation time, any occurrence of {0} in the format string will be replaced by the series name. CHAPTER 31. PACKAGE: ORG.JFREE.CHART.LABELS 31.17.3 285 Methods The following methods are defined: å public void addSeriesLabel(int series, String label); Adds an additional label for a series. This method does NOT fire a change event. å public void clearSeriesLabels(int series); Clears the additional labels for the specified series. This method does NOT fire a change event. å public String generateLabel(XYDataset dataset, int series); Generates the label string for a series in the specified dataset. å protected Object[] createItemArray(XYDataset dataset, int series); Creates and returns an array (of length 1) containing the string representation of the key for the specified series. This method is used internally. 31.17.4 Equals, Cloning and Serialization This class overrides the equals() method: å public boolean equals(Object obj); Tests this generator for equality with an arbitrary object. Instances of this class are Cloneable and Serializable. See Also XYSeriesLabelGenerator. 31.18 PieSectionLabelGenerator 31.18.1 Overview An interface that defines the methods used by a PiePlot to request section labels. Two generators can be specified for a PiePlot: • setLabelGenerator() – generates the labels displayed directly on the plot; • setLegendLabelGenerator() – generates the labels displayed in the plot’s legend (if it has one). The StandardPieSectionLabelGenerator class provides a standard implementation of this interface. 31.18.2 Usage The PieChartDemo2.java demo application includes code to customise the section labels, so you can refer to that demo for sample usage. 31.18.3 Methods The PiePlot class will call the following method to obtain a section label for each section in a pie chart as it is being drawn: å public String generateSectionLabel(PieDataset dataset, Comparable key); Returns a section label for the specified item in the dataset. A class implementing this method can return null, in which case no label will be displayed for the pie section. An alternative method that returns an AttributedString is defined, but is currently not used: å public AttributedString generateAttributedSectionLabel(PieDataset dataset, Comparable key); Returns an AttributedString for the section label for the specified item in the dataset. This method is not used at present—classes implementing this interface can safely return null for this method. CHAPTER 31. PACKAGE: ORG.JFREE.CHART.LABELS 31.18.4 286 Notes Some points to note: • you can develop your own label generator, register it with a PiePlot, and take full control over the labels that are generated. See Also PieToolTipGenerator. 31.19 PieToolTipGenerator 31.19.1 Overview The interface that must be implemented by a pie tool tip generator, a class used to generate tool tips for a pie chart. 31.19.2 Methods The PiePlot class will call the following method to obtain a tooltip for each section in a pie chart: å public String generateToolTip(PieDataset data, Comparable key); Returns a String that will be used as the tool tip text. This method can return null in which case no tool tip will be displayed. 31.19.3 Notes Some points to note: • the StandardPieToolTipGenerator class provides an implementation of this interface; • you can develop your own tool tip generator, register it with a PiePlot, and take full control over the labels that are generated; • section 11 contains information about using tool tips with JFreeChart. 31.20 StandardCategoryItemLabelGenerator 31.20.1 Overview A generator that can be assigned to a CategoryItemRenderer for the purpose of generating item labels (this class implements the CategoryItemLabelGenerator interface). This class is very flexible in the format of the labels it can generate. It uses Java’s MessageFormat class to create a label which can contain any of the items listed in table 31.1. The data value can be formatted using any NumberFormat instance. 31.20.2 Usage Most often you will assign a generator to a renderer and then never need to refer to it again: CategoryPlot plot = (CategoryPlot) chart.getPlot(); CategoryItemRenderer renderer = plot.getRenderer(); CategoryItemLabelGenerator generator = new StandardCategoryItemLabelGenerator( "{2}", new DecimalFormat("0.00")); renderer.setItemLabelGenerator(generator); renderer.setItemLabelsVisible(true); The renderer will call the generator’s methods when necessary. See section 12 for more information. CHAPTER 31. PACKAGE: ORG.JFREE.CHART.LABELS 31.20.3 287 Constructors To create a default generator: å public StandardCategoryItemLabelGenerator(); Creates a new generator that formats values using the default number format for the user’s locale. "{2}" is used as the label format string (that is, just the data value). To create a generator that formats values as numbers: å public StandardCategoryItemLabelGenerator(String labelFormat, NumberFormat formatter); Creates a generator that formats values as numbers using the supplied formatter. The labelFormat is passed to a MessageFormat to control the structure of the generated label, and can use any of the substitutions listed in table 31.1. To create a generator that formats values as dates (interpreting the numerical value as milliseconds since 1-Jan-1970, in the same way as java.util.Date): å public StandardCategoryItemLabelGenerator(String labelFormat, DateFormat formatter); Creates a generator that formats values as dates using the supplied formatter. The labelFormat is passed to a MessageFormat to control the structure of the generated label, and can use any of the substitutions listed in table 31.1. 31.20.4 Methods The renderer will call the following method whenever it requires an item label: å public String generateLabel(CategoryDataset dataset, int series, int category); Generates an item label for the specified data item. 31.20.5 Notes Some points to note: • instances of this class are cloneable and serializable, and the PublicCloneable interface is implemented; • for a demo, see ItemLabelDemo3.java in the JFreeChart demo collection. 31.21 StandardCategorySeriesLabelGenerator 31.21.1 Overview A generator that can be assigned to a CategoryItemRenderer for the purpose of generating series labels (this class implements the CategorySeriesLabelGenerator interface) for the legend. This class uses Java’s MessageFormat class to substitute the series name into an arbitrary string containing the token {0}. 31.21.2 Usage Most often you will assign a generator to a renderer and then never need to refer to it again: CategoryPlot plot = (CategoryPlot) chart.getPlot(); AbstractCategoryItemRenderer renderer = (AbstractCategoryItemRenderer) plot.getRenderer(); CategorySeriesLabelGenerator generator = new StandardCategorySeriesLabelGenerator("{0}"); renderer.setLegendItemLabelGenerator(generator); renderer.setItemLabelsVisible(true); The renderer will call the generator’s methods when necessary. CHAPTER 31. PACKAGE: ORG.JFREE.CHART.LABELS Code: Description: {0} {1} {2} The series key (or name). The category. The item value. 288 Table 31.3: MessageFormat substitutions for StandardCategoryToolTipGenerator 31.21.3 Constructors To create a default generator: å public StandardCategorySeriesLabelGenerator(); Creates a new generator that uses just the series name as the label. To create a generator that formats with a custom format string: å public StandardCategorySeriesLabelGenerator(String labelFormat); Creates a generator with the given format string. The labelFormat is passed to a MessageFormat to control the structure of the generated label, with {0} being substituted by the series name. 31.21.4 Methods The renderer will call the following method whenever it requires a series label: å public String generateLabel(CategoryDataset dataset, int series); Generates a series label for the specified series. This method is typically called by JFreeChart, not by external code. 31.21.5 Equals, Cloning and Serialization This class override the equals method: å public boolean equals(Object obj); Tests this generator for equality with an arbitrary object, returning true if and only if: • obj is an instance of StandardCategorySeriesLabelGenerator; • obj has the same formatPattern string as this generator. Instances of this class are Cloneable and Serializable. 31.22 StandardCategoryToolTipGenerator 31.22.1 Overview A generator that can be assigned to a CategoryItemRenderer for the purpose of generating tooltips. A format string provides the general template for each tool tip item, and Java’s MessageFormat class is used to substitute actual values from the dataset (the series key/name, the category, and the data value). Table 31.3 lists the items that can be included for substitution. 31.22.2 Usage This class provides an easy way to customise the tool tip text generated by a CategoryItemRenderer. This example shows how to create a new tool tip generator, and assign it to the plot’s renderer: CategoryPlot plot = (CategoryPlot) chart.getPlot(); CategoryItemRenderer renderer = plot.getRenderer(); renderer.setToolTipGenerator(new StandardCategoryToolTipGenerator( "The value is {2}, the series is {0} and the category is {1}.", NumberFormat.getInstance())); Once the generator is set, nothing more needs to be done—the renderer will call the generator’s methods when necessary. CHAPTER 31. PACKAGE: ORG.JFREE.CHART.LABELS 31.22.3 289 Constructors This class has a default constructor: å public StandardCategoryToolTipGenerator(); Creates a new generator that creates tooltips using the format string “{0}, {1} = {2}”. The data value is formatted using the default number format for the user’s locale. To create a generator that formats values as numbers: å public StandardCategoryToolTipGenerator(String labelFormat, NumberFormat formatter); Creates a generator that creates tooltips using the specified format string and number formatter. An IllegalArgumentException is thrown if either argument is null. To create a generator that formats values as dates (interpreting the numerical value as milliseconds since 1-Jan-1970, in the same way as java.util.Date): å public StandardCategoryToolTipGenerator(String labelFormat, DateFormat formatter); Creates a generator that creates tooltips using the specified format string and date formatter. In this case, the data value is interpreted as the number of milliseconds since 1-Jan-1970 (as for java.util.Date). An IllegalArgumentException is thrown if either argument is null. 31.22.4 Methods When the renderer requires a tool tip, it will call the following method: å public String generateToolTip(CategoryDataset dataset, int series, int category); Generates a tooltip for the specified data item using the format string and number (or date) formatter supplied to the constructor. 31.22.5 Notes Some points to note: • this class implements the CategoryToolTipGenerator and PublicCloneable interfaces; • section 11 contains information about using tool tips with JFreeChart. 31.23 StandardContourToolTipGenerator 31.23.1 Overview A default implementation of the ContourToolTipGenerator interface. This class is deprecated as of JFreeChart version 1.0.4. 31.24 StandardPieSectionLabelGenerator 31.24.1 Overview A generator that is used to create section labels for a PiePlot. The generator uses Java’s MessageFormat class to construct labels by substituting any or all of the objects listed in table 31.4. The default section label format is "{0}",2 which displays the item key as a string. This class implements the PieSectionLabelGenerator interface. 2 This is defined in the DEFAULT SECTION LABEL FORMAT constant field. CHAPTER 31. PACKAGE: ORG.JFREE.CHART.LABELS Code: Description: {0} {1} {2} {3} The The The The 290 item key. item value. item value as a percentage of the total. total of all values in the dataset. Table 31.4: MessageFormat substitutions for the StandardPieSectionLabelGenerator. 31.24.2 Usage You can use this class when you want to change the format of the the section labels on a pie chart. For example, to show percentages in the pie section labels: PiePlot plot = (PiePlot) chart.getPlot(); PieSectionLabelGenerator generator = new StandardPieSectionLabelGenerator( "{0} = {2}", new DecimalFormat("0"), new DecimalFormat("0.00%")); plot.setLabelGenerator(generator); 31.24.3 Constructors The default constructor uses number and percentage formatters appropriate for the default locale: å public StandardPieSectionLabelGenerator(); Creates a default section label generator. You can create a generator with a specific format string: å public StandardPieSectionLabelGenerator(String labelFormat); Equivalent to StandardPieSectionLabelGenerator(labelFormat, Locale.getInstance())—see be- low. å public StandardPieSectionLabelGenerator(Locale locale); [1.0.7] Equivalent to StandardPieSectionLabelGenerator(DEFAULT SECTION LABEL FORMAT, locale)—see be- low. å public StandardPieSectionLabelGenerator(String labelFormat, Locale locale); [1.0.7] Creates a generator using the specified format string. The item value and percentage (if included in the format string) will be formatted using default formatters for the specified locale. If labelFormat is null, this constructor throws an IllegalArgumentException. The final constructor allows you to specify the item value and percentage formatters: å public StandardPieSectionLabelGenerator(String labelFormat, NumberFormat numberFormat, NumberFormat percentFormat) Creates a generator using the specifed format string, with custom formatters for the item value and item percentage. This constructor throws an IllegalArgumentException if any of the arguments is null. 31.24.4 Methods To get the label for a section: å public String generateSectionLabel(PieDataset dataset, Comparable key); Returns the section label for the data item with the given key. The actual string returned depends on the format string and locale specified in the constructor for this class. 31.24.5 Attributed Labels An option is provided to use AttributedString instances as the section labels, however there is currently no mechanism in the PiePlot class to display these (so, for now, you can just ignored these methods). CHAPTER 31. PACKAGE: ORG.JFREE.CHART.LABELS Code: Description: {0} {1} {2} The item key. The item value. The item value as a percentage of the total. 291 Table 31.5: MessageFormat substitutions å public AttributedString generateAttributedSectionLabel(PieDataset dataset, Comparable key); Returns the attributed label for the section with the given key. This method can return null. The default implementation of the above method just returns fixed strings that are controlled via the following methods: å public AttributedString getAttributedLabel(int series); Returns the attributed label (possibly null). å public void setAttributedLabel(int series, AttributedString label); Sets the attributed label (null is permitted) for the given section. 31.24.6 Equals, Cloning and Serialization This class overrides the equals() method: å public boolean equals(Object obj); Tests this label generator for equality with an arbitrary object. Instances of this class are Cloneable and Serializable. 31.24.7 Notes In version 1.0.2, the default section label format changed to show only the section name (this change affects default pie plots, among other things). 31.25 StandardPieToolTipGenerator 31.25.1 Overview A label generator that can be used to generate tool tips for a PiePlot (this class implements the PieToolTipGenerator interface). The generator uses Java’s MessageFormat class to construct labels by substituting any or all of the objects listed in table 31.5. The default tool tip format string is "{0}: ({1}, {2})", which displays the item key, followed by the item value and percentage. 31.25.2 Usage You can use this class when you want to change the format of the the tool tips on a pie chart. For example: PiePlot plot = (PiePlot) chart.getPlot(); PieToolTipGenerator generator = new StandardPieToolTipGenerator( "{0} = {2}", new DecimalFormat("0"), new DecimalFormat("0.00%")); plot.setToolTipGenerator(generator); 31.25.3 Constructors The default constructor uses number and percentage formatters appropriate for the default locale: å public StandardPieToolTipGenerator(); Equivalent to StandardPieToolTipGenerator(DEFAULT TOOLTIP FORMAT, Locale.getDefault())—see below. CHAPTER 31. PACKAGE: ORG.JFREE.CHART.LABELS 292 You can create a generator with a specific format string: å public StandardPieToolTipGenerator(String labelFormat); Equivalent to StandardPieToolTipGenerator(labelFormat, Locale.getDefault())—see below. å public StandardPieToolTipGenerator(Locale locale); [1.0.7] Equivalent to StandardPieToolTipGenerator(DEFAULT TOOLTIP FORMAT, locale)—see below. å public StandardPieToolTipGenerator(String labelFormat, Locale locale); [1.0.7] Creates a generator using the specified format string. The item value and percentage (if included in the format string) will be formatted using default formatters for the specified locale. The final constructor allows you to specify the item value and percentage formatters: å public StandardPieToolTipGenerator(String labelFormat, NumberFormat numberFormat, NumberFormat percentFormat) Creates a generator using the specifed format string, with custom formatters for the item value and item percentage. 31.25.4 Methods See AbstractPieItemLabelGenerator. 31.25.5 Notes Some points to note: • instances of this class are cloneable and serializable; • section 11 contains information about using tool tips with JFreeChart. See Also PieToolTipGenerator. 31.26 StandardXYItemLabelGenerator 31.26.1 Overview A generator that can be assigned to an XYItemRenderer for the purpose of generating item labels (this class implements the XYItemLabelGenerator interface). This class is very flexible in the format of the labels it can generate. It uses Java’s MessageFormat class to create a label that can contain any of the items listed in table 31.2. The x and y values can be formatted using any instance of NumberFormat or DateFormat. 31.26.2 Usage Most often you will assign a generator to a renderer and then never need to refer to it again: XYPlot plot = (XYPlot) chart.getPlot(); XYItemRenderer renderer = plot.getRenderer(); XYItemLabelGenerator generator = new StandardXYItemLabelGenerator( "{2}", new DecimalFormat("0.00"), new DecimalFormat("0.00") ); renderer.setItemLabelGenerator(generator); renderer.setItemLabelsVisible(true); The renderer will call the generator’s methods when necessary. See section 12 for more information. CHAPTER 31. PACKAGE: ORG.JFREE.CHART.LABELS 31.26.3 293 Constructors To create a default generator: å public StandardXYItemLabelGenerator(); Creates a new generator that formats values using the default number format for the user’s locale. "{2}" is used as the label format string (that is, just the data value). To create a generator that formats the x and y values as numbers: å public StandardXYItemLabelGenerator(String labelFormat, NumberFormat xFormat, NumberFormat yFormat); Creates a generator that formats values as numbers using the supplied formatters. The labelFormat is passed to a MessageFormat to control the structure of the generated label, and can use any of the substitutions listed in table 31.2. To create a generator that formats the x-values as dates (interpreting the numerical value as milliseconds since 1-Jan-1970, in the same way as java.util.Date): å public StandardXYItemLabelGenerator(String labelFormat, DateFormat xFormat, NumberFormat yFormat); Creates a generator that formats values as dates using the supplied formatter. The labelFormat is passed to a MessageFormat to control the structure of the generated label, and can use any of the substitutions listed in table 31.2. å public StandardXYItemLabelGenerator(String formatString, NumberFormat xFormat, DateFormat yFormat); [1.0.4] Creates a generator that formats the x-values as numbers and the y-values as dates. å public StandardXYItemLabelGenerator(String formatString, DateFormat xFormat, DateFormat yFormat); Creates a generator that formats both the x and y-values as dates. 31.26.4 Methods The renderer will call the following method whenever it requires an item label: å public String generateLabel(XYDataset dataset, int series, int item); Generates an item label for the specified data item. 31.26.5 Notes Some points to note: • instances of this class are cloneable and serializable, and the PublicCloneable interface is implemented; See Also AbstractXYItemLabelGenerator, StandardXYToolTipGenerator. 31.27 StandardXYSeriesLabelGenerator 31.27.1 Overview A generator that can be assigned to an XYItemRenderer for the purpose of generating series labels for the legend (this class implements the XYSeriesLabelGenerator interface). This class is very flexible in the format of the labels it can generate. It uses Java’s MessageFormat class to create a label, with {0} being substituted with the series name. CHAPTER 31. PACKAGE: ORG.JFREE.CHART.LABELS 31.27.2 294 Constructors To create a default generator: å public StandardXYSeriesLabelGenerator(); Creates a new generator that formats values with "{0}" used as the label format string (that is, just the series name). To create a generator with a custom format string: å public StandardXYLabelGenerator(String labelFormat); Creates a generator that formats the series label with the given format string. The labelFormat is passed to a MessageFormat to control the structure of the generated label, with {0} being substituted with the series name. 31.27.3 Methods The renderer will call the following method whenever it requires an item label: å public String generateLabel(XYDataset dataset, int series); Generates a label for the specified series. 31.27.4 Notes Some points to note: • instances of this class are cloneable and serializable, and the PublicCloneable interface is implemented; 31.28 StandardXYToolTipGenerator 31.28.1 Overview A generator that can be assigned to an XYItemRenderer for the purpose of generating tooltips (this class implements the XYToolTipGenerator interface). This class is very flexible in the format of the labels it can generate. It uses Java’s MessageFormat class to create a label that can contain any of the items listed in table 31.2. The x and y values can be formatted using any instance of NumberFormat or DateFormat. 31.28.2 Usage You can create a tool tip generator and assign it to a renderer when you wish to control the formatting of the tool tip text. For example: XYPlot plot = (XYPlot) chart.getPlot(); XYItemRenderer renderer = plot.getRenderer(); XYToolTipGenerator generator = new StandardXYToolTipGenerator( "{2}", new DecimalFormat("0.00"), new DecimalFormat("0.00") ); renderer.setToolTipGenerator(generator); The renderer will call the generator’s methods when necessary. See section 11 for more information. For the display of time series data, you will want the x-values to be formatted as dates in the tool tips. You can achieve this by specifying a DateFormat instance as the formatter for the x-values, as follows: XYPlot plot = (XYPlot) chart.getPlot(); XYItemRenderer renderer = plot.getRenderer(); XYToolTipGenerator generator = new StandardXYToolTipGenerator( "{1}, {2}", new SimpleDateFormat("d-MMM-yyyy"), new DecimalFormat("0.00") ); renderer.setToolTipGenerator(generator); CHAPTER 31. PACKAGE: ORG.JFREE.CHART.LABELS 31.28.3 295 Constructors To create a default generator: å public StandardXYToolTipGenerator(); Creates a new generator that formats values using the default number format for the user’s locale. "{0}: ({1}, {2})" is used as the label format string (that is, the series name followed by the x and y values). To create a generator that formats the x and y values as numbers: å public StandardXYToolTipGenerator(String labelFormat, NumberFormat xFormat, NumberFormat yFormat); Creates a generator that formats values as numbers using the supplied formatters. The labelFormat is passed to a MessageFormat to control the structure of the generated label, and can use any of the substitutions listed in table 31.2. To create a generator that formats the x-values as dates (interpreting the numerical value as milliseconds since 1-Jan-1970, in the same way as java.util.Date): å public StandardXYToolTipGenerator(String labelFormat, DateFormat xFormat, NumberFormat yFormat); Creates a generator that formats values as dates using the supplied formatter. The labelFormat is passed to a MessageFormat to control the structure of the generated label, and can use any of the substitutions listed in table 31.2. å public StandardXYToolTipGenerator(String formatString, NumberFormat xFormat, DateFormat yFormat); [1.0.4] Creates a generator that formats the x-values as numbers and the y-values as dates. å public StandardXYToolTipGenerator(String formatString, DateFormat xFormat, DateFormat yFormat); Creates a generator that formats both the x and y-values as dates. 31.28.4 Methods The renderer will call the following method whenever it requires an item label: å public String generateToolTip(XYDataset dataset, int series, int item); Generates a tool tip for the specified data item. 31.28.5 Notes Some points to note: • instances of this class are cloneable and serializable, and the PublicCloneable interface is implemented; See Also AbstractXYItemLabelGenerator, StandardXYItemLabelGenerator. 31.29 StandardXYZToolTipGenerator 31.29.1 Overview A default implementation of the XYZToolTipGenerator interface. This generator is used with the XYBubbleRenderer class. CHAPTER 31. PACKAGE: ORG.JFREE.CHART.LABELS 31.30 SymbolicXYItemLabelGenerator 31.30.1 Overview 296 An item label generator for use with symbolic plots. 31.31 XYItemLabelGenerator 31.31.1 Overview This interface defines the API for an item label generator, which is used by a renderer to obtain labels for the items in a dataset. A generator is assigned to a renderer using the setItemLabelGenerator() method in the XYItemRenderer interface. Classes that implement this interface include: • StandardXYItemLabelGenerator; • SymbolicXYItemLabelGenerator; • BubbleXYItemLabelGenerator; • HighLowItemLabelGenerator. 31.31.2 Usage Chapter 12 contains information about using item labels. 31.31.3 Methods The renderer will call the following method whenever it requires an item label: å public String generateLabel(XYDataset dataset, int series, int item); Returns a string that will be used to label the specified data item. Classes that implement this method are permitted to return null for the result, in which case no label will be displayed for that item. 31.31.4 Notes Some points to note: • the StandardXYItemLabelGenerator class provides a very flexible implementation of this interface, which should meet most requirements. However, you can also write your own class that implements this interface, and take complete control over the generation of item labels; 31.32 XYSeriesLabelGenerator 31.32.1 Overview An xy series label generator is an object that assumes responsibility for generating the text strings that will be used for the series labels in a chart’s legend. A generator is assigned to a renderer using the setLegendItemLabelGenerator() method in the XYItemRenderer interface. Classes that implement this interface include: • StandardXYSeriesLabelGenerator; • MultipleXYSeriesLabelGenerator. CHAPTER 31. PACKAGE: ORG.JFREE.CHART.LABELS 31.32.2 297 Methods The renderer will call the following method whenever it requires a series label for the legend: å public String generateLabel(XYDataset dataset, int series); Returns a string that will be used to label the specified data series. See Also StandardXYSeriesLabelGenerator. 31.33 XYToolTipGenerator 31.33.1 Overview The interface that must be implemented by an XY tool tip generator, a class used to generate tool tips for an XYPlot. 31.33.2 Methods The plot will call the following method whenever it requires a tool tip for an item: å public String generateToolTip(XYDataset dataset, int series, int item); This method is called whenever the plot needs to generate a tooltip for a data item. It can return an arbitrary string, generally derived from the specified item in the supplied dataset.3 31.33.3 Notes Some points to note: • to “install” a tool tip generator, use the setToolTipGenerator() method in the XYItemRenderer interface. • StandardXYToolTipGenerator implements this interface, but you are free to write your own implementation to suit your requirements. Section 11 contains information about using tool tips with JFreeChart. 31.34 XYZToolTipGenerator 31.34.1 Overview A tool tip generator that creates labels for items in an XYZDataset. 31.34.2 Methods This interface adds a single method to the one it inherits from XYToolTipGenerator: å public String generateToolTip(XYZDataset dataset, int series, int item); Returns a (possibly null) string as the tool tip text for the specified item within a given series. 3 If you are implementing this function with a look up table for tool tips, be aware that some XYDataset implementations can reorder the data items, so you will need to ensure that your lookup table is kept in sync with the dataset. CHAPTER 31. PACKAGE: ORG.JFREE.CHART.LABELS 31.34.3 298 Notes Some points to note: • this interface extends XYToolTipGenerator; • the StandardXYZToolTipGenerator class is the only implementation of this interface provided by JFreeChart. Chapter 32 Package: org.jfree.chart.needle 32.1 Overview This package contains classes for drawing needles in a CompassPlot: • ArrowNeedle – an arrow needle; • LineNeedle – a line needle; • LongNeedle – a long needle; • PinNeedle – a pin needle; • PlumNeedle – a plum needle; • PointerNeedle – a pointer needle; • ShipNeedle – a ship needle; • WindNeedle – a wind needle; 32.2 ArrowNeedle 32.2.1 Overview A class that draws an arrow needle for the CompassPlot class (see figure 32.1). Figure 32.1: An arrow needle 299 CHAPTER 32. PACKAGE: ORG.JFREE.CHART.NEEDLE 32.3 LineNeedle 32.3.1 Overview 300 A class that draws a line needle for the CompassPlot class (see figure 32.2). Figure 32.2: A line needle 32.4 LongNeedle 32.4.1 Overview A class that draws a long needle for the CompassPlot class (see figure 32.3). Figure 32.3: A long needle 32.5 MeterNeedle 32.5.1 Overview A base class that draws a needle for the CompassPlot class. A range of different subclasses implement different types of needles: • ArrowNeedle – an arrow needle; • LineNeedle – a line needle; • LongNeedle – a long needle; • PinNeedle – a pin needle; • PlumNeedle – a plum needle; • PointerNeedle – a pointer needle; CHAPTER 32. PACKAGE: ORG.JFREE.CHART.NEEDLE • ShipNeedle – a ship needle; • WindNeedle – a wind needle; 32.6 PinNeedle 32.6.1 Overview A class that draws a pin needle for the CompassPlot class (see figure 32.4). Figure 32.4: A pin needle 32.7 PlumNeedle 32.7.1 Overview A class that draws a plum needle for the CompassPlot class (see figure 32.5). Figure 32.5: A plum needle 301 CHAPTER 32. PACKAGE: ORG.JFREE.CHART.NEEDLE 32.8 PointerNeedle 32.8.1 Overview A class that draws a pointer needle for the CompassPlot class (see figure 32.6). Figure 32.6: A pointer needle 32.9 ShipNeedle 32.9.1 Overview A class that draws a ship needle for the CompassPlot class (see figure 32.7). Figure 32.7: A ship needle 32.10 WindNeedle 32.10.1 Overview A class that draws a wind needle for the CompassPlot class (see figure 32.8). 302 CHAPTER 32. PACKAGE: ORG.JFREE.CHART.NEEDLE Figure 32.8: A wind needle 303 Chapter 33 Package: org.jfree.chart.plot 33.1 Overview The org.jfree.chart.plot package contains: • the Plot base class; • a range of plot subclasses, including PiePlot, CategoryPlot and XYPlot; • various support classes and interfaces. This is an important package, because the Plot classes play a key role in controlling the presentation of data with JFreeChart. 33.2 CategoryMarker 33.2.1 Overview A marker that can be used to highlight a category in a CategoryPlot. The marker can be drawn as a line (see figure 33.1) or as a rectangle (see figure 33.2). Markers are added to the plot using the addDomainMarker() methods in the CategoryPlot class. Figure 33.1: A CategoryMarker drawn as a line 304 CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT 305 Figure 33.2: A CategoryMarker drawn as a rectangle 33.2.2 Constructors To create a new marker, use one of the following constructors: å public CategoryMarker(Comparable key); Creates a marker for the category with the specified key, using Color.gray for the paint and new BasicStroke(1.0f) for the stroke. å public CategoryMarker(Comparable key, Paint paint, Stroke stroke); Creates a marker for the category with the specified key, using the specified paint and stroke. å public CategoryMarker(Comparable key, Paint paint, Stroke stroke, Paint outlinePaint, Stroke outlineStroke, float alpha); Creates a marker for the category with the specified key, using the specified paint and stroke. The alpha value controls the transparency (0.0 is transparent, 1.0 is opaque). 33.2.3 Methods To get the key that links the marker to a category: å public Comparable getKey(); Returns the key for the marker. å public void setKey(Comparable key); [1.0.3] Sets the key for the marker and sends a MarkerChangeEvent to all registered listeners. A flag controls whether the marker is drawn as a thin line in the center of the category or a rectangle covering the whole width of the category: å public boolean getDrawAsLine(); Returns true if the marker should be drawn as a thin line in the middle of the category, and false if the marker should be drawn as a rectangle covering the full width of the category. å public void setDrawAsLine(boolean drawAsLine); Sets the flag that controls whether the marker is drawn as a line or a rectangle, and sends a MarkerChangeEvent to all registered listeners. Other methods are inherited from the Marker class. 33.2.4 Equals, Cloning and Serialization This class overrides the equals() method: å public boolean equals(Object obj); Tests the marker for equality with an arbitrary object. This method returns true if and only if: CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT 306 • obj is not null; • obj is an instanceof CategoryMarker; • obj has the same field values as this marker. Instances of this class are Cloneable and Serializable. 33.2.5 Notes Some points to note: • markers are drawn by the drawDomainMarker() method in the AbstractCategoryItemRenderer class; • CategoryMarker is a subclass of Marker; • demos (CategoryMarkerDemo1 and CategoryMarkerDemo2) illustrating the use of this class are included in the JFreeChart demo collection. 33.3 CategoryPlot 33.3.1 Overview A general plotting class that is most commonly used to display bar charts, but also supports line charts, area charts, stacked area charts and more. A category plot has: • one or more domain axes (instances of CategoryAxis); • one or more range axes (instances of ValueAxis); • one or more datasets (these can be instances of any class that implements the CategoryDataset interface); • one or more renderers (these can be instances of any class that implements the CategoryItemRenderer interface); The plot can be displayed with a horizontal or vertical orientation (see the PlotOrientation class). 33.3.2 Attributes The attributes maintained by the CategoryPlot class, which are in addition to those inherited from the Plot class, are listed in Table 33.1. 33.3.3 Plot Orientation A CategoryPlot can be drawn with one of two orientations: • horizontal orientation – the domain (category) axis will appear at the left or right of the chart, and the range (value) axis will appear at the top or bottom of the chart; • vertical orientation – the domain (category) axis will appear at the top or bottom of the chart and the range (value) axis will appear at the left or right of the chart. The default orientation is PlotOrientation.VERTICAL. To change the plot’s orientation, use the following code: plot.setOrientation(PlotOrientation.HORIZONTAL); Note that calling this method will trigger a PlotChangeEvent that will result in the chart being redrawn if it is being displayed in a ChartPanel. CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT Attribute: Description: orientation axisOffset domainAxes domainAxisLocations rangeAxes rangeAxisLocations datasets renderers The plot orientation (horizontal or vertical). The offset between the data area and the axes. The domain axes (used to display categories). The locations of the domain axes. The range axes (used to display values). The locations of the range axes. The dataset(s). The plot’s renderers (“pluggable” objects responsible for drawing individual data items within the plot). The order for rendering data items (see DatasetRenderingOrder). Controls the column order in which the data items are rendered. Controls the row order in which the data items are rendered. A flag that controls whether gridlines are drawn against the domain axis. The position of the gridlines against the domain axis. The paint used to draw the domain gridlines. The stroke used to draw the domain gridlines. A flag that controls whether gridlines are drawn against the range axis. The paint used to draw the range gridlines. The stroke used to draw the range gridlines. A list of markers (constants) to be highlighted on the plot. A list of markers (constants) to be highlighted on the plot. The weight for the plot (only used when the plot is a subplot). Specifies a fixed amount of space to allocate to the domain axis (null permitted). Specifies a fixed amount of space to allocate to the range axis (null permitted). renderingOrder columnRenderingOrder rowRenderingOrder domainGridlinesVisible domainGridlinePosition domainGridlinePaint domainGridlineStroke rangeGridlinesVisible rangeGridlinePaint rangeGridlineStroke foregroundRangeMarkers backgroundRangeMarkers weight fixedDomainAxisSpace fixedRangeAxisSpace 307 Table 33.1: Attributes for the CategoryPlot class 33.3.4 Axes A CategoryPlot usually has a single domain axis (an instance of the CategoryAxis class) and a single range axis (an instance of the ValueAxis class). You can obtain a reference to the primary domain axis with: CategoryAxis domainAxis = plot.getDomainAxis(); Similarly, you can obtain a reference to the primary range axis with: ValueAxis rangeAxis = plot.getRangeAxis(); The CategoryPlot class also has support for multiple axes. You can obtain a reference to any secondary domain axis by specifying the axis index: CategoryAxis domainAxis2 = plot.getDomainAxis(1); Similarly, you can obtain a reference to any secondary range axis by specifying the axis index: ValueAxis rangeAxis2 = plot.getRangeAxis(1); To find the index for an axis: å public int getDomainAxisIndex(CategoryAxis axis); [1.0.3] Returns the index for the specified axis, or -1 if the axis does not belong to the plot. If axis is null, this method throws an IllegalArgumentException. å public int getRangeAxisIndex(ValueAxis axis); [1.0.7] Returns the index for the specified axis, or -1 if the axis does not belong to the plot. If axis is null, this method throws an IllegalArgumentException. The axis classes have many attributes that can be customised to control the appearance of your charts. CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT 33.3.5 308 Axis Offsets The axes can be offset slightly from the edges of the plot area, if required: å public RectangleInsets getAxisOffset(); Returns the object that controls the offset between the plot area and the axes. The default value is RectangleInsetsZERO INSETS. å public void setAxisOffset(RectangleInsets offset); Sets the object that controls the offset between the plot area and the axes, and sends a PlotChangeEvent to all registered listeners. If offset is null, this method throws an IllegalArgumentException. 33.3.6 Datasets and Renderers A CategoryPlot can have zero, one or many datasets and each dataset is usually associated with a renderer (the object that is responsible for drawing the visual representation of each item in a dataset). A dataset is an instance of any class that implements the CategoryDataset interface and a renderer is an instance of any class that implements the CategoryItemRenderer interface. To get/set a dataset: å public CategoryDataset getDataset(int index); Returns the dataset at the specified index (possibly null). å public void setDataset(int index, CategoryDataset dataset); Assigns a dataset to the plot. The new dataset replaces any existing dataset at the specified index. It is permitted to set a dataset to null (in that case, no data will be displayed on the chart). To get/set a renderer: å public CategoryItemRenderer getRenderer(int index); Returns the renderer at the specified index (possibly null). å public void setRenderer(int index, CategoryItemRenderer renderer); Sets the renderer at the specified index and sends a PlotChangeEvent to all registered listeners. It is permitted to set any renderer to null. 33.3.7 Dataset Rendering Order When a plot has more than one dataset, the order in which the datasets are rendered can have an impact on the final appearance of the chart. For example, if one dataset is represented using bars, and the other is represented using lines, you’ll normally want the lines to be drawn in front of the bars. By default, the datasets are drawn in reverse order, so that the first dataset you add appears at the front of the chart. You can control the rendering order using the following methods: å public DatasetRenderingOrder getDatasetRenderingOrder(); Returns the current dataset rendering order (never null). The default is DatasetRenderingOrder.REVERSE. å public void setDatasetRenderingOrder(DatasetRenderingOrder order); Sets the dataset rendering order and sends a PlotChangeEvent to all registered listeners. It is not permitted to set the rendering order to null. By default, datasets will be rendered in reverse order so that the first dataset added to the plot appears to be in front of the other datasets. 33.3.8 Item Rendering Order Within each dataset, the data items are rendered by column then by row, in ascending order (by default). In some cases, you might need to change the order in which the items are rendered (it only matters when the renderer draws items in such a way that they can overlap with other items, for example the bars drawn by a BarRenderer3D): CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT 309 å public SortOrder getColumnRenderingOrder(); Returns the column rendering order (the default is SortOrder.ASCENDING). This method never returns null. å public void setColumnRenderingOrder(SortOrder order); Sets the column rendering order and sends a PlotChangeEvent to all registered listeners. This method throws an IllegalArgumentException if order is null. å public SortOrder getRowRenderingOrder(); Returns the row rendering order (the default is SortOrder.ASCENDING). This method never returns null. å public void setRowRenderingOrder(SortOrder order); Sets the row rendering order and sends a PlotChangeEvent to all registered listeners. This method throws an IllegalArgumentException if order is null. Note that the above methods do not change the position of the items, only the order in which they get drawn. 33.3.9 Series Colors The colors used for the series within the chart are controlled by the plot’s renderer(s). You can obtain a reference to the primary renderer and set the series colors using code similar to the following: CategoryPlot plot = (CategoryPlot) chart.getPlot(); CategoryItemRenderer renderer = plot.getRenderer(); renderer.setSeriesPaint(0, new Color(0, 0, 255)); renderer.setSeriesPaint(1, new Color(75, 75, 255)); renderer.setSeriesPaint(2, new Color(150, 150, 255)); 33.3.10 Gridlines By default, the CategoryPlot class will display gridlines against the (primary) range axis, but not the domain axis. However, it is simple to override the default behaviour: CategoryPlot plot = (CategoryPlot) chart.getPlot(); plot.setDomainGridlinesVisible(true); plot.setRangeGridlinesVisible(true); Note that the domain and range gridlines are controlled independently. 33.3.11 Legend Items The items that appear in the legend for a chart are obtained by a call to the following method at the time the chart is being drawn: å public LegendItemCollection getLegendItems(); Returns the collection of legend items that should be displayed in the legend for this plot. Note that a new collection is returned each time this method is called—modifying the returned collection has no effect on the legend displayed by the chart. By default, this method will return a collection that contains one item for each series in the dataset(s) belonging to the plot. If this is not the behaviour you require, there are a couple of options for altering the items that will appear in the chart’s legend. First, you can specify a “fixed” set of legend items that will always be displayed, regardless of the contents of the dataset(s): å public void setFixedLegendItems(LegendItemCollection items); Sets a “fixed” collection of legend items that will always be used for this plot regardless of the contents of the dataset(s) belonging to the plot. Set this to null if you wish to revert to the default behaviour. A second, but more complex, approach involves subclassing CategoryPlot and overriding the getLegendItems() method. This gives you complete control over the legend items included for your plot. CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT 33.3.12 310 Fixed Axis Dimensions The width and height of the axes are normally determined by JFreeChart to allow just the required amount of space, no more and no less. Occasionally, you may want to override this behaviour and specify a fixed amount of space to allocate to each axis. As an example, this can make it easier to align the contents of multiple charts. å public AxisSpace getFixedDomainAxisSpace(); Returns the fixed dimensions for the domain axis (possibly null). å public void setFixedDomainAxisSpace(AxisSpace space); Sets the fixed dimensions for the domain axis. Set this to null if you prefer JFreeChart to determine this dynamically (the default behaviour). å public AxisSpace getFixedRangeAxisSpace(); Returns the fixed dimensions for the range axis (possibly null). å public void setFixedRangeAxisSpace(AxisSpace space); Sets the fixed dimensions for the range axis. Set this to null if you prefer JFreeChart to determine this dynamically (the default behaviour). 33.3.13 Crosshair This plot has support for a crosshair against the primary range axis. The following flag controls whether or not the plot displays the crosshair: å public boolean isRangeCrosshairVisible(); Returns the flag that controls whether or not the plot displays a crosshair against the range axis. The default value is false. å public void setRangeCrosshairVisible(boolean flag); Sets the flag that controls whether or not the plot displays a crosshair against the range axis, and sends a PlotChangeEvent to all registered listeners. The crosshair value is updated when the user clicks on a ChartPanel that displays this plot. A flag controls whether the crosshair is set to the value corresponding to the mouse click, or the nearest actual data value: å public boolean isRangeCrosshairLockedOnData(); Returns the flag that controls whether or not the crosshair point locks onto the nearest data value. The default value is true. å public void setRangeCrosshairLockedOnData(boolean flag); Sets the flag that controls whether or not the crosshair point locks onto the nearest data value, and sends a PlotChangeEvent to all registered listeners. To control the current crosshair value: å public double getRangeCrosshairValue(); Returns the current crosshair value. Note that after a mouse click, this value will change during the chart repaint—to read the latest value, you need to wait until the chart has finished repainting. å public void setRangeCrosshairValue(double value); Equivalent to setRangeCrosshairValue(value, true)—see the next method. å public void setRangeCrosshairValue(double value, boolean notify); Sets the crosshair value and, if requested, sends a PlotChangeEvent to all registered listeners. To control the paint and stroke used to draw the crosshair line: å public Stroke getRangeCrosshairStroke(); Returns the stroke used to draw the crosshair. The default stroke is a thin dashed line. This method never returns null. å public void setRangeCrosshairStroke(Stroke stroke); Sets the stroke used to draw the crosshair and sends a PlotChangeEvent to all registered listeners. CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT 311 å public Paint getRangeCrosshairPaint(); Returns the paint used to draw the crosshair. The default value is Color.blue. This method never returns null. å public void setRangeCrosshairPaint(Paint paint); Sets the paint used to draw the crosshair and sends a PlotChangeEvent to all registered listeners. If paint is null, this method throws an IllegalArgumentException. 33.3.14 Methods A zoom method is provided to support the zooming function provided by the ChartPanel class: å public void zoom(double percent); Increases or decreases the axis range (about the anchor value) by the specified percentage. If the percentage is zero, then the auto-range calculation is restored for the value axis. The category axis remains fixed during zooming, only the value axis changes. To add a range marker to a plot: å public void addRangeMarker(Marker marker); Adds a marker which will be drawn against the range axis. To add an annotation to a plot: å public void addAnnotation(CategoryAnnotation annotation); Adds an annotation to the plot. To set the weight for a plot: å public void setWeight(int weight); Sets the weight for a plot. This is used to determine how much space is allocated to the plot when it is used as a subplot within a combined plot. 33.3.15 Draw Method The following method is called by the JFreeChart class during chart drawing: å public void draw(Graphics2D g2, Rectangle2D plotArea, Point2D anchor, PlotState parentState, PlotRenderingInfo state); Draws the plot within the specified area. In typical situations, you won’t normally call this method directly. 33.3.16 Notes A number of CategoryItemRenderer implementations are included in the JFreeChart distribution. See Also CombinedDomainCategoryPlot, CombinedRangeCategoryPlot. 33.4 ColorPalette 33.4.1 Overview The abstract base class for the color palettes used by the ContourPlot class. This class is deprecated as of version 1.0.4. CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT 312 Figure 33.3: A CombinedDomainCategoryPlot 33.5 CombinedDomainCategoryPlot 33.5.1 Overview A category plot that allows multiple subplots to be displayed together using a shared domain axis— see figure 33.3 for an example. 33.5.2 Constructors To create a new parent plot: å public CombinedDomainCategoryPlot(); Creates a new parent plot that uses a default CategoryAxis for the shared domain axis. å public CombinedDomainCategoryPlot(CategoryAxis domainAxis); Creates a new parent plot with the specified domain axis (null not permitted). After creating a new parent plot, you need to add some subplots. 33.5.3 Adding and Removing Subplots To add a subplot to a combined plot: å public void add(CategoryPlot subplot); Adds a subplot to the combined plot, with a weight of 1, and sends a PlotChangeEvent to all registered listeners. Adding a null subplot is not permitted. The subplot’s domain axis will be set to null. You must ensure that the subplot has a non-null range axis. See the following method for a description of the weight. å public void add(CategoryPlot subplot, int weight); Adds a subplot to the combined plot, with the specified weight, and sends a PlotChangeEvent to all registered listeners. Adding a null subplot is not permitted. The subplot’s domain axis will be set to null. You must ensure that the subplot has a non-null range axis. The weight determines how much of the plot area is assigned to the subplot. For example, if you add three subplots with weights of 1, 2 and 4, the relative amount of space assigned to each plot is 1/7, 2/7 and 4/7 (where the 7 is the sum of the individual weights). To remove a subplot: å public void remove(CategoryPlot subplot); Removes the specified subplot and sends a PlotChangeEvent to all registered listeners. To get a list of the subplots: å public List getSubplots(); Returns an unmodifiable list of the subplots. CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT 33.5.4 313 Draw Method The following method is called by the JFreeChart class during chart drawing: å public void draw(Graphics2D g2, Rectangle2D plotArea, Point2D anchor, PlotState parentState, PlotRenderingInfo state); Draws the plot within the specified area. In typical situations, you won’t normally call this method directly. 33.5.5 Notes The CombinedCategoryPlotDemo1.java file (included in the JFreeChart demo collection) provides an example of this type of plot. See Also CombinedRangeCategoryPlot. 33.6 CombinedDomainXYPlot 33.6.1 Overview A subclass of XYPlot that allows you to combined multiple plots on one chart, where the subplots share the domain axis, and maintain their own range axes. Figure 33.4 illustrates the relationship between the CombinedDomainXYPlot and its subplots). CombinedDomainXYPlot shared range axis = null Subplot 1 independent range axes Subplot 2 domain axes = null Subplot 3 shared domain axis Figure 33.4: CombinedDomainXYPlot axes The CombinedXYPlotDemo1 class (included in the JFreeChart demo collection) provides an example of this type of plot. 33.6.2 Constructors The default constructor creates a plot with no subplots (initially) and a NumberAxis for the shared domain axis: å public CombinedDomainXYPlot(); Creates a new parent plot. CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT 314 More commonly, you will supply the shared domain axis: å public CombinedDomainXYPlot(ValueAxis domainAxis); Creates a new parent plot using the specified domainAxis (null permitted). After creating the parent plot, you need to add subplots. 33.6.3 Methods To add a subplot to a combined plot: å public void add(XYPlot subplot); Adds a subplot to the combined plot, with a weight of 1, and sends a PlotChangeEvent to all registered listeners. Adding a null subplot is not permitted. The subplot’s domain axis will be set to null. You must ensure that the subplot has a non-null range axis. See the next method for a description of the weight. å public void add(XYPlot subplot, int weight); Adds a subplot to the combined plot, with the specified weight, and sends a PlotChangeEvent to all registered listeners. Adding a null subplot is not permitted. The subplot’s domain axis will be set to null. You must ensure that the subplot has a non-null range axis. The weight determines how much of the plot area is assigned to the subplot. For example, if you add three subplots with weights of 1, 2 and 4, the relative amount of space assigned to each plot is 1/7, 2/7 and 4/7 (where the 7 is the sum of the individual weights). To remove a subplot: å public void remove(XYPlot subplot); Removes the specified subplot and sends a PlotChangeEvent to all registered listeners. 33.6.4 The Plot Orientation To set the plot orientation: å public void setOrientation(PlotOrientation orientation); Sets the orientation of this plot and all its subplots. 33.6.5 The Gap Between Subplots To control the amount of space between the subplots: å public double getGap(); Returns the gap between subplots, in Java2D units. å public void setGap(double gap); Sets the gap (in points) between the subplots and sends a PlotChangeEvent to all registered listeners. 33.6.6 Notes Some points to note: • the dataset for this class should be set to null (only the subplots display data); • the subplots managed by this class should have one axis set to null (the shared axis is maintained by this class); • you do not need to set a renderer for the plot, since each subplot maintains its own renderer; • a demonstration of this type of plot is described in section ??. CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT 315 See Also XYPlot. 33.7 CombinedRangeCategoryPlot 33.7.1 Overview A category plot that allows multiple subplots to be displayed together using a shared range axis— —see figure 33.5 for an example. Figure 33.5: A CombinedRangeCategoryPlot 33.7.2 Constructors To create a new parent plot: å public CombinedRangeCategoryPlot(); Creates a new parent plot that uses a default NumberAxis for the shared range axis. å public CombinedRangeCategoryPlot(ValueAxis rangeAxis); Creates a new parent plot with the specified range axis (null not permitted). After creating a new parent plot, you need to add some subplots. 33.7.3 Adding and Removing Subplots To add a subplot to a combined plot: å public void add(CategoryPlot subplot); Adds a subplot to the combined plot, with a weight of 1, and sends a PlotChangeEvent to all registered listeners. Adding a null subplot is not permitted. You must ensure that the subplot’s domain axis is not null. The subplot’s range axis will be set to null. å public void add(CategoryPlot subplot, int weight); Adds a subplot to the combined plot, with the specified weight, and sends a PlotChangeEvent to all registered listeners. Adding a null subplot is not permitted. You must ensure that the subplot’s domain axis is not null. The subplot’s range axis will be set to null. The weight determines how much of the plot area is assigned to the subplot. For example, if you add three subplots with weights of 1, 2 and 4, the relative amount of space assigned to each plot is 1/7, 2/7 and 4/7 (where the 7 is the sum of the individual weights). To remove a subplot: CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT 316 å public void remove(CategoryPlot subplot); Removes the specified subplot and sends a PlotChangeEvent to all registered listeners. To get a list of the subplots: å public List getSubplots(); Returns an unmodifiable list of the subplots. 33.7.4 Draw Method The following method is called by the JFreeChart class during chart drawing: å public void draw(Graphics2D g2, Rectangle2D plotArea, Point2D anchor, PlotState parentState, PlotRenderingInfo state); Draws the plot within the specified area. In typical situations, you won’t normally call this method directly. 33.7.5 Notes The CombinedCategoryPlotDemo2.java file (included in the JFreeChart demo collection) provides an example of this type of plot. 33.8 CombinedRangeXYPlot 33.8.1 Overview A subclass of XYPlot that allows you to combined multiple plots on one chart, where the subplots share a single range axis, and maintain their own domain axes. Figure 33.6 illustrates the relationship between the CombinedRangeXYPlot and its subplots). CombinedXYPlot (VERTICAL) shared range axis = null Subplot 1 independent range axes Subplot 2 domain axes = null Subplot 3 shared domain axis Figure 33.6: CombinedRangeXYPlot axes The CombinedRangeXYPlotDemo class provides an example of this type of plot. CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT 33.8.2 317 Methods There are two methods for adding a subplot to a combined plot: å public void add(XYPlot subplot); Adds a subplot to the combined plot, with a weight of 1. Adding a null subplot is not permitted. You must ensure that the subplot has a non-null domain axis. The subplot’s range axis will be set to null. å public void add(XYPlot subplot, int weight); Adds a subplot to the combined plot, with the specified weight. Adding a null subplot is not permitted. You must ensure that the subplot has a non-null domain axis. The subplot’s range axis will be set to null. The weight determines how much of the plot area is assigned to the subplot. For example, if you add three subplots with weights of 1, 2 and 4, the relative amount of space assigned to each plot is 1/7, 2/7 and 4/7 (where the 7 is the sum of the individual weights). To remove a subplot: å public void remove(XYPlot subplot); Removes the specified subplot and sends a PlotChangeEvent to all registered listeners. If subplot is null, this method throws an IllegalArgumentException. To control the amount of space between the subplots: å public void setGap(double gap); Sets the gap (in points) between the subplots. 33.8.3 Notes Some points to note: • the dataset for this class should be set to null (only the subplots display data); • the subplots managed by this class should have one axis set to null (the shared axis is maintained by this class);. • you do not need to set a renderer for the plot, since each subplot maintains its own renderer; • each subplot uses its own series colors. You should modify the default colors to ensure that the items for each subplot are uniquely colored; • a demonstration of this type of plot is described in section 14.5. 33.9 CompassPlot 33.9.1 Overview A compass plot presents directional data in the form of a compass dial—an example is shown in figure 33.7. 33.9.2 Constructors To create a new instance: å public CompassPlot(); Creates a new CompassPlot instance using an instance of DefaultValueDataset for the current value. å public CompassPlot(ValueDataset dataset); Creates a new CompassPlot instance using the specified dataset (which may be null). CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT Figure 33.7: A chart that uses CompassPlot 33.9.3 General Attributes To control the background color of the interior of the compass: å public Paint getRoseCenterPaint(); Returns the paint (never null) used to fill the interior of the compass dial. The default is Color.white. å public void setRoseCenterPaint(Paint paint); Sets the paint used to fill the interior of the compass dial and sends a PlotChangeEvent to all registered listeners. If paint is null, this method throws an IllegalArgumentException. To control the color of the compass border: å public Paint getRosePaint(); Returns the paint (never null) used to fill the outer border of the compass dial. The default is Color.yellow. å public void setRosePaint(Paint paint); Sets the paint used to fill the outer border of the compass dial and sends a PlotChangeEvent to all registered listeners. If paint is null, this method throws an IllegalArgumentException. The compass border is outlined with a highlight color: å public Paint getRoseHighlightPaint(); Returns the paint (never null) used to draw the edges of the outer border of the compass dial. The default is Color.black. å public void setRoseHighlightPaint(Paint paint); Sets the paint used to draw the edges of the outer border of the compass dial and sends a PlotChangeEvent to all registered listeners. If paint is null, this method throws an IllegalArgumentException. 33.9.4 The Plot Border To control whether or not the plot’s border/background is drawn: å public boolean getDrawBorder(); Returns the flag that controls whether or not the plot’s border is drawn. The default value is false. å public void setDrawBorder(boolean status); Sets the flag that controls whether or not the plot’s border is drawn. No change event is generated (this may change in the future). 318 CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT 33.9.5 319 Datasets A typical plot will use a single dataset (an instance of ValueDataset), but it is also possible to display the values from multiple datasets. å public ValueDataset[] getDatasets(); Returns an array containing references to this plot’s dataset(s). å public void addDataset(ValueDataset dataset); Equivalent to addDataset(dataset, null)—see the next method description. å public void addDataset(ValueDataset dataset, MeterNeedle needle); Adds a dataset (and corresponding needle) to the plot. 33.9.6 Needles The value from each dataset is displayed using a needle. To customise the appearance of the needle(s), use the following methods: å public void setSeriesNeedle(int type); Equivalent to setSeriesNeedle(0, type);—see the next method. å public void setSeriesNeedle(int index, int type); Sets the type of needle for the dataset specified by index. Recognised types are: • 0 – an instance of ArrowNeedle; • 1 – an instance of LineNeedle; • 2 – an instance of LongNeedle; • 3 – an instance of PinNeedle; • 4 – an instance of PlumNeedle; • 5 – an instance of PointerNeedle; • 6 – an instance of ShipNeedle; • 7 – an instance of WindNeedle; • 8 – an instance of ArrowNeedle; • 9 – an instance of MiddlePinNeedle; Note the duplication in items 0 and 8. To customise the needle used to display the value from a dataset: å public void setSeriesNeedle(int index, MeterNeedle needle); Sets the needle for the dataset specified by index and sends a PlotChangeEvent to all registered listeners. å public void setSeriesPaint(int series, Paint paint); Sets the fill paint for the needle associated with the dataset specified by the series index. å public void setSeriesOutlinePaint(int series, Paint p); Sets the outline paint for the needle associated with the dataset specified by the series index. å public void setSeriesOutlineStroke(int series, Stroke stroke); Sets the outline stroke for the needle associated with the dataset specified by the series index. 33.9.7 General Methods The compass plot does not display a legend, so the getLegendItems() method is overridden to return null: å public LegendItemCollection getLegendItems(); Returns null, so no legend items are displayed. The scale for a full revolution of the compass is controlled by the following methods: CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT 320 å public double getRevolutionDistance(); Returns the length of a full revolution for the compass. The default value is 360.0, because the compass displays degree values. å public void setRevolutionDistance(double size); Sets the length of a full revolution for the compass. 33.9.8 Labels Several label attributes are provided by this class, but never used (deprecate?). The label type is controlled via the following methods: å public int getLabelType(); Returns the label type, which is one of: • CompassPlot.NO LABELS; • CompassPlot.VALUE LABELS; The default value is CompassPlot.NO LABELS. This attribute is not currently used. å public void setLabelType(int type); Sets the label type and sends a PlotChangeEvent to all registered listeners. The label font: å public Font getLabelFont(); Returns the label font. The default value is null. This attribute is not currently used. å public void setLabelFont(Font font); Sets the label font and sends a PlotChangeEvent to all registered listeners. 33.9.9 Draw Method The following method is called by the JFreeChart class during chart drawing: å public void draw(Graphics2D g2, Rectangle2D area, Point2D anchor, PlotState parentState, PlotRenderingInfo info); Draws the plot within the specified area. In typical situations, you won’t normally call this method directly. 33.9.10 Notes Some points to note: • there is a demonstration CompassDemo1.java application included in the JFreeChart demo collection. 33.10 ContourPlot 33.10.1 Overview A custom plot that displays (x, y, z) data in the form of a 2D contour plot. This class is deprecated as of version 1.0.4. 33.10.2 Draw Method The following method is called by the JFreeChart class during chart drawing: å public void draw(Graphics2D g2, Rectangle2D plotArea, Point2D anchor, PlotState parentState, PlotRenderingInfo state); Draws the plot within the specified area. In typical situations, you won’t normally call this method directly. CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT 33.11 ContourPlotUtilities 33.11.1 Overview 321 A class that contains static utility methods used by the contour plot implementation. This class is deprecated as of version 1.0.4. 33.12 ContourValuePlot 33.12.1 Overview An interface used by the contour plot implementation. This interface is deprecated as of version 1.0.4. 33.13 CrosshairState 33.13.1 Overview This class maintains information about the crosshairs on a plot, as the plot is being rendered. Crosshairs will often need to “lock on” to the data point nearest to the anchor point (which is usually set by a mouse click). This class keeps track of the data item that is “closest” (either in screen space or in data space) to the anchor point. 33.13.2 Constructors The default constructor: å public CrosshairState(); Creates a new instance where distance is calculated in screen space. å public CrosshairState(boolean calculateDistanceInDataSpace); Creates a new instance where you can select to measure distance in data space or screen space. 33.13.3 Methods The following method is called as a plot is being rendered: å public void updateCrosshairPoint(double candidateX, double candidateY); Considers the candidate point and updates the crosshair point if the candidate is the “closest” to the anchor point. 33.14 DatasetRenderingOrder 33.14.1 Overview This class defines the tokens that can be used to specify the dataset rendering order in a CategoryPlot or an XYPlot. There are two tokens defined, as listed in table 33.2. Token: Description: DatasetRenderingOrder.FORWARD The primary dataset is rendered first, so that it appears to be “underneath” the other datasets. The primary dataset is rendered last, so it appears to be “on top” of the other datasets. DatasetRenderingOrder.REVERSE Table 33.2: DatasetRenderingOrder tokens The default setting is DatasetRenderingOrder.REVERSE—this ensures that the primary dataset appears “on top” of the secondary datasets. CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT 33.14.2 322 Usage To change the rendering order, use the following code: CategoryPlot plot = (CategoryPlot) chart.getPlot(); plot.setDatasetRenderingOrder(DatasetRenderingOrder.FORWARD); 33.14.3 Notes Some points to note: • an example (OverlaidBarChartDemo1.java) is included in the JFreeChart demo collection. 33.15 DefaultDrawingSupplier 33.15.1 Overview A default class used to provide a sequence of unique Paint, Stroke and Shape objects to be used by renderers when drawing charts (this class implements the DrawingSupplier interface). 33.15.2 Usage Every Plot class is initialised with an instance of this class as its drawing supplier, and it is unlikely that you would need to use this class directly. However, you might create your own class that implements the DrawingSupplier interface, and register it with the plot, as a way of overriding the default series colours, line styles and shapes. 33.15.3 Constructors The default constructor creates a drawing supplier with default sequences: å public DefaultDrawingSupplier(); Creates a new drawing supplier with default sequences: • the paint sequence is obtained from the createDefaultPaintArray() method in the ChartColor class; • the fill paint sequence contains just one colour (Color.white); • the outline paint sequence contains just one colour (Color.lightGray); • the stroke sequence contains just one stroke (BasicStroke(1.0f, BasicStroke.CAP SQUARE, BasicStroke.JOIN BEVEL)); • the outline stroke sequence contains just one stroke (BasicStroke(1.0f, BasicStroke.CAP SQUARE, BasicStroke.JOIN BEVEL)); • the shape sequence contains 10 shapes defined by the createStandardSeriesShapes() method. The alternate constructor allows you to supply your own sequences: å public DefaultDrawingSupplier(Paint[] paintSequence, Paint[] outlinePaintSequence, Stroke[] strokeSequence, Stroke[] outlineStrokeSequence, Shape[] shapeSequence); Creates a new drawing supplier with the specified sequences. None of the arrays should be null, nor should they contain null items.1 1 This is not currently enforced. CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT 33.15.4 323 Methods To get the next paint in the sequence: å public Paint getNextPaint(); Returns the next item in the paint sequence. This method should never return null. To get the next fill paint in the sequence: å public Paint getNextFillPaint(); [1.0.6] Returns the next item in the fill paint sequence. This method should never return null. This method was first introduced in JFreeChart 1.0.6. To get the next outline paint in the sequence: å public Paint getNextOutlinePaint(); Returns the next item in the outline paint sequence. This method should never return null. To get the next stroke in the sequence: å public Stroke getNextStroke(); Returns the next item in the stroke sequence. This method should never return null. To get the next outline stroke in the sequence: å public Stroke getNextOutlineStroke(); Returns the next item in the outline stroke sequence. This method should never return null. To get the next shape in the sequence: å public Shape getNextShape(); Returns the next shape in the outline stroke sequence. This method should never return null. The following method defines the default shape sequence for JFreeChart: å public static Shape[] createStandardSeriesShapes(); Returns an array containing ten “standard” shapes. 33.15.5 Equals, Cloning and Serialization To test for equality with an arbitrary object: å public boolean equals(Object obj); Tests this drawing supplier for equality with an arbitrary object (null permitted) Instances of this class are cloneable (the PublicCloneable interface is implemented) and serializable. 33.15.6 Notes This class provides a default implementation of the DrawingSupplier interface. 33.16 DialShape 33.16.1 Overview This class defines the tokens that can be used to specify the dial shape in a MeterPlot. There are three tokens defined, as listed in table 33.3. Token: Description: DialShape.CIRCLE DialShape.CHORD DialShape.PIE A circle. A chord. A pie. Table 33.3: DialShape tokens The result of applying each shape to a MeterPlot is illustrated in figure 33.8. CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT 324 Figure 33.8: DialShape examples 33.16.2 Usage The MeterPlot class has a method named setDialShape() that accepts the tokens defined by this class, for example plot.setDialShape(DialShape.CHORD); 33.17 DrawingSupplier 33.17.1 Overview A drawing supplier provides a limitless (but ultimately repeating) sequence of Paint, Stroke and Shape objects that can be used by renderers when drawing charts. All Plot classes will have a default drawing supplier. This provides a single source for colors and line styles, which is particularly useful for avoiding duplicates when a plot has multiple renderers. You can register your own drawing supplier with a plot if you want to modify the default behaviour. If you do this, you need to call the plot’s setDrawingSupplier() method before the chart is first drawn (the reason being that the plot’s renderer(s) will cache the values returned by the drawing supplier the first time a chart is drawn—subsequent changes to the drawing supplier will have no effect on the values already cached). In version 1.0.6, a new method (getNextFillPaint()) was added to this interface (breaking backwards compatibility for those that implement their own custom drawing suppliers). 33.17.2 Interface Methods This interface defines the following methods: å public Paint getNextPaint(); Returns the next Paint object in the sequence (never null). These are usually used as the default series colors in charts. å public Paint getNextOutlinePaint(); Returns the next outline Paint object in the sequence (never null). å public Paint getNextFillPaint(); [1.0.6] Returns the next fill Paint object in the sequence (never null). This method was added to the interface at version 1.0.6. å public Stroke getNextStroke(); Returns the next Stroke object in the sequence (never null). These are usually used as the default series line style in charts. CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT 325 å public Stroke getNextOutlineStroke(); Returns the next outline Stroke object in the sequence (never null). å public Shape getNextShape(); Returns the next Shape object in the sequence (never null). The shapes returned by this method should be centered on (0, 0) in Java2D coordinates. 33.17.3 Notes Some points to note: • the DefaultDrawingSupplier class provides an implementation of this interface; • if you write your own implementation of this interface, you should ensure that it implements the PublicCloneable interface and is serializable. Otherwise, plots that use your implementation will no longer be cloneable or serializable. 33.18 FastScatterPlot 33.18.1 Overview A custom plot that aims to be fast rather than flexible. It displays a single data series in a scatter plot format (that is, a dot to represent each data item). A couple of techniques are used to make this plot type faster than the other plot types provided by JFreeChart: • data is obtained directly from an array rather than via the XYDataset interface; • the plot draws each point directly rather than using a plug-in renderer. 33.18.2 Constructors This class has two constructors: å public FastScatterPlot(); Creates a new plot with no data, and axes labelled “X” and “Y”. å public FastScatterPlot(float[][] data, ValueAxis domainAxis, ValueAxis rangeAxis); Creates a new plot with the specified data and axes. For a description of the data array format, see section 33.18.3. If domainAxis or rangeAxis is null, this constructor throws an IllegalArgumentException. 33.18.3 The Data The data for this plot is supplied as an array containing two equal-length subarrays—one for the x-values and one for the y-values. The following sample code illustrates the creation of a small data array in the correct format: float[] x = new float[] { 1.0f, 2.0f, 5.0f, 6.0f }; float[] y = new float[] { 7.3f, 2.7f, 8.9f, 1.0f }; float[][] data = new float[][] { x, y }; To get/set the data array for the plot: å public float[][] getData(); Returns a reference to the data array used by this plot (this might be null). Note that if you update the values in the array directly, the chart will NOT be automatically repainted (as there is no mechanism to notify the chart that the dataset has been updated). å public void setData(float[][] data); Sets the data array for the plot, replacing any existing data, and sends a PlotChangeEvent to all registered listeners. If you set this to null, no data is displayed in the plot. CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT 33.18.4 326 The Axes This plot supports a single domain (x) axis and a single range (y) axis. To control the domain axis: å public ValueAxis getDomainAxis(); Returns the domain axis for the plot (never null). å public void setDomainAxis(ValueAxis axis); [1.0.3] Sets the domain axis for the plot, and sends a PlotChangeEvent to all registered listeners. If axis is null, this method throws an IllegalArgumentException. To control the range axis: å public ValueAxis getRangeAxis(); Returns the range axis for the plot (never null). å public void setRangeAxis(ValueAxis axis); [1.0.3] Sets the range axis for the plot, and sends a PlotChangeEvent to all registered listeners. If axis is null, this method throws an IllegalArgumentException. A utility method returns the range of data values for either of the plot’s axes: å public Range getDataRange(ValueAxis axis); Returns the range of values in the current dataset for the specified axis. If axis does not belong to the plot, this method returns null. 33.18.5 Rendering For efficiency, this plot renders the data items directly, rather than via a plug-in renderer. You can modify the color used to draw the dots for each data item: å public Paint getPaint(); Returns the paint used to draw the dot for each data item (never null). The default value is Color.RED. å public void setPaint(Paint paint); Sets the paint used to draw the dot for each data item, and sends a PlotChangeEvent to all registered listeners. Only one rendering color is defined, because this plot can only display data for a single series. 33.18.6 Gridlines You can display gridlines against the domain axis and/or the range axis. For both sets of gridlines, you can control: • the visibility of the gridlines (whether or not they are displayed at all); • the color of the gridlines; • the line style for the gridlines; For the domain axis gridlines: å public boolean isDomainGridlinesVisible(); Returns true if gridlines are drawn for the domain axis, and false otherwise. The default value is true. å public void setDomainGridlinesVisible(boolean visible); Sets a flag that controls whether or not the gridlines are displayed and sends a PlotChangeEvent to all registered listeners. å public Paint getDomainGridlinePaint(); Returns the paint used to draw the domain axis gridlines (never null). The default value is Color.lightGray. CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT 327 å public void setDomainGridlinePaint(Paint paint); Sets the paint used to draw the domain axis gridlines and sends a PlotChangeEvent to all registered listeners. If paint is null, this method throws an IllegalArgumentException. å public Stroke getDomainGridlineStroke(); Returns the stroke used to draw the domain axis gridlines (never null). The default stroke is a thin dashed line. å public void setDomainGridlineStroke(Stroke stroke); Sets the stroke used to draw the domain axis gridlines and sends a PlotChangeEvent to all registered listeners. If stroke is null, this method throws an IllegalArgumentException. Similarly, for the range axis gridlines: å public boolean isRangeGridlinesVisible(); Returns true if gridlines are drawn for the range axis, and false otherwise. The default value is true. å public void setRangeGridlinesVisible(boolean visible); Sets a flag that controls whether or not the gridlines are displayed and sends a PlotChangeEvent to all registered listeners. å public Paint getRangeGridlinePaint(); Returns the paint used to draw the range axis gridlines (never null). The default value is Color.lightGray. å public void setRangeGridlinePaint(Paint paint); Sets the Paint used for the range gridlines and sends a PlotChangeEvent to all registered listeners. å public Stroke getRangeGridlineStroke(); Returns the stroke used to draw the range axis gridlines (never null). The default stroke is a thin dashed line. å public void setRangeGridlineStroke(Stroke stroke); Sets the Stroke used for the range gridlines and sends a PlotChangeEvent to all registered listeners. If stroke is null, this method throws an IllegalArgumentException. 33.18.7 Zooming To support the zooming operations that can be invoked from the ChartPanel class, this plot implements the Zoomable interface: å public boolean isDomainZoomable(); Always returns true, because the plot supports zooming along the domain axis. å public boolean isRangeZoomable(); Always returns true, because the plot supports zooming along the range axis. To find the current orientation of the plot: å public PlotOrientation getOrientation(); Returns the plot orientation, which is always VERTICAL for this class. To invoke zooming on the domain axis: å public void zoomDomainAxes(double factor, PlotRenderingInfo info, Point2D source); Zooms the domain axis in or out by the specified factor. å public void zoomDomainAxes(double lowerPercent, double upperPercent, PlotRenderingInfo info, Point2D source); Zooms the domain axis to the specified lower and upper bounds. To invoke zooming on the range axis: å public void zoomRangeAxes(double factor, PlotRenderingInfo info, Point2D source); Zooms the range axis in or out by the specified factor. å public void zoomRangeAxes(double lowerPercent, double upperPercent, PlotRenderingInfo info, Point2D source); Zooms the range axis to the specified lower and upper bounds. CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT 33.18.8 328 Other Methods A string describing the plot type is returned by the following method: å public String getPlotType(); Returns a string describing the plot type. The string is localised, and intended for display in a user interface (such as a plot property editor). The following method is called by the JFreeChart class during chart drawing: å public void draw(Graphics2D g2, Rectangle2D plotArea, Point2D anchor, PlotState parentState, PlotRenderingInfo state); Draws the plot within the specified area. In typical situations, you won’t normally call this method directly. å public void render(Graphics2D g2, Rectangle2D dataArea, PlotRenderingInfo info, CrosshairState crosshairState); Called by the draw() method, this method renders the data values. 33.18.9 Equals, Cloning and Serialization This class overrides the equals() method: å public boolean equals(Object obj); Tests this plot for equality with an arbitrary object. Returns true if and only if: • obj is not null; • obj is an instance of FastScatterPlot; • obj has the same attributes as this plot (including the data values). Instances of this class are cloneable and serializable. 33.18.10 Notes Some points to note: • this plot does not support multiple datasets or axes; • you cannot specify the orientation of the plot (it is always PlotOrientation.VERTICAL); • this plot has no support for tooltips; • a demo (FastScatterPlotDemo.java) is included in the JFreeChart demo collection. 33.19 GreyPalette 33.19.1 Overview A grey palette (extends ColorPalette) used by the ContourPlot class. This class is deprecated as of version 1.0.4. 33.20 IntervalMarker 33.20.1 Overview An IntervalMarker is used to highlight a (fixed) range of values against the domain or range axis for a CategoryPlot or an XYPlot. This class extends the Marker class. CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT 33.20.2 329 Usage You can add a marker to an XYPlot using the addDomainMarker() or addRangeMarker() methods. Similarly, you can add a range marker to a CategoryPlot using the addRangeMarker() method. There is a demo application (DifferenceChartDemo2.java) included in the JFreeChart demo collection that illustrates the use of this class. 33.20.3 Constructors This class defines several constructors: å public IntervalMarker(double start, double end); Creates a new instance for the specified range (in data space). å public IntervalMarker(double start, double end, Paint paint); [1.0.9] Equivalent to IntervalMarker(start, end, paint, new BasicStroke(0.5f), null, null, 0.8f)— see the next constructor. å public IntervalMarker(double start, double end, Paint paint, Stroke stroke, Paint outlinePaint, Stroke outlineStroke, float alpha); Creates a new instance for the specified range (in data space) and with the given attributes. 33.20.4 General Attributes In addition to the methods inherited from Marker, this class defines: å public double getStartValue(); Returns the lower bound of the interval. å public void setStartValue(double value); [1.0.3] Sets the lower bound of the interval to be highlighted, and sends a MarkerChangeEvent to all registered listeners. å public double getEndValue(); Returns the upper value in the interval. å public void setEndValue(double value); [1.0.3] Sets the upper bound of the interval to be highlighted, and sends a MarkerChangeEvent to all registered listeners. 33.20.5 Gradient Paint Support The marker supports the use of GradientPaint via a transformer that can dynamically update the coordinates of the gradient to match the interval area: å public GradientPaintTransformer getGradientPaintTransformer(); Returns the transformer applied to any GradientPaint instances used by the marker. This method can return null, in which case any GradientPaint instance is used without transforma- tion. å public void setGradientPaintTransformer(GradientPaintTransformer transformer); Sets the transformer that will be applied to any GradientPaint instances used by the marker and sends a MarkerChangeEvent to all registered listeners. If transformer is null, any GradientPaint instance will be used without transformation. 33.20.6 Equals, Cloning and Serialization This class overrides the equals() method: å public boolean equals(Object obj); Tests this instance for equality with an arbitrary object (which may be null). Instances of this class are Cloneable and Serializable. CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT 33.20.7 330 Notes Markers don’t have any code to draw themselves, this function is delegated to the renderer classes. See Also ValueMarker. 33.21 Marker 33.21.1 Overview The base class for markers that can be added to a CategoryPlot or an XYPlot. Markers are used to highlight particular values or value ranges against either the domain or range axes. Markers can be displayed with or without labels. This abstract base class has three subclasses, as listed in Table 33.4. Class: Description: CategoryMarker ValueMarker IntervalMarker A marker that highlights a category on the domain axis of a CategoryPlot. A marker that highlights a single value on a numerical or date axis. A marker that highlights a range of values. Table 33.4: Subclasses of Marker 33.21.2 Usage Demo applications (MarkerDemo1 and MarkerDemo2) illustrating the use of markers are included in the JFreeChart demo collection. 33.21.3 Constructors Several constructors are provided for the use of subclasses—they are protected, so you cannot call them directly: å protected Marker(); Creates a new marker with default attributes. This is equivalent to new Marker(Color.gray). å protected Marker(Paint paint); Creates a new marker with the specified paint (null is not permitted). The other fields take the following default values: • stroke: new BasicStroke(0.5f); • outlinePaint: Color.gray; • outlineStroke: new BasicStroke(0.5f); • alpha: 0.80f; å protected Marker(Paint paint, Stroke stroke, Paint outlinePaint, Stroke outlineStroke, float alpha); Creates a new marker with the specified attributes. The paint and stroke arguments cannot be null. The alpha argument should be in the range 0.0 to 1.0. The label attributes, which cannot be specified in these constructors, take the following default values: CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT Attribute: Default Value: labelFont labelPaint labelAnchor labelOffset labelOffsetType labelTextAnchor new Font("SansSerif", Font.PLAIN, 9); Color.black; RectangleAnchor.TOP LEFT; new RectangleInsets(3.0, 3.0, 3.0, 3.0); LengthAdjustmentType.CONTRACT; TextAnchor.CENTER; 331 Table 33.5: Attribute Default Values 33.21.4 General Attributes This section describes the general attributes that control the appearance of markers. Label attributes are covered in the next section. To control the paint used to draw the marker: å public Paint getPaint(); Returns the paint used to draw the marker (never null). The default value is Color.gray. å public void setPaint(Paint paint); Sets the paint used to draw the marker (null is not permitted) and sends a MarkerChangeEvent to all registered listeners. To control the stroke used to draw markers that are rendered as lines: å public Stroke getStroke(); Returns the stroke used to draw the marker, if it is drawn as a line (never null). The default value is BasicStroke(0.5f). If the marker is a rectangular region, the outline is drawn using getOutlineStroke(), so this attribute is not used in that case. å public void setStroke(Stroke stroke); Sets the stroke used to draw the marker when it is drawn as a line (null is not permitted) and sends a MarkerChangeEvent to all registered listeners. To control the paint used to draw marker outlines: å public Paint getOutlinePaint(); Returns the paint used to draw the marker outline (possibly null). The default value is Color.gray. This field is not used when the marker is drawn as a line. å public void setOutlinePaint(Paint paint); Sets the paint used to draw the marker outline when it is drawn as a shape (typically a rectangle), rather than a line (set this to null if you do not want the outline drawn). After changing the value, this method sends a MarkerChangeEvent to all registered listeners. To control the stroke used to draw marker outlines: å public Stroke getOutlineStroke(); Returns the stroke used to draw the marker outline (possibly null). The default value is BasicStroke(0.5f). This is not used when the marker is drawn as a line. å public void setOutlineStroke(Stroke stroke); Sets the stroke used to draw the marker outline when it is drawn as a shape (typically a rectangle), rather than a line (set this to null if you do not want the outline drawn). After changing the value, this method sends a MarkerChangeEvent to all registered listeners. To control the alpha transparency of the marker: å public float getAlpha(); Returns the alpha transparency for the marker (a value in the range 0.0f to 1.0f). 0.0f is completely transparent and 1.0f is completely opaque. å public void setAlpha(float alpha); Sets the alpha transparency that should be used to draw the marker. This is a value in the range 0.0f (completely transparent) to 1.0f (completely opaque). After changing the value, this method sends a MarkerChangeEvent to all registered listeners. CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT 33.21.5 332 Label Attributes Labels can be drawn on or near markers. This section describes the attributes that control the appearance and position of the label. These methods control the label text, font and color: å public String getLabel(); Returns the label text (which may be null). If the label string is null (the default), the marker will be drawn without a label. å public void setLabel(String label); Sets the label text (null is permitted) and sends a MarkerChangeEvent to all registered listeners. å public Font getLabelFont(); Returns the font used to display the label (never null). The default value is Font("SansSerif", Font.PLAIN, 9). å public void setLabelFont(Font font); Sets the font used to display the label (null is not permitted) and sends a MarkerChangeEvent to all registered listeners. å public Paint getLabelPaint(); Returns the paint used to display the label text (never null). The default value is Color.black. å public void setLabelPaint(Paint paint); Sets the paint used to display the label text (null is not permitted) and sends a MarkerChangeEvent to all registered listeners. The remaining methods control the position of the label relative to the marker bounds when it is drawn on the plot: å public RectangleAnchor getLabelAnchor(); Returns the attribute that defines the anchor point, relative to the marker bounds, that the label will be aligned to. The actual point is offset slightly from the marker bounds—see the getLabelOffset() method. å public void setLabelAnchor(RectangleAnchor anchor); Sets the point on the marker bounds that is used for alignment of the label, then sends a MarkerChangeEvent to all registered listeners. This anchor (after being adjusted by the label offsets) determines a fixed point on the chart that the marker label can be aligned to. Figure 33.9 illustrates how the marker label anchor position is calculated relative to the marker’s bounds. One of the nine potential anchors is selected via the setLabelAnchor() method, and the margin between the marker’s bounds and the potential anchor points is determined by the getLabelOffset() and getLabelOffsetType() methods. Figure 33.9: Marker insets and the label anchor CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT 333 å public RectangleInsets getLabelOffset(); Returns the label offsets (never null). The default value is RectangleInsets(3.0, 3.0, 3.0, 3.0) (that is, the anchor points lie on a rectangle three Java2D units inside (or outside) the marker’s bounding rectangle). å public void setLabelOffset(RectangleInsets offset); Sets the offset between the marker’s bounds and the label anchor points (null is not permitted), then sends a MarkerChangeEvent to all registered listeners. å public LengthAdjustmentType getLabelOffsetType(); Returns the label offset type, typically either CONTRACT (the default) or EXPAND. This controls how the insets returned by getLabelOffset() are applied to calculate the label anchor position— figure 33.9 illustrates the CONTRACT option, while figure 33.10 illustrates the EXPAND option. å public void setLabelOffsetType(LengthAdjustmentType adj); Sets the label offset type, which should be either CONTRACT or EXPAND (null is not permitted), then sends a MarkerChangeEvent to all registered listeners. Figure 33.10 illustrates how the label anchor points can be positioned outside the marker’s bounds (by setting the label offset type to EXPAND). Figure 33.10: Marker insets and the label anchor To set the point on the label that is aligned to the label anchor:2 å public TextAnchor getLabelTextAnchor(); Returns the point on the label bounds that is aligned to the label anchor point (the default is TextAnchor.CENTER). This method never returns null. å public void setLabelTextAnchor(TextAnchor anchor); Sets the point on the label that is aligned to the fixed point on the chart determined by the getLabelAnchor() method, then sends a MarkerChangeEvent to all registered listeners. Note that if the marker denotes a single value, the bounding rectangle may have zero width. 33.21.6 Equals, Cloning and Serialization This class overrides the equals() method: å public boolean equals(Object obj); Tests this marker for equality with an arbitrary object. This method returns true if and only if: • obj is not null; 2 Try running DrawStringDemo.java, in the JCommon distribution, to get an understanding of how the TextAnchor setting controls basic string alignment. CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT 334 • obj is an instance of Marker; • obj has the same attribute values as this marker. Instances of this class are cloneable and serializable (in order that charts that have markers can be cloneable and serializable). 33.21.7 Notes Some points to note: • markers are drawn on the chart by the plot’s main renderer—see the default drawing methods defined in AbstractCategoryItemRenderer and AbstractXYItemRenderer; • prior to version 1.0.3, there was no change notification mechanism for markers, so charts were not updated automatically when marker attributes changed (one way to trigger a repaint of the chart, at least for charts displayed in a ChartPanel, was to call chart.setNotify(true)). From version 1.0.3 onwards, there is a change notification mechanism, so the repaint will occur automatically. 33.22 MeterInterval 33.22.1 Overview Represents a range of values on a MeterPlot that should be highlighted for some reason. For example, on a temperature dial you might show intervals for “normal”, “high” and “extreme”. 33.22.2 Constructors To create a new interval: å public MeterInterval(String label, Range range); Creates a new interval with the specified label and range. The default outline paint for the interval is Color.yellow, the default outline stroke is BasicStroke(2.0f), and the default background paint is null. å public MeterInterval(String label, Range range, Paint outlinePaint, Stroke outlineStroke, Paint backgroundPaint); Creates a new interval with the specified label and range. The label is typically displayed in the plot’s legend (if visible). The range is highlighted by filling the background with backgroundPaint. If label or range is null, this method throws an IllegalArgumentException. All other arguments can be null. 33.22.3 Methods To get the label for the interval: å public String getLabel(); The label for the interval. This will normally be displayed in the plot’s legend. å public Range getRange(); Returns the value range for the interval. å public Paint getBackgroundPaint(); Returns the paint used to fill the background for the interval. å public Paint getOutlinePaint(); Returns the paint used to draw the outline for the interval. å public Stroke getOutlineStroke(); Returns the stroke used to draw the outline for the interval. CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT 33.22.4 335 Equals, Cloning and Serialization To test for equality with an arbitrary object: å public boolean equals(Object obj); Tests the interval for equality with an arbitrary object. Instances of this class are immutable, so it is not necessary to clone them. Serialization is supported. 33.22.5 Notes Some points to note: • this class is immutable—you cannot change the interval’s range or other attributes. 33.23 MeterPlot 33.23.1 Overview A plot that displays a single value in a dial presentation. The current value is represented by a needle in the dial, and is also displayed in the center of the dial in text format. Figure 33.11: A meter chart Specific intervals in the dial can be highlighted by adding MeterInterval instances to the plot. A new class (DialPlot) is now included in the experimental directory of the JFreeChart distribution— it is intended that DialPlot will eventually replace MeterPlot. 33.23.2 Constructors To create a new MeterPlot: å public MeterPlot(); Creates a new plot with a default range of 0 to 100 and no dataset. å public MeterPlot(ValueDataset dataset); Creates a dial with default settings, using the supplied dataset. The plot can be customised after it is created, if the default values are not suitable. CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT 33.23.3 336 The Dataset A MeterPlot displays a single value, but still uses a dataset to represent the value rather than relying on a “value” field in the plot. This maintains the separation between the data and the “view”, and consistency with other plot types in JFreeChart. To access the current dataset: å public ValueDataset getDataset(); Returns the current dataset (possibly null). å public void setDataset(ValueDataset dataset); Sets the dataset for the plot (null permitted) and sends a PlotChangeEvent to all registered listeners. If the dataset is set to null, no value will be displayed on the dial. To update the displayed value in the chart, call the setValue() method in the dataset. This will trigger a DatasetChangeEvent which will be picked up by the chart (and cause the chart to be repainted if it is displayed in a ChartPanel). 33.23.4 The Current Value Display A needle is used to indicate the current value on the dial. To change the color of the needle: å public Paint getNeedlePaint(); Returns the paint used to display the needle on the dial. The default is Color.green. å public void setNeedlePaint(Paint paint); Sets the color of the needle on the dial and sends a PlotChangeEvent to all registered listeners. An IllegalArgumentException is thrown if paint is null. The current value is also displayed (near the center of the dial) in text format, with the units appended. To change the font used to display the current value: å public Font getValueFont(); Returns the font used to display the current value in the middle of the plot (never null). å public void setValueFont(Font font); Sets the font used to display the current value and sends a PlotChangeEvent to all registered listeners. An IllegalArgumentException is thrown if font is null. To change the color used to display the current value: å public Paint getValuePaint(); Returns the paint used to display the current value (never null). å public void setValuePaint(Paint paint); Sets the paint used to display the current value and sends a PlotChangeEvent to all registered listeners. An IllegalArgumentException is thrown if paint is null. To change the “units” for the value: å public String getUnits(); Returns a string describing the units for the dial (possibly null). This is displayed after the value in the middle of the dial. å public void setUnits(String units); Sets the unit description for the plot and sends a PlotChangeEvent to all registered listeners. If this is set to null, then no units are displayed with the meter value. 33.23.5 The Dial Range, Shape and Background The range of values that can be displayed on the dial is configurable using the following methods: å public Range getRange(); Returns the range of data values on the dial (never null). The default is 0 to 100. CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT 337 å public void setRange(Range range); Sets the range of data values on the dial and sends a PlotChangeEvent to all registered listeners. An IllegalArgumentException is thrown if range is null. If the current value in the plot’s dataset falls outside this range, no needle will be displayed. To control the shape of the dial: å public DialShape getDialShape(); Returns the dial shape (never null). The default is DialShape.CIRCLE. å public void setDialShape(DialShape shape); Sets the dial shape and sends a PlotChangeEvent to all registered listeners. An IllegalArgumentException is thrown if shape is null. Refer to the description of the DialShape class for a sample of the available shapes. The angle spanned by the dial is configurable with the following methods: å public int getMeterAngle(); Returns the angle (in degrees) of the full range of the dial. The default value is 270 degrees. å public void setMeterAngle(int angle); Sets the angle (in degrees) of the full range of the dial. This is required to be in the range 1 to 360 degrees. To change the background color of the dial: å public Paint getDialBackgroundPaint(); Returns the paint used for the dial background (never null). The default is Color.black. å public void setDialBackgroundPaint(Paint paint); Sets the color of the dial background. If you set this to null, no background is painted. To control the outline paint for the dial: å public Paint getDialOutlinePaint(); Returns the paint used to draw the dial outline (possibly null). å public void setDialOutlinePaint(Paint paint); Sets the paint used to draw the dial outline and sends a PlotChangeEvent to all registered listeners. The dial can be drawn with or without a border: å public boolean getDrawBorder(); Returns the flag that controls whether or not a border is drawn around the dial. å public void setDrawBorder(boolean draw); Sets the flag that controls whether or not a border is drawn around the dial and sends a PlotChangeEvent to all registered listeners. 33.23.6 Tick Labels Labels are drawn for the first and last ticks only (this is a limitation that needs to be addressed): å public boolean getTickLabelsVisible(); Returns true if the tick labels should be displayed, and false otherwise. å public void setTickLabelsVisible(boolean visible); Sets the flag that controls whether or not tick labels are visible, and sends a PlotChangeEvent to all registered listeners. The font for the labels is controlled with the following methods: å public Font getTickLabelFont(); Returns the font used to display the tick labels. å public void setTickLabelFont(Font font); Sets the font used to display the tick labels and sends a PlotChangeEvent to all registered listeners. CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT 338 The paint for the labels is controlled with the following methods: å public Paint getTickLabelPaint(); Returns the paint used to display the tick labels. å public void setTickLabelPaint(Paint paint); Sets the paint used to display the tick labels and sends a PlotChangeEvent to all registered listeners. The formatter for the labels is controlled with the following methods: å public NumberFormat getTickLabelFormat(); Returns the formatter used to convert the tick values to strings for display. å public void setTickLabelFormat(NumberFormat format); Sets the formatter used to convert the tick values to strings for display and sends a PlotChangeEvent to all registered listeners. 33.23.7 Intervals It is possible to highlight certain data ranges by adding one or more MeterInterval instances to the plot. å public List getIntervals(); Returns an unmodifiable list of the intervals for the plot. The list may be empty. å public void addInterval(MeterInterval interval); Adds an interval to the plot. å public void clearIntervals(); Removes all intervals from the plot and sends a PlotChangeEvent to all registered listeners. The sample chart in figure 33.11 contains three intervals labelled “Normal”, “Warning” and “Critical”. 33.23.8 Legend Items This plot utilises the legend to display descriptions for the MeterInterval instances (if any) that have been added to the plot. The following method returns the required items: å public LegendItemCollection getLegendItems(); Returns a collection of legend items for the plot. For this plot, there is one item for each MeterInterval that has been added to the plot. You can override this method to customise the legend display. 33.23.9 Drawing Methods This class has several drawing methods that are used internally. In some cases, you can override these methods to change the appearance of the plot: å public void draw(Graphics2D g2, Rectangle2D plotArea, Point2D anchor, PlotState parentState, PlotRenderingInfo state); Draws the plot within the specified area. This method is called by the JFreeChart class. å protected void drawArc(Graphics2D g2, Rectangle2D area, double minValue, double maxValue, Paint paint, Stroke stroke); Draws an arc between the specified values. å protected void fillArc(Graphics2D g2, Rectangle2D area, double minValue, double maxValue, Paint paint, boolean dial); Fills the background area between the specified values. å protected void drawArcForInterval(Graphics2D g2, Rectangle2D meterArea, MeterInterval interval); Draws an interval arc. CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT 339 å protected void drawTick(Graphics2D g2, Rectangle2D meterArea, double value); Draws a tick, with no label, for the given value. å protected void drawTick(Graphics2D g2, Rectangle2D meterArea, double value, boolean label); Draws a tick, with or without a corresponding label, for the given value. å protected void drawValueLabel(Graphics2D g2, Rectangle2D area); Draws the text in the middle of the dial that displays the current value. 33.23.10 Other Methods To obtain a short description of the plot type: å public String getPlotType(); Returns a short localised string representing the plot type. To convert a data value to an angle: å public double valueToAngle(double value); Returns the angle in degrees corresponding to the given data value. The zooming method is overridden to do nothing, zooming is not supported by this plot: å public void zoom(double percent); This method is overridden to do nothing. 33.23.11 Equals, Cloning and Serialization To test the plot for equality with an arbitrary object: å public boolean equals(Object obj); Tests the plot for equality with an arbitrary object. The plot is equal to obj if and only if: • obj is not null; • obj is an instance of MeterPlot; • this plot and obj have the same field values (not including the dataset, which is ignored for the purposes of equality testing). This class is both cloneable and serializable. 33.23.12 Notes Some points to note: • the original version of this class was contributed by Hari; • the MeterChartDemo1 and MeterChartDemo2 classes in the JFreeChart demo collection provide a working example of this class. • the DialPlot class provides a newer and more flexible alternative to this class. See Also ValueDataset, DialShape, MeterInterval. 33.24 MultiplePiePlot 33.24.1 Overview A specialised plot that displays data from a CategoryDataset in the form of multiple pie charts. Figure 33.12 shows an example. CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT 340 Figure 33.12: A multiple pie chart 33.24.2 Constructors There are two constructors for this class: å public MultiplePiePlot(); Creates a new plot with a null dataset. å public MultiplePiePlot(CategoryDataset dataset); Creates a new plot with the specified dataset (which can be null). Data for the individual pie charts is extracted from the dataset by column (you can change this using the setDataExtractOrder() method). 33.24.3 Methods This plot uses a single chart instance to draw the multiple pie charts: å public JFreeChart getPieChart(); Returns the chart that is used to render each pie chart in the plot. Any changes you make to this chart will be reflected in the appearance of all the pie charts. å public void setPieChart(JFreeChart pieChart); Sets the chart that is used to render each of the pie charts in the plot. The getPlot() method for this chart MUST return a PiePlot instance (this includes PiePlot3D and RingPlot, since these are subclasses of PiePlot). It is advisable to use a chart that does not include a legend. To access the current dataset for the plot: å public CategoryDataset getDataset(); Returns the current dataset, which may be null. å public void setDataset(CategoryDataset dataset); Sets the dataset for the plot and sends a PlotChangeEvent to all registered listeners. The plot will register itself with the new dataset so that it receives notification of any changes to the dataset (and also will unregister from the old dataset). An important factor determining the appearance of this plot is the order in which the data is extracted for the pie charts: å public TableOrder getDataExtractOrder(); Returns a key that determines how data is extracted (by column or by row) to form the individual pie charts. The default is TableOrder.BY COLUMN. CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT å public void setDataExtractOrder(TableOrder order); Sets the order of data extraction to one of TableOrder.BY COLUMN or TableOrder.BY ROW. In the first case, the number of pie charts displayed will be equal to the number of columns in the dataset, and in the second case it will be equal to the number of rows in the dataset. A lower limit can be specified and will be used to aggregate small data values: å public double getLimit(); Returns the smallest value that will be displayed in it’s own pie section (the default is 0.0). All sections with values less than this will be aggregated into a single section. å public void setLimit(double limit); Sets the smallest value that will be displayed in it’s own pie section and sends a PlotChangeEvent to all registered listeners. The key used for aggregated data items can be accessed with the following methods: å public Comparable getAggregatedItemsKey(); [1.0.2] Returns the key used for aggregated items (never null). The default is Other—this can be changed by calling the setAggregatedItemsKey() method. å public void setAggregatedItemsKey(Comparable key); [1.0.2] Sets the key that is used for aggregated items and sends a PlotChangeEvent to all registered listeners. This method throws an IllegalArgumentException if key is null. To determine the paint used to display the pie section for aggregated items: å public Paint getAggregatedItemsPaint(); [1.0.2] Returns the paint used to display the pie section for aggregated items. The default value is Color.lightGray and this field cannot be set to null. å public void setAggregatedItemsPaint(Paint paint); [1.0.2] Sets the paint used to display the pie section for aggregated items and sends a PlotChangeEvent to all registered listeners. This method throws an IllegalArgumentException if paint is null. 33.24.4 Miscellaneous Methods The plot type is described by the following method: å public String getPlotType(); Returns the string Multiple Pie Plot. The legend items are created by the following method (which you are free to override): å public LegendItemCollection getLegendItems(); Returns the legend items for the plot. Depending on the data extract order, this will be the column keys or the row keys from the dataset. The following method is called by the JFreeChart class during chart drawing: å public void draw(Graphics2D g2, Rectangle2D plotArea, Point2D anchor, PlotState parentState, PlotRenderingInfo state); Draws the plot within the specified area. In typical situations, you won’t normally call this method directly. 33.24.5 Equals, Cloning and Serialization The equals method is overridden: å public boolean equals(Object obj); Tests this plot for equality with an arbitrary object. This method returns true if and only if: • obj is not null; • obj is an instance of MultiplePiePlot; • both plots have the same attributes (excluding the dataset and the registered listeners). Instances of this class are cloneable and serializable. 341 CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT 33.24.6 342 Notes Some points to note: • several demo applications (MultiplePieChartDemo1-4.java) are included in the JFreeChart demo distribution. • the createMultiplePieChart() and createMultiplePieChart3D() methods in the ChartFactory class create charts using this plot. 33.25 PieLabelDistributor 33.25.1 Overview The PiePlot class uses this class to arrange section labels so that they do not overlap one another. This is largely an implementation detail—you won’t need to use this class directly. 33.26 PieLabelRecord 33.26.1 Overview A temporary holder of information about the label for one section of a PiePlot. Instances of this class are used by the PieLabelDistributor class. Typically, you won’t use this class directly. 33.27 PiePlot 33.27.1 Overview The PiePlot class draws pie charts using data obtained through the PieDataset interface. A sample chart is shown in figure 33.13. Pie Chart Demo 1 Six One Five Four Two Three One Two Three Four Five Six Figure 33.13: A simple pie chart (see PieChartDemo1.java) Refer to chapter 5 for a general overview of the pie chart support in JFreeChart. The PiePlot class extends Plot. A subclass (PiePlot3D) that draws plots with a 3D effect is also available. CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT 33.27.2 343 Constructors To construct a pie plot: å public PiePlot(PieDataset dataset); Creates a pie plot for the given dataset (null is permitted). All plot attributes are initialised with default values—these can be changed at any time. This class also has a default constructor: å public PiePlot(); Creates a new plot with no dataset. 33.27.3 Attributes The attributes maintained by the PiePlot class, which are in addition to those inherited from the Plot class, are listed in table 33.6. Attribute: Description: interiorGap The amount of space to leave blank around the outside of the pie, expressed as a percentage of the chart height and width. Extra space is added for the labels. A flag that controls whether the pie chart is constrained to be circular, or allowed to take on an elliptical shape to fit the available space. The angle of the first pie section, expressed in degrees (0 degrees is three o’clock, 90 degrees is twelve o’clock, 180 degrees is nine o’clock and 270 degrees is six o’clock). Pie sections can be ordered in a clockwise (Rotation.CLOCKWISE) or anticlockwise (Rotation.ANTI CLOCKWISE) direction. The paint used for all sections (usually null). Deprecated as of 1.0.6. The paint used for each section, unless overridden by sectionPaint. The default paint, used when no other setting is specified. A flag that controls whether or not section outlines are drawn. The outline paint used for all sections (usually null). Deprecated as of 1.0.6. The outline paint used for each section. The default outline paint, used when no other setting is specified. The outline stroke used for all sections (usually null).Deprecated as of 1.0.6. The outline stroke used for each section. The default outline stroke, used when no other setting is specified. The shadow paint. The x-offset for the shadow effect. The y-offset for the shadow effect. The amount (percentage) to “explode” each pie section. The section label generator, an instance of PieSectionLabelGenerator. The font for the section labels. The colour for the section labels. The background colour for the section labels. The maximum label width as a percentage of the plot width. The gap for the section labels. The label link margin. The Paint used for the lines that connect the pie sections with their corresponding labels. The Stroke used for the lines that connect the pie sections to their corresponding labels. A plug-in tool tip generator. A plug-in URL generator (for image map generation). The index for this plot (only used by the MultiplePiePlot class). circular startAngle direction sectionPaint sectionPaintList baseSectionPaint sectionOutlinesVisible sectionOutlinePaint sectionOutlinePaintList baseSectionOutlinePaint sectionOutlineStroke sectionOutlineStrokeList baseSectionOutlineStroke shadowPaint shadowXOffset shadowYOffset explodePercentages labelGenerator labelFont labelPaint labelBackgroundPaint maximumLabelWidth labelGap labelLinkMargin labelLinkPaint labelLinkStroke toolTipGenerator urlGenerator pieIndex Table 33.6: Attributes for the PiePlot class The following default values are used where necessary: CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT Name: DEFAULT DEFAULT DEFAULT DEFAULT DEFAULT DEFAULT Value: INTERIOR GAP START ANGLE LABEL FONT LABEL PAINT LABEL BACKGROUND PAINT LABEL GAP 0.1 (10 percent) 90.0 new Font("SansSerif", Font.PLAIN, 10); Color.black; new Color(255, 255, 192); 0.10 (10 percent) 344 CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT 33.27.4 345 The Plot Border The PiePlot draws a border around the outside of the plot, with the chart title and legend appearing outside this border. This border is common to all plot types, but is especially noticeable in pie charts (and other charts that don’t have axes). You can change the appearance of this border (or hide it completely) using methods inherited from the Plot class—refer to section 33.30.6 for details. 33.27.5 The Dataset To access the dataset being used by the plot: å public PieDataset getDataset(); Returns the current dataset (possibly null). å public void setDataset(PieDataset dataset); Replaces the dataset being used by the plot (this triggers a DatasetChangeEvent). 33.27.6 General Methods To control whether the pie chart is circular or elliptical: å public boolean isCircular(); Returns the flag that controls whether or not the pie chart is constrained to be circular in appearance. The default value is true. å public void setCircular(boolean flag); Equivalent to setCircular(flag, true)—see next method. å public void setCircular(boolean circular, boolean notify); Sets a flag that controls whether the pie chart is circular or elliptical in shape, and sends a PlotChangeEvent to all registered listeners. To control the position of the first section in the chart: å public double getStartAngle(); Returns the angle (in degrees) at which the first pie section starts. Zero is at 3 o’clock, and as the angle increases it proceeds anticlockwise around the chart (so that 90 degrees, the current default, is at 12 o’clock). This is the same encoding used by Java’s Arc2D class. å public void setStartAngle(double angle); Sets the angle (in degrees) at which the first section starts, and sends a PlotChangeEvent to all registered listeners. To control the direction (clockwise or anticlockwise) of the sections in the pie chart: å public Rotation getDirection(); Returns the direction in which the pie sections are drawn. The default value is Rotation.CLOCKWISE. å public void setDirection(Rotation direction); Sets the direction of the sections in the pie chart. Use one of the constants Rotation.CLOCKWISE (the default) and Rotation.ANTICLOCKWISE. To control the amount of space around the pie chart: å public double getInteriorGap(); Returns the gap around the interior of the pie plot (the region where the labels are drawn) as a percentage of the plot width and height. The default value is 0.08. å public void setInteriorGapPercent(double percent); Sets the amount of space to leave inside the plot area and sends a PlotChangeEvent to all registered listeners. CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT 33.27.7 346 Section Paint The paint used to fill each section in the pie chart is, by default, auto-populated from the plot’s DrawingSupplier. However, you can easily customise the colours using the methods described below. To control the paint associated with a section: å public Paint getSectionPaint(Comparable key); [1.0.3] Returns the paint associated with the specified section, which may be null. å public void setSectionPaint(Comparable key, Paint paint); [1.0.3] Sets the paint to use for the specified section and sends a PlotChangeEvent to all registered listeners. The base section paint is a default that is used when no other setting is available: å public Paint getBaseSectionPaint(); Returns the base section paint, which is never null. The default value is Color.gray. å public void setBaseSectionPaint(Paint paint); Sets the base section paint (null is not permitted) and sends a PlotChangeEvent to all registered listeners. An override setting is available, but deprecated as of JFreeChart 1.0.6 because it is more or less redundant: å public Paint getSectionPaint(); [Deprecated, 1.0.6] Returns the paint that should be used for ALL sections in the PiePlot. The default value is null. å public void setSectionPaint(Paint paint); [Deprecated, 1.0.6] Sets the paint that applies to ALL sections in the PiePlot and sends a PlotChangeEvent to all registered listeners. The PiePlot drawing code makes use of the following utility methods: å protected Paint lookupSectionPaint(Comparable key); [1.0.3] Returns the paint associated with the given key, or null. å protected Paint lookupSectionPaint(Comparable key, boolean autoPopulate); [1.0.3] Returns the paint associated with the given key. If autoPopulate is true and there is currently no paint defined, a new paint is fetched from the plot’s DrawingSupplier. 33.27.8 Section Outlines The sections in a pie plot can be drawn with or without an outline: å public boolean getSectionOutlinesVisible(); Returns true if section outlines should be drawn for the plot, and false otherwise. The default value is true. å public void setSectionOutlinesVisible(boolean visible); Sets the flag that controls whether or not section outlines are drawn, and sends a PlotChangeEvent to all registered listeners. The paint and stroke attributes used to draw the section outlines are specified via the following methods: å public Paint getSectionOutlinePaint(); [Deprecated, 1.0.6] Returns the override value for the section outline paint. This defaults to null, which means the getSectionOutlinePaint(int) method will be called instead. å public void setSectionOutlinePaint(Paint paint); [Deprecated, 1.0.6] Sets the override value for the section outline paint and sends a PlotChangeEvent to all registered listeners. Most of the time, you should leave this set to null so that the per-series and base-level settings are exposed. CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT å public Paint getSectionOutlinePaint(int section); Returns the outline paint to use for the specified section. If this is null, the plot will use the value returned by getBaseSectionOutlinePaint() instead. å public void setSectionOutlinePaint(int section, Paint paint); Sets the paint used to outline a particular section in the chart and sends a PlotChangeEvent to all registered listeners. å public Paint getBaseSectionOutlinePaint(); Returns the default section outline paint, which is used when no other non-null setting is specified. The default value is Color.gray. å public void setBaseSectionOutlinePaint(Paint paint); Sets the default section outline paint (null is not permitted) and sends a PlotChangeEvent to all registered listeners. Similar methods are defined for the outline stroke: å public Stroke getSectionOutlineStroke(); [Deprecated, 1.0.6] Returns the override value for the section outline stroke. This defaults to null, which means the getSectionOutlineStroke(int) method will be called instead. å public void setSectionOutlineStroke(Stroke stroke); [Deprecated, 1.0.6] Sets the override value for the section outline stroke and sends a PlotChangeEvent to all registered listeners. Most of the time, you should leave this set to null so that the per-series and base-level settings are exposed. å public Stroke getSectionOutlineStroke(int section); Returns the outline stroke to use for the specified section. If this is null, the plot will use the value returned by getBaseSectionOutlineStroke() instead. å public void setSectionOutlineStroke(int section, Stroke stroke); Sets the stroke used to outline a particular section in the chart and sends a PlotChangeEvent to all registered listeners. å public Stroke getBaseSectionOutlineStroke(); Returns the default section outline stroke, which is used when no other non-null setting is specified. The default value is BasicStroke(0.5f). å public void setBaseSectionOutlineStroke(Stroke stroke); Sets the default section outline stroke (null is not permitted) and sends a PlotChangeEvent to all registered listeners. 33.27.9 Shadow Effect The pie plot will draw a “shadow” effect. To control the paint used to draw the shadow: å public Paint getShadowPaint(); Returns the paint used to draw the shadow for each pie section. If this is null, no shadow is drawn. The default value is Color.gray. å public void setShadowPaint(Paint paint); Sets the paint used to draw the “shadow” effect. If you set this to null, no shadow effect will be drawn. The x-offset for the shadow effect is controlled with the following methods: å public double getShadowXOffset(); Returns the x-offset for the shadow effect, in Java2D units. The default value is 4.0f. å public void setShadowXOffset(double offset); Sets the x-offset (in Java2D units) for the shadow effect, and sends a PlotChangeEvent to all registered listeners. The y-offset for the shadow effect is controlled by these methods: å public double getShadowYOffset(); Returns the y-offset for the shadow effect, in Java2D units. The default value is 4.0f. å public void setShadowYOffset(double offset); Sets the y-offset (in Java2D units) for the shadow effect, and sends a PlotChangeEvent to all registered listeners. 347 CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT 33.27.10 348 Exploded Sections It is possible to “explode” sections of the pie chart. å public double getExplodePercent(Comparable key); Returns the amount by which a specific section in the pie plot is offset, as a percentage of the radius of the pie. å public void setExplodePercent(Comparable key, double percent); Sets the amount by which a specific section of the pie plot is offset, expressed as a percentage of the radius of the pie, then sends a PlotChangeEvent to all registered listeners. The following utility method is used internally: å public double getMaximumExplodePercent(); Returns the maximum offset for the pie plot. The PieChartDemo2 application (included in the JFreeChart demo collection) provides a demo. 33.27.11 Section Labels Section labels are generated by a user-definable generator object: å public PieSectionLabelGenerator getLabelGenerator(); Returns the section label generator for the plot (possibly null). The default value is an instance of StandardPieSectionLabelGenerator. å public void setLabelGenerator(PieSectionLabelGenerator generator); Sets the label generator for the plot and sends a PlotChangeEvent to all registered listeners. If you set this to null, no section labels will be displayed on the plot. For example, to display percentage values for the pie sections: PiePlot plot = (PiePlot) chart.getPlot(); PieSectionLabelGenerator generator = new StandardPieSectionLabelGenerator( "{0} = {2}", new DecimalFormat("0"), new DecimalFormat("0.00%")); plot.setLabelGenerator(generator); To control the font used to display the section labels: å public Font getLabelFont(); Returns the font (never null) used to display the section labels. The default value is Font("SansSerif", Font.PLAIN, 10). å public void setLabelFont(Font font); Sets the font used to display the section labels, and sends a PlotChangeEvent to all registered listeners. If font is null, this method throws an IllegalArgumentException. To control the colour of the section labels: å public Paint getLabelPaint(); Returns the colour used to display the section labels (never null). å public void setLabelPaint(Paint paint); Sets the colour used to display the section labels and sends a PlotChangeEvent to all registered listeners. If paint is null, this method throws an IllegalArgumentException. To control the background colour of the section labels: å public Paint getLabelBackgroundPaint(); Returns the colour used to fill the section label boxes—if this is null, the boxes are transparent (the plot background colour will show through). å public void setLabelBackgroundPaint(Paint paint); Sets the colour used to fill the section label boxes and sends a PlotChangeEvent to all registered listeners. If you set this to null, the label boxes will be transparent (the plot background colour will show through). To control the outline colour of the section label boxes: CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT labelFont labelOutlineStroke 349 labelPaint Section Label labelShadowPaint labelOutlinePaint labelBackgroundPaint Figure 33.14: PieSectionLabels.pdf å public Paint getLabelOutlinePaint(); Returns the colour used to draw the outline around the section labels. If this is null, no outline is drawn. å public void setLabelOutlinePaint(Paint paint); Sets the colour used to draw the outline around the section labels and sends a PlotChangeEvent to all registered listeners. If you set this to null, the label boxes will not have an outline drawn. To control the outline stroke for the section label boxes: å public Stroke getLabelOutlineStroke(); Returns the stroke used to draw the outline around the section labels. If this is null, no outline box is drawn. å public void setLabelOutlineStroke(Stroke stroke); Sets the stroke used to draw outlines around the section labels, and sends a PlotChangeEvent to all registered listeners. If stroke is null, no outlines will be draw. To control the shadow paint for the section labels: å public Paint getLabelShadowPaint(); Returns the paint used to draw the shadows beneath the section label boxes. If this is null, no shadow is drawn. The default value is DEFAULT LABEL SHADOW PAINT (Color(151, 151, 151, 128)). å public void setLabelShadowPaint(Paint paint); Sets the paint used to draw the shadows beneath the section label boxes, and sends a PlotChangeEvent to all registered listeners. If paint is null, no shadow will be drawn. CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT 350 To control the padding for the section labels: å public RectangleInsets getLabelPadding(); [1.0.7] Returns the padding (never null for the section labels. This is the whitespace around the text and inside the outline. å public void setLabelPadding(RectangleInsets padding); [1.0.7] Sets the padding for the section labels and sends a PlotChangeEvent to all registered listeners. If padding is null, this method throws an IllegalArgumentException. The following methods allow you to plug in an alternative pie label distributor: å public AbstractPieLabelDistributor getLabelDistributor(); [1.0.6] Returns the object (never null) responsible for distributing the section labels to avoid overlap- ping. å public void setLabelDistributor(AbstractPieLabelDistributor distributor); [1.0.6] Sets the object responsible for distributing the section labels and sends a PlotChangeEvent to all registered listeners. If distributor is null, this method throws an IllegalArgumentException. 33.27.12 Simple Label Positioning A new “simple” labelling option has been introduced in JFreeChart 1.0.7, where the labels are drawn roughly in the center of each pie section. No attempt is made to avoid overlapping labels in the case that several small pie sections are displayed alongside each other, so use this option only for cases where that is not a concern. å public boolean getSimpleLabels(); [1.0.7] Returns the flag that controls whether the pie plot shows section labels in the “simple” format. The default value is false. å public void setSimpleLabels(boolean simple); [1.0.7] Sets the flag that controls whether the pie plot shows section labels in the “simple” format, and sends a PlotChangeEvent to all registered listeners. The position of the simple labels is controlled with an offset attribute: å public RectangleInsets getSimpleLabelOffset(); [1.0.7] Returns the insets used to calculate the simple label anchor points relative to the pie plot’s bounding rectangle. The default value is RectangleInsets(UnitType.RELATIVE, 0.18, 0.18, 0.18, 0.18). å public void setSimpleLabelOffset(RectangleInsets offset); [1.0.7] Sets the insets used to calculate the simple label anchor points relative to the pie plot’s bounding rectangle, and sends a PlotChangeEvent to all registered listeners. 33.27.13 Label Links With regular section labels, a linking line is drawn to connect the pie section with its corresponding section label. To control whether or not these linking lines are drawn: å public boolean getLabelLinksVisible(); Returns the flag that controls whether or not the section label linking lines are visible. The default value is true. å public void setLabelLinksVisible(boolean visible); Sets the flag that controls whether or not the section label linking lines are visible, and sends a PlotChangeEvent to all registered listeners. To control the colour of the linking lines: å public Paint getLabelLinkPaint(); Returns the label link paint (never null). The default value is Color.black. CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT 351 å public void setLabelLinkPaint(Paint paint); Sets the Paint used for the lines connecting the pie sections to their corresponding labels and sends a PlotChangeEvent to all registered listeners. If paint is null, this method throws an IllegalArgumentException. To control the line style for the linking lines: å public Stroke getLabelLinkStroke(); Returns the stroke used to draw the label linking lines (never null). The default value is BasicStroke(0.5f). å public void setLabelLinkStroke(Stroke stroke); Sets the Stroke used for the lines connecting the pie sections to their corresponding labels and sends a PlotChangeEvent to all registered listeners. If stroke is null, this method throws an IllegalArgumentException. The overall space allocated to the section labels and their linking lines is configurable using the following methods: å public double getLabelGap(); Returns the gap between the edge of the pie and the label areas at the left and right side of the pie, as a percentage of the overall plot width. The default value is 0.025 (two-and-a-half percent). å public void setLabelGap(double gap); Sets the label gap and sends a PlotChangeEvent to all registered listeners. å public double getMaximumLabelWidth(); Returns the maximum label width as a percentage of the plot width. The default value is 0.14 (fourteen percent). å public void setMaximumLabelWidth(double width); Sets the maximum label width (as a percentage of the plot width) and sends a PlotChangeEvent to all registered listeners. The label linking line has a bend or “elbow” at a point slightly outside of the pie chart. The distance of the point from the edge of the pie chart is expressed as a percentage of the pie radius, and is referred to as the label link margin: å public double getLabelLinkMargin(); Returns the label link margin, expressed as a percentage of the radius of the pie chart. The default value is 0.025 (two-and-a-half percent). å public void setLabelLinkMargin(double margin); Sets the label link margin, and sends a PlotChangeEvent to all registered listeners. 33.27.14 Legend Items The legend for a pie chart is recreated each time the plot is drawn. The JFreeChart class will call the getLegendItems() method to create a collection of items for display in the legend. The methods below provide various configuration options for the generated legend items. The text for each legend item is created by a label generator that can be modified: å public PieSectionLabelGenerator getLegendLabelGenerator(); Returns the generator that derives the labels for the items in the legend (never null). The default value is a default instance of StandardPieSectionLabelGenerator. å public void setLegendLabelGenerator(PieSectionLabelGenerator generator); Sets the generator that derives the labels for the items in the legend and sends a PlotChangeEvent to all registered listeners. If generator is null, this method throws an IllegalArgumentException. The shape displayed for each legend item is controlled via the following methods: å public Shape getLegendItemShape(); Returns the shape displayed with each legend item (never null). The default shape is a circle with radius 4.0 (in Java2D units). CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT 352 å public void setLegendItemShape(Shape shape); Sets the shape to be displayed with each legend item and sends a PlotChangeEvent to all registered listeners. If shape is null, this method throws an IllegalArgumentException. A generator can be used to create the tool tip text for each item in the legend: å public PieSectionLabelGenerator getLegendLabelToolTipGenerator(); Returns the generator that creates the tool tips for each item in the legend. The default value is null. å public void setLegendLabelToolTipGenerator(PieSectionLabelGenerator generator); Sets the generator that creates the tool tips for each item in the legend and sends a PlotChangeEvent to all registered listeners. If generator is null, no tool tips will be displayed for the legend items. Similarly, a generator is used to create URLs for each item in the legend (for use when creating HTML image maps): å public PieURLGenerator getLegendLabelURLGenerator(); [1.0.4] Returns the generator that creates the URL for each item in the legend. These are only used when creating HTML image maps. The default value is null. å public void setLegendLabelURLGenerator(PieURLGenerator generator); [1.0.4] Sets the generator that creates the URL for each item in the legend and sends a PlotChangeEvent to all registered listeners. If generator is null, no URLs will be generated. 33.27.15 Tool Tips If you are displaying your pie chart in a ChartPanel, or writing and you want to customise the tooltip text, you can register your own tool tip generator with the plot: å public PieToolTipGenerator getToolTipGenerator(); Returns the tool tip generator for the plot. The default value is null.3 å public void setToolTipGenerator(PieToolTipGenerator generator); Registers a tool tip generator with the pie plot and sends a PlotChangeEvent to all registered listeners. You can set this to null if you do not require tooltips. 33.27.16 URLs If you create an HTML image map for a pie chart, it is possible to assign a URL to each pie section in the chart: å public PieURLGenerator getURLGenerator(); Returns the current URL generator (possibly null) for the plot. å public void setURLGenerator(PieURLGenerator generator); Sets the URL generator for the plot and sends a PlotChangeEvent to all registered listeners. 33.27.17 Handling for Null and Zero Values A couple of flags in the PiePlot class control how zero and null values in the dataset are treated by the plot: å public boolean getIgnoreNullValues(); The default value is false. å public void setIgnoreNullValues(boolean flag); Sets the flag that controls whether or not null values in the dataset are ignored, then sends a PlotChangeEvent to all registered listeners. å public boolean getIgnoreZeroValues(); The default value is false. å public void setIgnoreZeroValues(boolean flag); Sets the flag that controls whether or not zero values in the dataset are ignored, then sends a PlotChangeEvent to all registered listeners. 3 Although if you use the ChartFactory class to create a pie chart, it may install a tool tip generator for you. CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT 33.27.18 353 Draw Method The following method is called by the JFreeChart class during chart drawing: å public void draw(Graphics2D g2, Rectangle2D area, Point2D anchor, PlotState parentState, PlotRenderingInfo state); Draws the plot within the specified area. In typical situations, you won’t normally call this method directly. 33.27.19 Other Methods å protected Comparable getSectionKey(int section); [1.0.3] Returns the key for the specified section. An index can be assigned to a PiePlot—this is used by the MultiplePiePlot class as a way of identifying subplots, and the index is picked up the StandardPieURLGenerator class when generating URLs for HTML image maps: å public int getPieIndex(); Returns the index that has been assigned to the plot. å public void setPieIndex(int index); Sets the index for the plot. This method generates no notification event. As a workaround for JRE bug 4836495, a minimum arc angle is maintained by the plot—pie segments with an angle less than this value are not drawn: å public double getMinimumArcAngleToDraw(); Returns the minimum angle for drawing the arc segment for a pie section. The default value is 0.00001. å public void setMinimumArcAngleToDraw(double angle); Sets the minimum angle for drawing a pie segment. Any segment with an angle less than this value will not be drawn. This is a workaround for a JRE bug: • see http://bugs.sun.com/bugdatabase/view bug.do?bug id=4836495 33.27.20 Notes Some points to note: • chapter 5 provides a general overview of the pie chart support in JFreeChart; • there are several methods in the ChartFactory class that will construct a default pie chart for you; • the DatasetUtilities class has methods for creating a PieDataset from a CategoryDataset; • the PieChartDemo1 class in the org.jfree.chart.demo package provides a simple pie chart demonstration (plus, there are more demos included in the JFreeChart demo collection). • the default section label format changed between version 1.0.1 and 1.0.2 of JFreeChart—in later versions, only the section key (and not the value) is displayed; • some label layout bug fixes included from version 1.0.8 onwards have resulted in the chart dimensions changing—you may need to adjust your code for this. See Also PieDataset, PieSectionLabelGenerator, PieToolTipGenerator, Plot. CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT 33.28 PiePlot3D 33.28.1 Overview 354 An extension of the PiePlot class that draws pie charts with a 3D effect—see figure 33.15 for an example. The ChartFactory class has a createPieChart3D() method that you can use to create a ready-made JFreeChart instance containing a PiePlot3D. Pie Chart 3D Demo 1 C/C++ Visual Basic PHP Java Perl Java Visual Basic C/C++ PHP Perl Figure 33.15: A pie chart with 3D effect (see PieChart3DDemo1.java) 33.28.2 Limitations To avoid over-selling this plot type, let’s point out that it has some limitations: • the 3D effect is drawn using plain 2D graphics primitives—there is no 3D engine performing a perspective transformation, no ability to control the viewing angle, etc. The effect looks fine when the plot is wider than it is tall, but resizing the chart can result in the perspective looking wrong; • the plot does not support the “exploded” sections that the regular PiePlot class supports; For now, we suggest that you avoid this class unless you can live with its limitations. In the future, we hope to reimplement this class using a proper 3D graphics engine. 33.28.3 Constructor To create a new instance: å public PiePlot3D(); Equivalent to PiePlot3D(null)—see the next constructor. å public PiePlot3D(PieDataset dataset); Creates a new plot with the specified dataset (null is permitted). 33.28.4 General Attributes This class inherits most of its attributes from the PiePlot class. The depth factor specifies the size of the 3D effect as a percentage of the height of the plot area: å public double getDepthFactor(); Returns the depth factor for the 3D effect, as a percentage of the height of the pie plot. The default value is 0.12 (twelve percent). CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT 355 å public void setDepthFactor(double factor); Sets the depth factor (as a percentage of the height of the pie plot) and sends a PlotChangeEvent to all registered listeners. A new flag has been introduced in JFreeChart 1.0.7 to control whether or not the sides of the pie plot are drawn in a darker colour—this only works when the sectionPaint is an instance of java.awt.Color: å public boolean getDarkerSides(); [1.0.7] Returns the flag that controls whether or not the sides of the pie plot are drawn using a darker colour. The default is false (to preserve the existing behaviour). å public void setDarkerSides(boolean darker); [1.0.7] Sets the flag that controls whether or not the sides of the pie plot are drawn using a darker colour, and sends a PlotChangeEvent to all registered listeners. 33.28.5 Other Methods The other methods are intended for use by JFreeChart—you won’t normally call these methods directly: å public String getPlotType(); Returns a localised string describing the plot type. This can be used for display to end-users (for example, in the property editors). The JFreeChart class will call the following method to draw the plot: å public void draw(...); Draws the plot within a specified area. å protected void drawSide(...); Draws the sides for one segment. 33.28.6 Equals, Cloning and Serialization This class overrides the equals() method:4 å public boolean equals(Object obj); Tests this plot for equality with an arbitrary object. If obj is null, this method returns false. Instances of this class are Cloneable and Serializable. 33.28.7 Notes Some points to note: • the translucent appearance of the sample chart is achieved by setting the plot’s foreground alpha to 0.5f—see the setForegroundAlpha() method in the Plot class; • some demos (PieChart3DDemo1-3.java) are included in the JFreeChart demo collection. • additional information is provided in section 5.8; See Also PiePlot. 4 At least, as of version 1.0.5 it does! CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT 33.29 PiePlotState 33.29.1 Overview 356 A class that records temporary state information during the drawing of a pie chart. This allows one instance of a PiePlot to be drawn to multiple targets simultaneously (for example, a chart might be drawn on the screen at the same time it is being saved to a file). 33.30 Plot 33.30.1 Overview An abstract base class that controls the visual representation of data in a chart. The JFreeChart class maintains a reference to a Plot, and will provide it with an area in which to draw itself (after allocating space for the chart titles and legend). A range of subclasses are used to create different types of charts: • CategoryPlot – for bar charts and other plots where one axis displays categories and the other axis displays values; • MeterPlot – dials, thermometers and other plots that display a single value; • PiePlot – for pie charts; • XYPlot – for line charts, scatter plots, time series charts and other plots where both axes display numerical (or date) values; Figure 33.16 illustrates the plot class hierarchy. Plot #dataset CategoryPlot PiePlot +getDataset() +getDomainAxis() +getRangeAxis() +getDataset() CombinedDomainCategoryPlot MeterPlot XYPlot +getMeterDataset() +getDataset() +getDomainAxis() +getRangeAxis() ThermometerPlot CombinedRangeCategoryPlot CombinedDomainXYPlot OverlaidCategoryPlot CombinedRangeXYPlot OverlaidXYPlot Figure 33.16: Plot classes When a chart is drawn, the JFreeChart class first draws the title (or titles) and legend. Next, the plot is given an area (the plot area) into which it must draw a representation of its dataset. This function is implemented in the draw() method, each subclass of Plot takes a slightly different approach. 33.30.2 Constructors This class is abstract, so the constructor is protected. You cannot create an instance of this class directly, you must use a subclass. CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT Attribute: Description: parent datasetGroup insets outlineStroke outlinePaint backgroundPaint backgroundImage The parent plot (possibly null). The dataset group (not used). The amount of space to leave around the outside of the plot. The Stroke used to draw an outline around the plot area. The Paint used to draw an outline around the plot area. The Paint used to draw the background of the plot area. An image that is displayed in the background of the plot (can be null). The image alignment. The alpha transparency value used when coloring the plot’s background, and also when drawing the background image (if there is one). The alpha transparency used to draw items in the plot’s foreground. A string that is displayed by some plots when there is no data to display. The Font used to display the “no data” message. The Paint used to display the “no data” message. The drawing supplier (provides default colors and line strokes). backgroundImageAlignment backgroundAlpha foregroundAlpha noDataMessage noDataMessageFont noDataMessagePaint drawingSupplier 357 Table 33.7: Attributes for the Plot class 33.30.3 Attributes This class maintains the attributes listed in table 33.7. All subclasses will inherit these core attributes. 33.30.4 Usage To customise the appearance of a plot, you first obtain a reference to the plot as follows: Plot plot = chart.getPlot(); With this reference, you can change the appearance of the plot by modifying it’s attributes. For example: plot.setBackgroundPaint(Color.lightGray); plot.setNoDataMessage("There is no data."); Very often, you will find it necessary to cast the Plot object to a specific subclass so that you can access attributes that are defined by the subclass. Refer to the usage notes for each subclass for more details. 33.30.5 The Plot Type The following method returns a string indicating the plot type: å public abstract String getPlotType(); Returns a string indicating the plot type. This method must never return null. The string can be localised (that is, a different string may be returned for each locale). The method is abstract, and subclasses are required to implement it. 33.30.6 The Plot Border An border is drawn around the outside of most plot types. You can change the appearance of the border by modifying the Paint and Stroke used to draw it (or set either to null to hide the border completely). å public Paint getOutlinePaint(); Returns the paint used to draw the plot outline. The default value is Color.GRAY. CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT 358 å public void setOutlinePaint(Paint paint); Sets the paint used to draw the plot outline and sends a PlotChangeEvent to all registered listeners. If you set this to null, no outline will be drawn. å public Stroke getOutlineStroke(); Returns the stroke used to draw the plot outline. The default value is BasicStroke(0.5f). å public void setOutlineStroke(Stroke stroke); Sets the stroke used to draw the plot outline and sends a PlotChangeEvent to all registered listeners. If you set this to null, no outline will be drawn. For the CategoryPlot and XYPlot classes, the outline is drawn around all four sides of the data area. Note that each of the plot’s axes may also draw a line along the edge of the data area—see the axisLineVisible attribute defined in the Axis class. 33.30.7 The Plot Background The background area for a plot is the area inside the plot’s axes (if the plot has axes)—it does not include the chart titles, the legend or the axis labels. The plot’s background is filled with the backgroundPaint: å public Paint getBackgroundPaint(); Returns the paint used to fill the plot’s background, or null if the plot has a transparent background. The default value is Color.WHITE. å public void setBackgroundPaint(Paint paint); Sets the background paint for the plot and sends a PlotChangeEvent to all registered listeners. You can set this attribute to null for a transparent plot background (in this case, the chart’s background is visible—see the JFreeChart class for more information). The alpha transparency for the plot’s background is configurable: å public float getBackgroundAlpha(); Returns the alpha transparency for the plot’s background. The default value is 1.0f (opaque). å public void setBackgroundAlpha(float alpha); Sets the alpha transparency for the plot’s background and sends a PlotChangeEvent to all registered listeners. The range of values permitted is 0.0f (fully transparent) through to 1.0f (fully opaque). If the background is at all transparent, you will be able to see the chart’s background showing through. You can also add an image to the background area: å public Image getBackgroundImage(); Returns the background image for the plot. The default value is null. å public void setBackgroundImage(Image image); Sets the background image for the plot5 and sends a PlotChangeEvent to all registered listeners. If image is null, no background image will be drawn. A number of options are provided for aligning the background image: å public int getBackgroundImageAlignment(); Returns the alignment type for the background image. The default values is Align.FIT (which means the image is stretched to fit the available space). To modify the alignment, use the following method: å public void setBackgroundImageAlignment(int alignment); Sets the alignment for the background image and sends a PlotChangeEvent to all registered listeners. For the alignment argument, use one of the predefined constants in the Align class from the JCommon class library: CENTER, TOP, BOTTOM, LEFT, RIGHT, TOP LEFT, TOP RIGHT, BOTTOM LEFT, BOTTOM RIGHT, FIT HORIZONTAL, FIT VERTICAL and FIT (stretches to fill the entire area). 5 Take care that the image supplied is actually loaded into memory. The createImage() method in Java’s Toolkit class will load images asynchronously, which can result in a chart being drawn before the background image is available—see section 20.4 for more information. CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT 359 The background image can be drawn using an alpha-transparency, you can set this as follows: å public float getBackgroundImageAlpha(); Returns the alpha transparency for drawing the background image. å public void setBackgroundImageAlpha(float alpha); Sets the alpha transparency for drawing the background image, and sends a PlotChangeEvent to all registered listeners. There are similar methods in the JFreeChart class that allow you to control the background area for the chart (which encompasses the entire chart area). 33.30.8 The Plot Insets The space around the outside of the plot is controlled by the plot insets: å public RectangleInsets getInsets(); Returns the insets for the plot (never null). The default value is RectangleInsets(4.0, 8.0, 4.0, 8.0). å public void setInsets(RectangleInsets insets); Equivalent to setInsets(insets, true)—see next method. å public void setInsets(RectangleInsets insets, boolean notify); Sets the insets for the plot and, if notify is true, sends a PlotChangeEvent to all registered listeners. If insets is null, this method throws an IllegalArgumentException. 33.30.9 The Drawing Supplier The “drawing supplier” is a plug-in object responsible for providing a never-ending sequence of Paint and Stroke objects for the plot and its renderers. A default instance is installed for every plot automatically, but you can provide a custom supplier if you need to: å public DrawingSupplier getDrawingSupplier(); Returns the drawing supplier for the plot (or the plot’s parent if this is a subplot). å public void setDrawingSupplier(DrawingSupplier supplier); Sets the drawing supplier and sends a PlotChangeEvent to all registered listeners. A null supplier is not permitted. In cases where there is a hierarchy of plots, the intention is that the drawing supplier of the root plot is shared by all the subplots—this ensures that colors are not duplicated by subplots. 33.30.10 The Parent Plot Some plot classes (such as the CombinedDomainXYPlot class) manage a number of child plots. A child plot can access its parent plot via the following method: å public Plot getParent(); Returns the parent plot, or null if this plot has no parent. å public void setParent(Plot parent); Sets the parent plot for this plot. This method is intended for use by JFreeChart, you shouldn’t need to call it directly. In fact, setting the parent plot incorrectly will corrupt your chart. If a plot has a parent, then it is sometimes referred to as a subplot. The following method can be used to determine if a plot is a subplot: å public boolean isSubplot(); Returns true if this plot is a subplot. To determine the plot at the root of a hierarchy of plots, use the following method: å public Plot getRootPlot() Returns this plot if there is no parent plot, otherwise returns the root plot for this plot’s parent. CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT 33.30.11 360 The Dataset Group The datasetGroup attribute is not currently used. It was originally intended to provide a single object on which to synchronise access to multiple datasets, for those plots that use more than one dataset. However, this has never been implemented. å public DatasetGroup getDatasetGroup(); Returns the dataset group for the plot. This is not used. å protected void setDatasetGroup(DatasetGroup group); Sets the dataset group for the plot. This is not used. 33.30.12 The “No Data” Message” Some plots will display a message when no data is available for plotting. The message itself is a simple string, controlled via the following methods: å public String getNoDataMessage(); Returns the string displayed by some plots when no data is available. The default value is null. å public void setNoDataMessage(String message); Sets the string displayed by some plots when no data is available and sends a PlotChangeEvent to all registered listeners. To control the font: å public Font getNoDataMessageFont(); Returns the font used to display the “no data” message (never null). The default value is Font("SansSerif", Font.PLAIN, 12). å public void setNoDataMessageFont(Font font); Sets the font used to display the “no data” message and sends a PlotChangeEvent to all registered listeners. If font is null, this method throws an IllegalArgumentException. To control the paint: å public Paint getNoDataMessagePaint(); Returns the paint used to display the “no data” message (never null). The default value is Color.BLACK. å public void setNoDataMessagePaint(Paint paint); Sets the paint used to display the “no data” message and sends a PlotChangeEvent to all registered listeners. If paint is null, this method throws an IllegalArgumentException. 33.30.13 Legend Items The following method returns a new collection of legend items for the plot: å public LegendItemCollection getLegendItems(); This implementation returns null—subclasses should override this method. 33.30.14 Other Methods The JFreeChart class expects every plot to implement the draw() method, and uses this to draw the plot in a specific area via a Graphics2D instance. You won’t normally need to call this method yourself: å public abstract void draw(Graphics2D g2, Rectangle2D area, Point2D anchor, PlotState parentState, PlotRenderingInfo info); Draws the chart using the supplied Graphics2D. The plot should be drawn within the plotArea. If you wish to record details of the items drawn within the plot, you need to supply a ChartRenderingInfo object. Once the drawing is complete, this object will contain a lot of information about the plot. If you don’t want this information, pass in null. CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT 361 The following method (only used by plots that have axes) receives notification of axis changes: å public void axisChanged(AxisChangeEvent event); Fires a PlotChangeEvent. The following method receives notification whenever a Marker managed by the plot is modified: å public void markerChanged(MarkerChangeEvent event); [1.0.3] Called whenever a marker managed by this plot is changed. In response, this method fires a PlotChangeEvent which, by default, will be received by the chart that owns this plot. 33.30.15 Notes Refer to specific subclasses for information about setting the colors, shapes and line styles for data drawn by the plot. 33.31 PlotOrientation 33.31.1 Overview Used to represent the orientation of a plot (in particular, the CategoryPlot and XYPlot classes). There are two values, as listed in table 33.8. Class: Description: PlotOrientation.HORIZONTAL PlotOrientation.VERTICAL A “horizontal” orientation. A “vertical” orientation. Table 33.8: Plot orientation values The orientation corresponds to the “direction” of the range axis. So, for example, a bar chart with a vertical orientation will display vertical bars, while a bar chart with a horizontal orientation will display horizontal bars. 33.31.2 Notes Some points to note: • for interesting effects, in addition to changing the orientation of a chart you can: – change the location of the chart’s axes—see the setAxisLocation() methods in the plot classes; – invert the scale of the axes—see the setInverted(boolean) method in the axis classes. • two demos (PlotOrientationDemo1.java and PlotOrientationDemo2.java) are included in the JFreeChart demo collection. 33.32 PlotRenderingInfo 33.32.1 Overview This class is used to record information about the individual elements in a single rendering of a plot. Typically, you will obtain one of these from the ChartRenderingInfo class—it is not a class that you are likely to need to instantiate yourself. CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT 33.32.2 362 Constructor To create a new instance: å public PlotRenderingInfo(ChartRenderingInfo owner); Creates a new instance belonging to the specified ChartRenderingInfo instance. You can supply a null owner (JFreeChart does this internally when a temporary instance is required). 33.32.3 Methods To find the owner of this instance: å public ChartRenderingInfo getOwner(); Returns the ChartRenderingInfo instance that owns this PlotRenderingInfo instance. This may be null. To access the plot area: å public Rectangle2D getPlotArea(); Returns the area (in Java2D space) in which the plot is drawn. å public void setPlotArea(Rectangle2D area); Sets the area (in Java2D space) into which the plot has been drawn. This method is used internally by JFreeChart, you shouldn’t need to call it yourself (unless you are developing your own plot class). To access the data area: å public Rectangle2D getDataArea(); Returns the area (in Java2D space) in which the data is drawn (that is, the area “inside” the axes). å public void setDataArea(Rectangle2D area); Sets the area (in Java2D space) into which the data items are drawn. This method is used internally by JFreeChart, you shouldn’t need to call it yourself (unless you are developing your own plot class). 33.32.4 Subplot Info Some plots (such as CombinedDomainXYPlot) manage a number of subplots, and there will be a PlotRenderingInfo instance for each of these subplots. The following methods provide access to these instances: å public int getSubplotCount(); Returns the number of subplots (possibly zero). å public void addSubplotInfo(PlotRenderingInfo info); Adds a PlotRenderingInfo instance for a subplot. å public PlotRenderingInfo getSubplotInfo(int index); Returns a PlotRenderingInfo instance for the specified subplot. å public int getSubplotIndex(Point2D source); Returns the index of the subplot (if any) at the specified location in Java2D space. If source is null, this method throws an IllegalArgumentException. 33.32.5 Equals, Cloning and Serialization This class overrides the equals() method: å public boolean equals(Object obj); Tests this instance for equality with an arbitrary object. å public Object clone() throws CloneNotSupportedException; Returns a clone of this instance. This is a deep clone except for the owner field, which is simply copied as a reference. CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT 33.33 PlotState 33.33.1 Overview 363 A class that records temporary state information during the drawing of a chart. This allows a single chart instance to be drawn to multiple targets simultaneously (for example, a chart might be drawn on the screen at the same time it is being saved to a file). 33.34 PlotUtilities 33.34.1 Overview A class containing static utility methods related to plots. JFreeChart version 1.0.7. 33.34.2 This class was first introduced in Methods To determine if a plot contains no data: å public static boolean isEmptyOrNull(XYPlot plot); [1.0.7] Returns true if the datasets for the specified plot are either empty or null, and false otherwise. See Also: DatasetUtilities 33.35 PolarPlot 33.35.1 Overview A plot that is used to display data from an XYDataset using polar coordinates—see figure 33.17 for an example. Figure 33.17: A polar chart The items in the plot are drawn by a PolarItemRenderer. 33.35.2 Usage A demo application (PolarChartDemo1.java) is included in the JFreeChart demo collection. CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT 33.35.3 364 Constructors To create a new plot: å public PolarPlot(); Creates a new plot with no dataset, axis or renderer. If you use this constructor, you will need to supply a plot, dataset and renderer separately. å public PolarPlot(XYDataset dataset, ValueAxis radiusAxis, PolarItemRenderer renderer); Creates a new polar plot with the specified dataset, axis and renderer. The x-values in the dataset should be in the range 0-360 degrees. The axis is typically an instance of NumberAxis and the renderer is typically an instance of DefaultPolarItemRenderer. Note that a convenience method (createPolarChart()) for creating charts based on this plot is provided in the ChartFactory class. 33.35.4 Axis, Dataset and Renderer This plot supports a single axis (the range or y-axis), dataset and renderer. To access the axis: å public ValueAxis getAxis(); Returns the axis that provides the value scale for the plot. å public void setAxis(ValueAxis axis); Sets the axis that provides the value scale for the plot and sends a PlotChangeEvent to all registered listeners. The axis will extend from the center of the plot towards the right hand side of the chart. To access the dataset: å public XYDataset getDataset(); Returns the dataset for the plot (possibly null). Note that this plot only allows for a single dataset, unlike some other plots in JFreeChart. å public void setDataset(XYDataset dataset); Sets the dataset for the plot (null is permitted). This method sends a DatasetChangeEvent to the plot, which in turn generates a PlotChangeEvent for all registered listeners. To access the renderer: å public PolarItemRenderer getRenderer(); Returns the current renderer. If the renderer is null, no data will be displayed. å public void setRenderer(PolarItemRenderer renderer); Sets the renderer and sends a PlotChangeEvent to all registered listeners. If you set the renderer to null, no data will be displayed. 33.35.5 Angle Gridlines The “angle gridlines” are the (optional) lines radiating out from the center of the chart. These are hard-coded (at present) to appear at 45 degree intervals. You can control whether or not the labels for the gridlines are visible with the following methods: å public boolean isAngleLabelsVisible(); Returns the flag that controls whether or not the angle labels are visible. å public void setAngleLabelsVisible(boolean visible); Sets the flag that controls whether or not the angle labels are visible and sends a PlotChangeEvent to all registered listeners. If the new flag value is the same as the old flag value, this method does nothing. The font used to display the labels: å public Font getAngleLabelFont(); Returns the font for the angle labels (never null). CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT 365 å public void setAngleLabelFont(Font font); Sets the font for the angle labels and sends a PlotChangeEvent to all registered listeners. An exception is thrown if font is null. The (foreground) paint used to display the labels: å public Paint getAngleLabelPaint(); Returns the paint for the angle labels (never null). å public void setAngleLabelPaint(Paint paint); Sets the paint for the angle labels and sends a PlotChangeEvent to all registered listeners. An exception is thrown if paint is null. To control whether or not the angle gridlines are displayed: å public boolean isAngleGridlinesVisible(); Returns the flag that controls whether or not the angle gridlines are displayed. å public void setAngleGridlinesVisible(boolean visible); Sets the flag that controls whether or not the angle gridlines are visible and sends a PlotChangeEvent to all registered listeners. If the new flag value is the same as the old flag value, this method does nothing. The stroke and paint used for the gridlines is controlled with the following methods: å public Stroke getAngleGridlineStroke(); Returns the stroke used to display the angle gridlines (never null). å public void setAngleGridlineStroke(Stroke stroke); Sets the stroke used to display the angle gridlines and sends a PlotChangeEvent to all registered listeners. An exception is thrown if stroke is null. å public Paint getAngleGridlinePaint(); Returns the paint used to display the angle gridlines (never null). å public void setAngleGridlinePaint(Paint paint); Sets the paint used to display the angle gridlines and sends a PlotChangeEvent to all registered listeners. An exception is thrown if paint is null. 33.35.6 Radius Gridlines The “radius gridlines” are drawn as circles at a regular interval that is controlled by the size of the tick unit on the plot’s axis. å public boolean isRadiusGridlinesVisible(); Returns the flag that controls whether or not the radius gridlines are drawn. å public void setRadiusGridlinesVisible(boolean visible); Sets the flag that controls whether or not the radius gridlines are visible and sends a PlotChangeEvent to all registered listeners. If the new flag value is the same as the old flag value, this method does nothing. å public Stroke getRadiusGridlineStroke(); Returns the radius gridline stroke (never null). å public void setRadiusGridlineStroke(Stroke stroke); Sets the stroke used to draw the radius gridlines and sends a PlotChangeEvent to all registered listeners. An exception is thrown if stroke is null. å public Paint getRadiusGridlinePaint(); Returns the radius gridline paint (never null). å public void setRadiusGridlinePaint(Paint paint); Sets the paint used to draw the radius gridlines and sends a PlotChangeEvent to all registered listeners. An exception is thrown if paint is null. CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT 33.35.7 366 Corner Text Items This plot provides an option to add one or more short text items (called “corner text items”) to the lower right corner of the plot: å public void addCornerTextItem(String text); Adds a small text item to be displayed at the bottom right corner of the plot and sends a PlotChangeEvent to all registered listeners. An exception is thrown if text is null. å public void removeCornerTextItem(String text); Removes the specified item from the list of corner text items (if the item is not in the list, this method does nothing) and sends a PlotChangeEvent to all registered listeners. å public void clearCornerTextItems(); Removes all corner text items from the list and sends a PlotChangeEvent to all registered listeners. 33.35.8 Drawing Methods The following method is called by the JFreeChart class during chart drawing: å public void draw(Graphics2D g2, Rectangle2D plotArea, Point2D anchor, PlotState parentState, PlotRenderingInfo state); Draws the plot within the specified area. In typical situations, you won’t normally call this method directly. Likewise for these other drawing methods: å protected void drawCornerTextItems(Graphics2D g2, Rectangle2D area); Draws the corner text items (in the lower right corner of the plot). å protected AxisState drawAxis(Graphics2D g2, Rectangle2D plotArea, Rectangle2D dataArea); Draws the radial axis. This extends from the center of the plot out towards the right hand side of the chart. å protected void render(Graphics2D g2, Rectangle2D dataArea, PlotRenderingInfo info); Draws the data values on the chart using the current renderer. å protected void drawGridlines(Graphics2D g2, Rectangle2D dataArea, List angularTicks, List radialTicks); Draws the gridlines for the chart. 33.35.9 Zooming Methods This plot supports zooming for the range axis only. Most of the methods documented below belong to the Zoomable interface, but because the plot has only one axis, some of the methods do nothing. The objective of these methods is to support the zooming mechanism provided by the ChartPanel class. å public PlotOrientation getOrientation(); Returns PlotOrientation.HORIZONTAL always. This method is required by the Zoomable interface, but not used by this class. å public boolean isDomainZoomable(); Returns false, because there is no domain axis to zoom. å public boolean isRangeZoomable(); Returns true to indicate that the range axis is zoomable. å public void zoom(double percent); Zooms in or out by the specified amount. Values less than 1.0 reduce the axis range (“zoom in”) and values greater than 1.0 expand the axis range (“zoom out”). å public void zoomRangeAxes(double factor, PlotRenderingInfo state, Point2D source); Zooms the range axis. CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT 367 å public void zoomRangeAxes(double lowerPercent, double upperPercent, PlotRenderingInfo state, Point2D source); Zooms the range axis. å public void zoomDomainAxes(double factor, PlotRenderingInfo state, Point2D source); This method does nothing, since the plot has no domain axes. å public void zoomDomainAxes(double lowerPercent, double upperPercent, PlotRenderingInfo state, Point2D source); This method does nothing, since the plot has no domain axes. 33.35.10 Other Methods The remaining methods in this class are: å public String getPlotType(); Returns a short (localised) string describing the plot type. å public int getSeriesCount(); A convenience method that returns the number of series in the plot’s dataset (or zero if the dataset is null). å public Range getDataRange(ValueAxis axis); Returns the range of y-values for the specified axis. For this plot (which has only one axis and one dataset) this is the range of y-values in the plot’s dataset. å public LegendItemCollection getLegendItems(); Returns the legend items for the plot. This method is called by the chart drawing code, you won’t normally need to call it yourself. You can override this method to alter the items that are displayed in the legend. The plot registers itself with its dataset and receives notification of any changes to the dataset via the following method: å public void datasetChanged(DatasetChangeEvent event); This method is called whenever the plot’s dataset is updated. You won’t normally need to call this method directly. Likewise, the plot registers itself with its renderer and receives notification of any changes to the renderer via the following method: å public void rendererChanged(RendererChangeEvent event); This method is called whenever the plot’s renderer is updated. You won’t normally need to call this method directly. 33.35.11 Equals, Cloning and Serialization To test a plot for equality with an arbitrary object: å public boolean equals(Object obj); Returns true if this plot is equal to obj and false otherwise. To create a clone of the plot: å public Object clone() throws CloneNotSupportedException; Returns a clone of the plot (note that the dataset is not cloned). This class implements Serializable. 33.35.12 Notes Some points to note: • this plot does not support multiple axes, datasets or renderers; • a demo (PolarChartDemo1.java) is included in the JFreeChart demo collection. CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT 33.36 RainbowPalette 33.36.1 Overview 368 A rainbow palette (extends ColorPalette) used by the ContourPlot class. This class is deprecated as of version 1.0.4. 33.37 RingPlot 33.37.1 Overview A ring plot is an adaptation of a pie plot, where a hole is left in the middle of the “pie”—see figure 33.18 for an example. This class extends the PiePlot class. Figure 33.18: A ring chart 33.37.2 Constructors The default constructor: å public RingPlot(); Creates a new plot with null for the dataset. To create a new plot with a given dataset: å public RingPlot(PieDataset dataset); Creates a new plot with the specified dataset (null is permitted). 33.37.3 Section Depth The depth (or thickness) of the ring is configurable with the following methods: å public double getSectionDepth(); [1.0.3] Returns the section depth as a percentage of the plot’s radius. The default value is 0.20 (twenty percent). å public void setSectionDepth(double sectionDepth); [1.0.3] Sets the section depth and sends a PlotChangeEvent to all registered listeners. CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT 33.37.4 369 Separators The plot can draw lines to highlight the separation between sections. The separators have a number of attributes that can be customised: • visibility – you can display or hide the separators; • stroke – the line style for the separator lines; • paint – the color for the separator lines; • inner extension – the amount by which the separator lines extend into the interior of the plot; • outer extension – the amount by which the separator lines extend outside the plot. These attributes are controlled by the following methods: å public boolean getSeparatorsVisible(); Returns true if the separators between sections are visible, and false otherwise. The default value is true. å public void setSeparatorsVisible(boolean visible); Sets the flag that controls whether or not the separators between sections are visible, and sends a PlotChangeEvent to all registered listeners. å public Stroke getSeparatorStroke(); Returns the stroke used to draw the separator lines, if they are visible. This method never returns null. The default value is BasicStroke(0.5f). å public void setSeparatorStroke(Stroke stroke); Sets the stroke used to draw the separator lines (null not permitted) and sends a PlotChangeEvent to all registered listeners. å public Paint getSeparatorPaint(); Returns the paint used to draw the separator lines, if they are visible. This method never returns null. The default value is Color.gray. å public void setSeparatorPaint(Paint paint); Sets the paint used to draw the separator lines (null not permitted) and sends a PlotChangeEvent to all registered listeners. å public double getInnerSeparatorExtension(); Returns the length of the separator line drawn inside the ring for each section. The value is a percentage of the ring depth (the default is 0.20). å public void setInnerSeparatorExtension(double percent); Sets the length of the inner separator line as a percentage of the ring depth and sends a PlotChangeEvent to all registered listeners. å public double getOuterSeparatorExtension(); Returns the length of the outer separator line for each section, as a percentage of the ring depth. The default value is 0.20 (twenty percent). å public void setOuterSeparatorExtension(double percent); Sets the length of the outer separator line as a percentage of the ring depth, and sends a PlotChangeEvent to all registered listeners. 33.37.5 Equals, Cloning and Serialization This class overrides the equals() method: å public boolean equals(Object obj); Tests this plot for equality with an arbitrary object. Note that the plot’s dataset is NOT considered in the equality test. This class is Cloneable and Serializable. CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT 33.37.6 370 Notes Some points to note: • this plot only supports a single ring. Support for multiple concentric rings would be an interesting addition to JFreeChart; • a demo (RingChartDemo1.java) is included in the JFreeChart demo collection. 33.38 SeriesRenderingOrder 33.38.1 Overview Used to represent the order in which a plot passes the series in a dataset to the renderer. There are two values, as listed in table 33.9. Class: Description: SeriesRenderingOrder.FORWARD SeriesRenderingOrder.REVERSE Forward. Reverse. Table 33.9: Series rendering order values 33.38.2 Notes See the setSeriesRenderingOrder() method in the XYPlot class. 33.39 SpiderWebPlot 33.39.1 Overview A plot that displays data from a CategoryDataset in a format that resembles a spider web—see figure 33.19 for an example. Figure 33.19: A spider web chart (see SpiderWebChartDemo1.java) 33.39.2 Constructors There are three constructors for this class: CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT 371 å public SpiderWebPlot(); Creates a new plot with a null dataset. All attributes are initialised with default values. å public SpiderWebPlot(CategoryDataset dataset); Creates a new plot with the given dataset (null is permitted), with each row in the dataset representing a series. å public SpiderWebPlot(CategoryDataset dataset, TableOrder extract); Creates a new plot with the given dataset. The extract argument controls whether rows or columns in the dataset are represented as “series” for the plot. 33.39.3 Methods To get a brief description of the plot type: å public String getPlotType(); Returns a short, localised, string describing the plot type (“Spider Web Plot” in English). To access the plot’s dataset: å public CategoryDataset getDataset(); Returns the plot’s dataset, which may be null. å public void setDataset(CategoryDataset dataset); Sets the dataset for the plot and sends a PlotChangeEvent to all registered listeners. The dataset can be set to null. To control the order in which data items are read from the dataset: å public TableOrder getDataExtractOrder(); Returns the “order” in which data items are extracted from the dataset. For TableOrder.BY ROW (the default), each row is considered to be a series. For TableOrder.BY COLUMN, each column in the dataset is considered to be a series. å public void setDataExtractOrder(TableOrder order); Sets the “order” in which data items are extracted from the dataset, and sends a PlotChangeEvent to all registered listeners. If order is null, this method throws an IllegalArgumentException. To specify the starting position for the first category: å public double getStartAngle(); Returns the angle of the first category, in degrees, relative to a radial line extending from the center of the plot horizontally to the right (that is, 3 o’clock on a clock face), in an anticlockwise direction. The default value is 90.0 which draws the first category at the top of the plot (that is, 12 o’clock). å public void setStartAngle(double angle); Sets the angle for the first category, in degrees, and sends a PlotChangeEvent to all registered listeners. To specify the direction in which categories are added to the plot: å public Rotation getDirection(); Returns the direction in which the categories are added to the plot. The default is Rotation.CLOCKWISE. å public void setDirection(Rotation direction); Sets the direction in which the categories are added to the plot and sends a PlotChangeEvent to all registered listeners. To control the size of the shapes drawn for each data item: å public double getHeadPercent(); Returns the size of the shapes drawn at each data point. This is a percentage of width and height of the plot area. The default value is 0.01 (one percent). å public void setHeadPercent(double percent); Sets the size of the shapes drawn at each data point and sends a PlotChangeEvent to all registered listeners. The size is a percentage of the plot area height and width. CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT 372 To control whether the “web” for each data series is filled or unfilled: å public boolean isWebFilled(); Returns the flag that controls whether the interior of the polygon defined by the data points for one series is filled. The default value is true. å public void setWebFilled(boolean flag); Sets the flag that controls whether the interior of the polygon defined by the data points for each series is filled, and sends a PlotChangeEvent to all registered listeners. å public double getMaxValue(); Returns the maximum value for display on the axes. å public void setMaxValue(double value); Sets the maximum value for display on the axes. å public double getInteriorGap(); Returns a percentage between 0.0 and 0.40 (forty percent) indicating the amount of whitespace to leave around the plot (some of which is used for the labels). The default value is 0.25. å public void setInteriorGap(double percent); Sets the amount of whitespace around the plot as a percentage (in the range 0.0 to 0.40). To appearance and position of the category labels on the chart can be controlled via the following methods: å public Font getLabelFont(); Returns the font used to display category labels (never null). The default is Font("SansSerif", Font.PLAIN, 10). å public void setLabelFont(Font font); Sets the font used to display category labels and sends a PlotChangeEvent to all registered listeners. An exception is thrown if font is null. å public Paint getLabelPaint(); Returns the paint used to display category labels (never null). The default is Color.black. å public void setLabelPaint(Paint paint); Sets the paint used to display category labels and sends a PlotChangeEvent to all registered listeners. An exception is thrown if paint is null. å public double getAxisLabelGap(); Returns the gap between the end of each “radial” axis and the corresponding label, expressed as a percentage of the axis length. The default value is 0.10 (ten percent). å public void setAxisLabelGap(double gap); Sets the gap between the end of each “radial” axis and the corresponding label, expressed as a percentage of the axis length, and sends a PlotChangeEvent to all registered listeners. 33.39.4 Series Attributes Paint The paint used to draw each series is specified on a “per series” basis: å public Paint getSeriesPaint(int series); Returns the paint for the specified series. If getSeriesPaint() returns a non-null value, this is returned. Otherwise, the method checks to see if a specific value has been set for the series, in which case that is returned. If all else fails, the value returned by getBaseSeriesPaint() is used. å public void setSeriesPaint(int series, Paint paint); Sets the paint for the specified series and sends a PlotChangeEvent to all registered listeners. It is permitted to set this to null. The base paint is used as the fallback for any series that doesn’t have a paint explicitly defined: å public Paint getBaseSeriesPaint(); Returns the default series paint (never null). CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT 373 å public void setBaseSeriesPaint(Paint paint); Sets the default series paint and sends a PlotChangeEvent to all registered listeners. As a convenience, you can override the paint for ALL series, although in typical usage you won’t need to do this:6 å public Paint getSeriesPaint(); Returns the override paint for all series. The default value is null. å public void setSeriesPaint(Paint paint); Sets the override paint for all series and sends a PlotChangeEvent to all registered listeners. OutlinePaint The outline paint used to for each series (to draw the outline of the shape at each data point) is specified on a “per series” basis: å public Paint getSeriesOutlinePaint(int series); Returns the outline paint for the specified series. If getSeriesOutlinePaint() returns a nonnull value, this is returned. Otherwise, the method checks to see if a specific value has been set for the series, in which case that is returned. If all else fails, the value returned by getBaseSeriesOutlinePaint() is used. å public void setSeriesOutlinePaint(int series, Paint paint); Sets the outline paint for the specified series and sends a PlotChangeEvent to all registered listeners. It is permitted to set this to null. The base paint is used as the fallback for any series that doesn’t have a paint explicitly defined: å public Paint getBaseSeriesOutlinePaint(); Returns the default series outline paint (never null). å public void setBaseSeriesOutlinePaint(Paint paint); Sets the default series outline paint and sends a PlotChangeEvent to all registered listeners. As a convenience, you can override the outline paint for ALL series, although in typical usage you won’t need to do this:7 å public Paint getSeriesOutlinePaint(); Returns the override outline paint for all series. The default value is null. å public void setSeriesOutlinePaint(Paint paint); Sets the outline paint for the specified series and sends a PlotChangeEvent to all registered listeners. It is permitted to set this to null. OutlineStroke The outline stroke used to for each series (to draw the outline of the shape at each data point) is specified on a “per series” basis: å public Stroke getSeriesOutlineStroke(int series); Returns the outline stroke for the specified series. If getSeriesOutlineStroke() returns a nonnull value, this is returned. Otherwise, the method checks to see if a specific value has been set for the series, in which case that is returned. If all else fails, the value returned by getBaseSeriesOutlineStroke() is used. å public void setSeriesOutlineStroke(int series, Stroke stroke); Sets the outline stroke for the specified series and sends a PlotChangeEvent to all registered listeners. It is permitted to set this to null. The base stroke is used as the fallback for any series that doesn’t have a stroke explicitly defined: å public Stroke getBaseSeriesOutlineStroke(); Returns the default series outline stroke (never null). 6 These 7 These methods could be (much) better named. methods could be (much) better named. CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT 374 å public void setBaseSeriesOutlineStroke(Stroke stroke); Sets the default series outline stroke and sends a PlotChangeEvent to all registered listeners. As a convenience, you can override the outline stroke for ALL series, although in typical usage you won’t need to do this:8 å public Stroke getSeriesOutlineStroke(); Returns the override outline stroke for all series. The default value is null. å public void setSeriesOutlineStroke(Stroke stroke); Sets the outline stroke for the specified series and sends a PlotChangeEvent to all registered listeners. It is permitted to set this to null. 33.39.5 Legend Methods A range of methods control the appearance of the legend for the plot (if the chart displays a legend): å public Shape getLegendItemShape(); Returns the shape used for each legend item. The default value is Ellipse2D.Double(-4.0, -4.0, 8.0, 8.0). å public void setLegendItemShape(Shape shape); Sets the shape to use for the legend items (null) not permitted) and sends a PlotChangeEvent to all registered listeners. For correct alignment, the supplied shape should be centered on (0, 0). å public CategoryItemLabelGenerator getLabelGenerator(); Returns the generator that creates the labels for each category in the chart. å public void setLabelGenerator(CategoryItemLabelGenerator generator); Sets the generator used to create labels for each category in the chart and sends a PlotChangeEvent to all registered listeners. å public LegendItemCollection getLegendItems(); Returns a collection of legend items for the plot. By default, this method returns one item for each category—you can override the method to change this behaviour. 33.39.6 Tool Tips and URLs From version 1.0.2 onwards, this plot has support for generating tool tips (for display by the ChartPanel class, or in HTML image maps) and URLs (for HTML image maps): å public CategoryToolTipGenerator getToolTipGenerator(); [1.0.2] Returns the tool tip generator (possibly null). The default value is null. å public void setToolTipGenerator(CategoryToolTipGenerator generator); [1.0.2] Sets the tool tip generator (null is permitted) and sends a PlotChangeEvent to all registered listeners. å public CategoryURLGenerator getURLGenerator(); [1.0.2] Returns the URL generator (possibly null). The default value is null. å public void setURLGenerator(CategoryURLGenerator generator); [1.0.2] Sets the URL generator (null is permitted) and sends a PlotChangeEvent to all registered lis- teners. 33.39.7 Other Methods The draw() method is typically called by the JFreeChart class: å public void draw(Graphics2D g2, Rectangle2D area, Point2D anchor, PlotState parentState, PlotRenderingInfo info); Draws the plot within the specified area. 8 These methods could be (much) better named. CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT 33.39.8 375 Notes Some points to note: • this plot doesn’t use a separate renderer mechanism, although that would be a useful enhancement; • the plot does support negative values in the dataset, and the axis does not display any scale (both of these issues need to be addressed); • a demo (SpiderWebChartDemo1.java) is included in the JFreeChart demo collection. 33.40 ThermometerPlot 33.40.1 Overview A plot that displays a single value in a thermometer-style representation—see figure 33.20. ThermometerDemo2 °C 100 90 80 70 60 50 40 30 20 10 0 37.2 Figure 33.20: A simple thermometer chart (see ThermometerDemo2.java) You can define three sub-ranges on the thermometer scale to provide some context for the displayed value: the normal, warning and critical sub-ranges. The colour of the “mercury” in the thermometer can be configured to change for each sub-range. By default, the display range for the thermometer is fixed (using the overall range specified by the user). However, there is an option to automatically adjust the thermometer scale to display only the sub-range in which the current value falls. This allows the current data value to be displayed with more precision. 33.40.2 Constructors To create a new ThermometerPlot: å public ThermometerPlot(); Equivalent to ThermometerPlot(new DefaultValueDataset())—see the next method. å public ThermometerPlot(ValueDataset dataset); Creates a thermometer with default settings, using the supplied dataset (which may be null). CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT 33.40.3 376 The Dataset The ThermometerPlot displays a single value which it obtains from a ValueDataset. The following methods provide access to the dataset currently assigned to the plot: å public ValueDataset getDataset(); Returns the current dataset (possibly null). å public void setDataset(ValueDataset dataset); Sets the dataset for the plot (replacing any existing dataset). It is permitted to set the dataset to null. Calling this method triggers a PlotChangeEvent. When you assign a dataset to the plot, the plot registers itself as a DatasetChangeListener. Updating the dataset will result in the plot being notified, and the plot (in turn) notifies the chart. If you display your chart in a ChartPanel, this notification mechanism results in the chart being repainted whenever the dataset changes. 33.40.4 General Attributes You can control the amount of white space around the thermometer: å public RectangleInsets getPadding(); Returns the padding around the outside of the thermometer (never null). The default value is new RectangleInsets(UnitType.RELATIVE, 0.05, 0.05, 0.05, 0.05). å public void setPadding(RectangleInsets padding); Sets the padding around the thermometer and sends a PlotChangeEvent to all registered listeners. If padding is null, this method throws an IllegalArgumentException. To control the size of the thermometer bulb: å public int getBulbRadius(); [1.0.7] Returns the radius (or half-width) of the thermometer, in Java2D units. The default value is 40. å public void setBulbRadius(int r); [1.0.7] Sets the radius of the thermometer bulb, and sends a PlotChangeEvent to all registered listeners. No validation is performed on the argument—you should generally specify a value that is larger that the column radius. å public int getBulbDiameter(); [1.0.7] Returns the bulb diameter, which is always twice the value returned by getBulbRadius(). There is no setter method for this attribute. To control the width of the main column of the thermometer: å public int getColumnRadius(); [1.0.7] Returns the radius (or half-width) of the main column of the thermometer, in Java2D units. The default value is 20. å public void setColumnRadius(int r); [1.0.7] Sets the radius of the main column of the thermometer, in Java2D units, and sends a PlotChangeEvent to all registered listeners. No validation is performed on the new value—in general, you should specify a value that is less than the bulb radius. å public int getColumnDiameter(); [1.0.7] Returns the column diameter, which is always twice the value returned by getColumnRadius(). There is no setter method for this attribute. To control the gap between the two outlines drawn to represent the thermometer: å public int getGap(); [1.0.7] Returns the gap, in Java2D units, between the thermometer outlines. å public void setGap(int gap); [1.0.7] Sets the gap, in Java2D units, between the outlines used to represent the thermometer, and sends a PlotChangeEvent to all registered listeners. CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT 377 To control the colour of the thermometer outline: å public Paint getThermometerPaint(); Returns the outline paint (never null). The default value is Color.black. å public void setThermometerPaint(Paint paint); Sets the paint used to draw the outline of the thermometer and sends a PlotChangeEvent to all registered listeners. If paint is null, this method does nothing. To control the pen used to draw the thermometer outline: å public Stroke getThermometerStroke(); Returns the outline stroke (never null). The default value is new BasicStroke(1.0f). å public void setThermometerStroke(Stroke stroke); Sets the stroke used to draw the outline of the thermometer and sends a PlotChangeEvent to all registered listeners. If stroke is null, this method does nothing. 33.40.5 The Value Label The current data value can be displayed on the plot, with settings to control the location, font, colour, and number formatter. First, to control the location: å public int getValueLocation(); Returns the current value location, which is one of: • NONE (0) – no value label is displayed; • RIGHT (1) – the value label is displayed to the right of the thermometer; • LEFT (2) – the value label is displayed to the left of the thermometer; • BULB (3) – the value label is displayed inside the thermometer bulb. The default value is BULB. å public void setValueLocation(int location); Sets the location at which the current value will be displayed, and sends a PlotChangeEvent to all registered listeners. If location is not one of the values specified in getValueLocation(), this method throws an IllegalArgumentException. Note that the default value label colour is white, so if you change the location you should also change the colour so that the label remains visible. The font for the value label can be set as follows: å public Font getValueFont(); Returns the font used to display the value label, if it is visible. The default value is new Font("SansSerif", Font.BOLD, 16). å public void setValueFont(Font font); Sets the font used to display the value label, if it is visible, and sends a PlotChangeEvent to all registered listeners. If font is null, this method throws an IllegalArgumentException. Similarly, the paint for the value label can be set as follows: å public Paint getValuePaint(); Returns the paint used to display the value label, if it is visible. The default value is Color.white. å public void setValuePaint(Paint paint); Sets the paint used to display the current value and sends a PlotChangeEvent to all registered listeners. If paint is null, this method throws an IllegalArgumentException. You can set a formatter for the value label:9 å public void setValueFormat(NumberFormat formatter); Sets the formatter for the value label and sends a PlotChangeEvent to all registered listeners. 9 For whatever reason, there is currently no corresponding “getter” method. CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT 378 Near the top of the thermometer, a label can be shown with a temperature unit: å public int getUnits(); Returns a code indicating the unit type: • UNITS NONE – no unit indicator is displayed; • UNITS FAHRENHEIT – Fahrenheit units; • UNITS CELCIUS – Celcius units; • UNITS KELVIN – Kelvins. The default value is UNITS CELCIUS. å public void setUnits(int u); Sets the unit type and sends a PlotChangeEvent to all registered listeners. If u is not one of the constants specified in getUnits(), this method does nothing. å public void setUnits(String u); [DEPRECATED] Sets the unit type via a string. This method is deprecated—use setUnits(int) instead. 33.40.6 The Range Axis The ThermometerPlot has a single range axis that controls the display of data values. You can access the range axis with the following methods: å public ValueAxis getRangeAxis(); Returns the axis used by the plot. This is never null. The default value is a default NumberAxis with no label. å public void setRangeAxis(ValueAxis axis); Sets the axis for the plot and sends a PlotChangeEvent to all registered listeners. If axis is null, this method throws an IllegalArgumentException. You can change any of the visual characteristics of the axis, but you should avoid changing the axis range directly—instead, use the plot bounds methods specified in the next sub-section. The axis can be displayed at the left or right of the thermometer, or not displayed at all: å public int getAxisLocation(); Returns the axis location, which is one of: • NONE; • LEFT; • RIGHT. The default value is LEFT. å public void setAxisLocation(int location); Sets the axis location and sends a PlotChangeEvent to all registered listeners. If location is not one of the values specified in getAxisLocation, this method throws an IllegalArgumentException. The following methods don’t appear to do anything useful, and have been deprecated: å public boolean getShowValueLines(); [DEPRECATED] Returns the showValueLines flag. å public void setShowValueLines(boolean flag); [DEPRECATED] Sets a flag that doesn’t appear to do anything at all! This method has been deprecated. CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT 33.40.7 379 The Plot Bounds The plot stores lower and upper bounds for the values it can display, controlled by the methods below. Note that the axis may display some subset of the specified bounds (see the subranges in the next section): å public double getLowerBound(); Returns the lower bound for the plot. The default value is 0.0. å public void setLowerBound(double lower); Sets the lower bound for the plot and updates the current axis range. å public double getUpperBound(); Returns the upper bound for the plot. The default value is 100.0. å public void setUpperBound(double upper); Sets the upper bound for the plot and updates the current axis range. To set the overall range of values to be displayed in the thermometer: å public void setRange(double lower, double upper); Sets the lower and upper bounds for the value that can be displayed in the thermometer. If the data value is outside this range, the thermometer will be drawn as “empty” or “full”. 33.40.8 Subranges Within the plot’s bounds, you can specify three sub-ranges: • NORMAL (0) – the normal range; • WARNING (1) – the warning range; • CRITICAL (2) – the critical range. Each subrange can have a different mercury paint. To define subranges: å public void setSubrange(int subrange, double lower, double upper); Sets the lower and upper bounds for a sub-range. Use one of the constants NORMAL, WARNING or CRITICAL to indicate the sub-range. In addition to the actual bounds for the sub-ranges, you can specify display bounds for each subrange: å public void setDisplayBounds(int range, double lower, double upper); Sets the lower and upper bounds of the display range for a sub-range. The display range is usually equal to or slightly bigger than the actual bounds of the sub-range. The display bounds are only used if the thermometer axis range is automatically adjusted to display the current sub-range (see the followDataInSubranges flag in the next section). å public boolean getFollowDataInSubranges(); Returns the flag that controls whether or not the axis range automatically changes to show only the subrange within which the current data value falls. The default value is false. å public void setFollowDataInSubranges(boolean flag); If true, the thermometer range is adjusted to display only the current sub-range (which displays the value with greater precision). If false, the overall range is displayed at all times. By default, this flag is set to false. A couple of additional setter methods allow you to specify the subrange value and display bounds in one call: å public void setSubrangeInfo(int range, double low, double hi); Sets the value and display bounds for the specified subrange. å public void setSubrangeInfo(int range, double rangeLow, double rangeHigh, double displayLow, double displayHigh); Sets the value and display bounds for the specified subrange. CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT 33.40.9 380 The Mercury Colour In a real thermometer, mercury is the substance inside the thermometer that expands and contracts, rising and falling within the glass tube and indicating the current temperature. In the Thermometer plot, a tall thin rectangle is drawn in the middle of the plot to highlight the current value—the colour of this indicator is the “mercury colour”. The default mercury colour is defined with the following methods: å public Paint getMercuryPaint(); Returns the default mercury paint (never null). This is used: • for all values, if useSubrangePaint is false; • for any value outside the three defined subranges, if useSubrangePaint is true. The default value is Color.lightGray. å public void setMercuryPaint(Paint paint); Sets the default mercury paint and sends a PlotChangeEvent to all registered listeners. If paint is null, this method throws an IllegalArgumentException. A different colour can be specified for each of three user-definable subranges: å public Paint getSubrangePaint(int range); Returns the paint (never null) defined for the specified subrange. The default values are Color.green, Color.orange and Color.red. If range is not in the range 0 to 2, this method returns the default mercury paint (as returned by getMercuryPaint()). å public void setSubrangePaint(int range, Paint paint); Sets the paint for the specified subrange and sends a PlotChangeEvent to all registered listeners. If range is not in the range 0 to 2, or paint is null, this method does nothing.10 The mercury colours for subranges are only used if the useSubrangePaint flag is set to true (which is the default): å public boolean getUseSubrangePaint(); Returns the flag that controls whether or not the subrange colours are used. The default value is true. å public void setUseSubrangePaint(boolean flag); Sets the flag that controls whether or not the sub-range colours are used for the mercury in the thermometer, and sends a PlotChangeEvent to all registered listeners. 33.40.10 Other Methods The following methods are called by the JFreeChart class during chart drawing—you shouldn’t need to call them directly: å public Range getDataRange(ValueAxis axis); Returns the default range for the specified axis. This is required by the Zoomable interface. å public LegendItemCollection getLegendItems(); Always returns null. This plot displays only a single value, so it doesn’t need a default legend. å public PlotOrientation getOrientation(); Always returns PlotOrientation.VERTICAL. å public void draw(Graphics2D g2, Rectangle2D plotArea, Point2D anchor, PlotState parentState, PlotRenderingInfo state); Draws the plot within the specified area. In typical situations, you won’t normally call this method directly. 10 This is at odds with the general JFreeChart style where an exception would be thrown. CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT 33.40.11 381 Zooming This plot has in-built support zooming (a mechanism that is utilised, for example, by the ChartPanel class): å public boolean isDomainZoomable(); Returns false because this plot type has no domain axis. The domain axis zooming methods are all no-ops: å public void zoomDomainAxes(double factor, PlotRenderingInfo state, Point2D source); Does nothing—this plot has no domain axis. å public void zoomDomainAxes(double factor, PlotRenderingInfo state, Point2D source, boolean useAnchor); [1.0.7] As above. å public void zoomDomainAxes(double lowerPercent, double upperPercent, PlotRenderingInfo state, Point2D source); As above. The range axis on the plot is zoomable: å public boolean isRangeZoomable(); Returns true to indicate that the range axis is zoomable for this plot type. The following zooming methods are defined: å public void zoomRangeAxes(double factor, PlotRenderingInfo state, Point2D source); Equivalent to zoomRangeAxis(factor, state, source, false)—see next method. å public void zoomRangeAxes(double factor, PlotRenderingInfo state, Point2D source, boolean useAnchor); [1.0.7] Scales the length of the range axis by the specified factor. If useAnchor is true, the axis bounds are scaled about the source point, otherwise the scaling occurs around the central point of the current axis range. å public void zoomRangeAxes(double lowerPercent, double upperPercent, PlotRenderingInfo state, Point2D source); Updates the lower and upper bounds of the axis range to the specified points (expressed as a point along the axis in percentage terms). 33.40.12 Equals, Cloning and Serialization This class overrides the equals() method: å public boolean equals(Object obj); Tests this plot for equality with an arbitrary object. Note that the dataset is ignored for the equality test. If obj is null, this method returns false. Instances of this class are Cloneable and Serializable. 33.40.13 Notes Some points to note: • the ThermometerPlot class was originally contributed by Bryan Scott from the Australian Antarctic Division. • the JThermometer class provides a simple (but incomplete) Javabean wrapper for this class. • a demo (ThermometerDemo1.java) is included in the JFreeChart Demo Collection. See Also ValueDataset. CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT 33.41 ValueAxisPlot 33.41.1 Overview 382 This interface should be implemented by plots that use the ValueAxis class (or its subclasses). This provides an entry point for the axis to query the plot to find out the range of data values that will be plotted against the axis (bear in mind that more than one dataset from the plot may be mapped to a particular axis). 33.41.2 Methods This interface defines a single method: å public Range getDataRange(ValueAxis axis); Returns the range that is required to display all data values that are plotted against the specified axis. 33.41.3 Notes This interface is implemented by CategoryPlot, FastScatterPlot, PolarPlot, ThermometerPlot and XYPlot. 33.42 ValueMarker 33.42.1 Overview A value marker is used to indicate a constant value against the domain or range axis for a CategoryPlot or an XYPlot. This class extends the Marker class. 33.42.2 Usage You can add a marker to an XYPlot using the addDomainMarker() or addRangeMarker() methods. Similarly, you can add a range marker to a CategoryPlot using the addRangeMarker() method. There is a demo application (MarkerDemo1.java) included in the JFreeChart demo collection that illustrates the use of this class. 33.42.3 Constructors The following constructors are defined: å public ValueMarker(double value); Creates a new instance with the specified value and default values for all other attributes. å public ValueMarker(double value, Paint paint, Stroke stroke); Creates a new instance with the specified value, paint and stroke. å public ValueMarker(double value, Paint paint, Stroke stroke, Paint outlinePaint, Stroke outlineStroke, float alpha); Creates a new instance with the specified value and attributes. 33.42.4 Methods In addition to the methods inherited from Marker, this class defines: å public double getValue(); Returns the current value for the marker. å public void setValue(double value); [1.0.3] Sets the value for the marker and sends a MarkerChangeEvent to all registered listeners. CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT 33.42.5 383 Equals, Cloning and Serialization This class overrides the equals() method: å public boolean equals(Object obj); Tests this instance for equality with an arbitrary object (which may be null. Instances of this class are cloneable and serializable. 33.42.6 Notes Some points to note: • the marker is most often drawn as a line, but in a chart with a 3D-effect the marker will be drawn as a polygon—for this reason, the marker has both paint and outlinePaint attributes, and stroke and outlineStroke attributes; See Also IntervalMarker. 33.43 WaferMapPlot 33.43.1 Overview A plot for generating wafer map charts. 33.43.2 Draw Method The following method is called by the JFreeChart class during chart drawing: å public void draw(Graphics2D g2, Rectangle2D plotArea, Point2D anchor, PlotState parentState, PlotRenderingInfo state); Draws the plot within the specified area. In typical situations, you won’t normally call this method directly. See Also WaferMapRenderer. 33.44 XYPlot 33.44.1 Overview Draws a visual representation of data from an XYDataset, where the domain axis measures the x-values and the range axis measures the y-values. The type of plot is typically displayed using a vertical orientation, but it is possible to change to a horizontal orientation which can be useful for certain applications. 33.44.2 Layout Axes are laid out at the left and bottom of the drawing area. The space allocated for the axes is determined automatically. The following diagram shows how this area is divided: Determining the dimensions of these regions is an awkward problem. The plot area can be resized arbitrarily, but the vertical axis and horizontal axis sizes are more difficult. Note that the height of the vertical axis is related to the height of the horizontal axis, and, likewise, the width of the vertical axis is related to the width of the horizontal axis. This results in a “chicken and egg” problem, because changing the width of an axis can affect its height (especially if the tick units change with the resize) and changing its height can affect the width (for the same reason). CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT 384 Figure 33.21: The plot regions 33.44.3 Constructors To create a default instance: å public XYPlot(); Creates a new plot with no dataset, no axes and no renderer. Take care to specify these attributes before using the plot, otherwise JFreeChart may throw a NullPointerException. To create a plot with a specific renderer: å public XYPlot(XYDataset dataset, ValueAxis domainAxis, ValueAxis rangeAxis, XYItemRenderer renderer); Creates a new XYPlot instance with the specified dataset, axes and renderer. Any of these arguments can be null, but in that case you should take care to specify the missing attributes before using the plot, otherwise JFreeChart may throw a NullPointerException. 33.44.4 Datasets and Renderers An XYPlot can have zero, one or many datasets and each dataset is usually associated with a renderer (the object that is responsible for drawing the visual representation of each item in a dataset). A dataset is an instance of any class that implements the XYDataset interface and a renderer is an instance of any class that implements the XYItemRenderer interface. To get/set a dataset: å public XYDataset getDataset(); Equivalent to getDataset(0)—see below. This is a convenience method for developers that typically work with a single dataset. å public XYDataset getDataset(int index); Returns the dataset at the specified index (possibly null). å public void setDataset(XYDataset dataset); Equivalent to setDataset(0, dataset)—see below. This is a convenience method for developers that typically work with a single dataset. å public void setDataset(int index, XYDataset dataset); Assigns a dataset to the plot at the given index. The new dataset replaces any existing dataset at the specified index. It is permitted to set a dataset to null (in that case, no data will be displayed on the chart). For non-null datasets, this plot will be registered with the dataset to receive notification of changes to the dataset. To get/set a renderer: å public XYItemRenderer getRenderer(int index); Returns the renderer at the specified index (possibly null). å public void setRenderer(int index, XYItemRenderer renderer); Sets the renderer at the specified index and sends a PlotChangeEvent to all registered listeners. It is permitted to set any renderer to null. CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT 385 A number of renderer implementations are available (and you are free to develop your own, of course): • CandlestickRenderer; • ClusteredXYBarRenderer; • HighLowRenderer; • StandardXYItemRenderer; • XYAreaRenderer; • XYBarRenderer; • XYBubbleRenderer; • XYDifferenceRenderer; The items in each dataset are, by default, plotted against the primary axes. You can change that by adding a mapping between a dataset and the axes it should be plotted against—see section 33.44.10. 33.44.5 Dataset Rendering Order When a plot has multiple datasets and renderers, the order in which the datasets are rendered has an impact on the appearance of the chart. You can control the rendering order using the following methods: å public DatasetRenderingOrder getDatasetRenderingOrder(); Returns the current dataset rendering order (never null). å public void setDatasetRenderingOrder(DatasetRenderingOrder order); Sets the dataset rendering order and sends a PlotChangeEvent to all registered listeners. It is not permitted to set the rendering order to null. By default, datasets will be rendered in reverse order so that the “primary” dataset appears to be “on top” of the other datasets. 33.44.6 Series Rendering Order The series within each dataset are, by default, rendered in reverse order (so that the first series in each dataset appears in front of all the other series in that dataset). You can control this using the following methods: å public SeriesRenderingOrder getSeriesRenderingOrder(); Returns the current series rendering order (never null). The default value is SeriesRenderingOrder.REVERSE. å public void setSeriesRenderingOrder(SeriesRenderingOrder order); Sets the series rendering order and sends a PlotChangeEvent to all registered listeners. This method throws an IllegalArgumentException if order is null. 33.44.7 Axes Most plots will have a single domain axis (or x-axis) and a single range axis (or y-axis). To get/set the domain axis: å public ValueAxis getDomainAxis(); Returns the domain axis with index 0. å public void setDomainAxis(ValueAxis axis); Sets the domain axis with index 0 and sends a PlotChangeEvent to all registered listeners. CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT 386 To get/set the range axis: å public ValueAxis getRangeAxis(); Returns the range axis with index 0. å public void setRangeAxis(ValueAxis axis); Sets the range axis with index 0 and sends a PlotChangeEvent to all registered listeners. Multiple domain and/or range axes are also supported—see Chapter 13 for details. å public ValueAxis getDomainAxis(int index); Returns the domain axis at the specified index. This method can return null. å public void setDomainAxis(int index, ValueAxis axis); Equivalent to setDomainAxis(index, axis, true)—see below. å public void setDomainAxis(int index, ValueAxis axis, boolean notify); Sets the domain axis at the specified index (replacing any axis already there) and, if requested, sends a PlotChangeEvent to all registered listeners. å public void setDomainAxes(ValueAxis[] axes); This is a convenience method that calls setDomainAxis(int, ValueAxis) for each axis in the array, firing a single PlotChangeEvent once all the axes have been added. An exception is thrown if axes is null. å public ValueAxis getRangeAxis(int index); Returns the range axis at the specified index. This method can return null. å public void setRangeAxis(int index, ValueAxis axis); Equivalent to setRangeAxis(index, axis, true)—see below. å public void setRangeAxis(int index, ValueAxis axis, boolean notify); Sets the range axis at the specified index (replacing any axis already there) and, if requested, sends a PlotChangeEvent to all registered listeners. å public void setRangeAxes(ValueAxis[] axes); This is a convenience method that calls setRangeAxis(int, ValueAxis) for each axis in the array, firing a single PlotChangeEvent once all the axes have been added. An exception is thrown if axes is null. 33.44.8 Location of Axes The plot’s axes can appear at the top, bottom, left or right of the plot area. The location for an axis is specified using the AxisLocation class, which combines two possible locations within each option—which one is actually used depends on the orientation (horizontal or vertical) of the plot. For “vertical” plots (the usual default), the domain axis will appear at the top or bottom of the plot area, and the range axis will appear at the left or right of the plot area. For “horizontal” plots, the domain axis will appear at the left or right of the plot area, and the range axis will appear at the top or bottom of the plot area. To set the location for the domain axis: å public void setDomainAxisLocation(AxisLocation location); Sets the location for the domain axis and sends a PlotChangeEvent to all registered listeners. Similarly, to set the location for the range axis: å public void setRangeAxisLocation(AxisLocation location); Sets the range axis location and sends a PlotChangeEvent to all registered listeners. For example, to display the range axis on the right side of a chart: plot.setRangeAxisLocation(AxisLocation.BOTTOM OR RIGHT); This assumes the plot orientation is vertical, if it changes to horizontal the axis will be displayed at the bottom of the chart. CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT 33.44.9 387 Axis Offsets By default, the axes are drawn “flush” against the edge of the plot’s data area. It is possible to specify an amount by which the plot’s axes are offset fromthe data area using the following methods: å public RectangleInsets getAxisOffset(); Returns the gap between the plot’s data area and the axes. å public void setAxisOffset(RectangleInsets offset); Sets the gap between the plot’s data area and the axes. You cannot set this to null—for no gap, use RectangleInsets.ZERO INSETS. 33.44.10 Mapping Datasets to Axes For a plot with multiple datasets, renderers and axes, you need to specify which axes should be used for each dataset. By default, the items in a dataset will be plotted against the “primary” domain and range axes—that is, the axes at index 0. If you want a dataset plotted against a different axis, you need to “map” the dataset to the axis. There are separate methods to map a dataset to a domain axis and a range axis: å public void mapDatasetToDomainAxis(int index, int axisIndex); Maps a dataset to a domain axis. You need to take care that the dataset and axis both exist when you create a mapping entry. å public void mapDatasetToRangeAxis(int index, int axisIndex); Maps a dataset to a range axis. You need to take care that the dataset and axis both exist when you create a mapping entry. To find the domain and/or range axis that a dataset is currently mapped to: å public ValueAxis getDomainAxisForDataset(int index) Returns the domain axis that the specified dataset is currently mapped to. å public ValueAxis getRangeAxisForDataset(int index); Returns the range axis that the specified dataset is currently mapped to. 33.44.11 Gridlines The XYPlot class provides support for drawing gridlines against the primary domain axis and the primary range axis (gridlines for other axes are not currently supported).11 For each axis, there is a flag that controls whether or not the gridlines are visible. For visible gridlines, you can customise the line style (Stroke) and color (Paint). For example, to change the grid to display solid black lines: XYPlot plot = (XYPlot) chart.getPlot(); plot.setDomainGridlineStroke(new BasicStroke(0.5f)); plot.setDomainGridlinePaint(Color.black); plot.setRangeGridlineStroke(new BasicStroke(0.5f)); plot.setRangeGridlinePaint(Color.black); If you prefer to have no gridlines at all, you can turn them off: XYPlot plot = (XYPlot) chart.getPlot(); plot.setDomainGridlinesVisible(false); plot.setRangeGridlinesVisible(false); The settings for the domain axis gridlines and the range axis gridlines are independent of one another. The following methods control the domain axis gridlines: å public boolean isDomainGridlinesVisible(); Returns true if the plot should draw gridlines for the primary domain axis, and false otherwise. 11 There is a good argument for moving this feature into the axis classes, but that hasn’t been done yet. CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT 388 å public void setDomainGridlinesVisible(boolean visible); Sets the flag that controls whether or not the plot should draw gridlines for the primary domain axis, and sends a PlotChangeEvent to all registered listeners. å public Stroke getDomainGridlineStroke(); Returns the stroke used to draw the gridlines for the primary domain axis (the default is a thin dashed line). This method never returns null. å public void setDomainGridlineStroke(Stroke stroke); Sets the stroke used to draw the gridlines for the primary domain axis, and sends a PlotChangeEvent to all registered listeners. This method throws an IllegalArgumentException if stroke is null. å public Paint getDomainGridlinePaint(); Returns the paint used to draw the gridlines for the primary domain axis (the default is Color.lightGray). This method never returns null. å public void setDomainGridlinePaint(Paint paint); Sets the paint used to draw the gridlines for the primary domain axis, and sends a PlotChangeEvent to all registered listeners. This method throws an IllegalArgumentException if paint is null. Similarly, the following methods control the range axis gridlines: å public boolean isRangeGridlinesVisible(); Returns true if the plot should draw gridlines for the primary range axis, and false otherwise. å public void setRangeGridlinesVisible(boolean visible); Sets the flag that controls whether or not the plot should draw gridlines for the primary range axis, and sends a PlotChangeEvent to all registered listeners. å public Stroke getRangeGridlineStroke(); Returns the stroke used to draw the gridlines for the primary range axis (the default is a thin dashed line). This method never returns null. å public void setRangeGridlineStroke(Stroke stroke); Sets the stroke used to draw the gridlines for the primary range axis, and sends a PlotChangeEvent to all registered listeners. This method throws an IllegalArgumentException if stroke is null. å public Paint getRangeGridlinePaint(); Returns the paint used to draw the gridlines for the primary range axis (the default is Color.lightGray). This method never returns null. å public void setRangeGridlinePaint(Paint paint); Sets the paint used to draw the gridlines for the primary range axis, and sends a PlotChangeEvent to all registered listeners. This method throws an IllegalArgumentException if paint is null. 33.44.12 Grid Bands The XYPlot class can color alternate bands between the tick marks on the plot’s axes. To control this facility for the (primary) domain axis: å public Paint getDomainTickBandPaint(); Returns the paint used to fill alternate bands between the tick values on the primary domain axis. The default value is null (no bands are filled). å public void setDomainTickBandPaint(Paint paint); Sets the paint used to fill alternate bands between the tick values on the domain axis, and sends a PlotChangeEvent to all registered listeners. If paint is null, no bands will be filled. A similar feature is supported for the (primary) range axis: å public Paint getRangeTickBandPaint(); Returns the paint used to fill alternate bands between the tick values on the primary range axis. The default value is null (no bands are filled). å public void setRangeTickBandPaint(Paint paint); Sets the paint used to fill alternate bands between the tick values on the range axis, and sends a PlotChangeEvent to all registered listeners. If paint is null, no bands will be filled. A demo (GridBandDemo1.java) is included in the JFreeChart demo collection. CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT 33.44.13 389 Zero Base Line A facility is provided where the plot can draw a base line against the range axis at the zero value. This is not visible by default, but you can switch it on and control the stroke and paint using the following methods: å public boolean isRangeZeroBaselineVisible(); Returns the flag that controls whether or not the plot draws a base line against the zero value of the range axis. The default value is false. å public void setRangeZeroBaselineVisible(boolean visible); Sets the flag that controls whether or not the plot draws a base line against the zero value of the range axis. A PlotChangeEvent is sent to all registered listeners. å public Stroke getRangeZeroBaselineStroke(); Returns the stroke (never null) used to draw the zero baseline, if it is visible. The default is BasicStroke(0.5f). å public void setRangeZeroBaselineStroke(Stroke stroke); Sets the stroke used to draw the zero baseline, and sends a PlotChangeEvent to all registered listeners. This method throws an IllegalArgumentException if stroke is null. å public Paint getRangeZeroBaselinePaint(); Returns the paint (never null) used to draw the zero baseline, if it is visible. The default is Color.black. å public void setRangeZeroBaselinePaint(Paint paint); Sets the paint used to draw the zero baseline and sends a PlotChangeEvent to all registered listeners. 33.44.14 Crosshairs The XYPlot class supports the display of crosshairs for the primary domain and range axes.12 Use the following methods: å public boolean isDomainCrosshairVisible(); Returns true if the crosshair for the primary domain axis is visible, and false otherwise. å public void setDomainCrosshairVisible(boolean flag); Sets the visibility flag for the crosshair linked to the primary domain axis, and sends a PlotChangeEvent to all registered listeners. å public boolean isDomainCrosshairLockedOnData(); Returns true if the crosshair automatically “snaps” to the nearest data value, and false oth- erwise. å public void setDomainCrosshairLockedOnData(boolean flag); Sets the flag that determines whether or not the crosshair automatically snaps to the nearest data value. If the flag value changes, this method sends a PlotChangeEvent to all registered listeners. å public double getDomainCrosshairValue(); Returns the value of the crosshair for the domain axis. Note that this value is recalculated as the chart is repainted, so you should only rely on this value if you know that the chart has finished painting. In particular, this method will return the old value if you call it from within a mouse click event handler. You can use a ChartProgressListener to determine when chart painting has completed—see CrosshairDemo1.java for an example. å public void setDomainCrosshairValue(double value); Sets the crosshair value for the primary domain axis and sends a PlotChangeEvent to all registered listeners. å public void setDomainCrosshairValue(double value, boolean notify); Sets the crosshair value for the primary domain axis and if requested sends a PlotChangeEvent to all registered listeners (but only if the crosshairs are visible). 12 Unfortunately, it is not possible to display crosshairs for other axes at this time. CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT 390 å public Stroke getDomainCrosshairStroke(); Returns the domain crosshair stroke (never null). The default value is a thin dashed line. å public void setDomainCrosshairStroke(Stroke stroke); Sets the stroke used to display the crosshair for the primary domain axis (null is not permitted), and sends a PlotChangeEvent to all registered listeners. å public Paint getDomainCrosshairPaint(); Returns the paint (never null) used to draw the crosshair for the primary domain axis. The default value is Color.blue. å public void setDomainCrosshairPaint(Paint paint); Sets the paint used to draw the crosshair for the primary domain axis and sends a PlotChangeEvent to all registered listeners. Similarly for the crosshair related to the primary range axis: å public boolean isRangeCrosshairVisible(); Returns true if the crosshair for the primary range axis is visible, and false otherwise. å public void setRangeCrosshairVisible(boolean flag); Sets the visibility flag for the crosshair linked to the primary range axis, and sends a PlotChangeEvent to all registered listeners. å public boolean isRangeCrosshairLockedOnData(); Returns true if the crosshair automatically “snaps” to the nearest data value, and false oth- erwise. å public void setRangeCrosshairLockedOnData(boolean flag); Sets the flag that determines whether or not the crosshair automatically snaps to the nearest data value. If the flag value changes, this method sends a PlotChangeEvent to all registered listeners. å public double getRangeCrosshairValue(); Returns the value of the crosshair for the range axis. Note that this value is recalculated as the chart is repainted, so you should only rely on this value if you know that the chart has finished painting. In particular, this method will return the old value if you call it from within a mouse click event handler. You can use a ChartProgressListener to determine when chart painting has completed—see CrosshairDemo1.java for an example. å public void setRangeCrosshairValue(double value); Sets the crosshair value for the primary range axis and sends a PlotChangeEvent to all registered listeners. å public void setRangeCrosshairValue(double value, boolean notify); Sets the crosshair value for the primary range axis and if requested sends a PlotChangeEvent to all registered listeners (but only if the crosshairs are visible). å public Stroke getRangeCrosshairStroke(); Returns the range crosshair stroke (never null). The default value is a thin dashed line. å public void setRangeCrosshairStroke(Stroke stroke); Sets the stroke used to display the crosshair for the primary range axis (null is not permitted), and sends a PlotChangeEvent to all registered listeners. å public Paint getRangeCrosshairPaint(); Returns the paint (never null) used to draw the crosshair for the primary range axis. The default value is Color.blue. å public void setRangeCrosshairPaint(Paint paint); Sets the paint used to draw the crosshair for the primary range axis and sends a PlotChangeEvent to all registered listeners. CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT 33.44.15 391 Markers Markers are used to highlight particular values along the domain axis or the range axis for a plot. Typically, a marker will be represented by a solid line perpendicular to the axis against which it is measured, although custom renderers can alter this default behaviour. To add a marker along the domain axis: å public void addDomainMarker(Marker marker); Adds a marker for the domain axis. This is usually represented as a vertical line on the plot (assuming a vertical orientation for the plot). To add a marker along the range axis: å public void addRangeMarker(Marker marker); Adds a marker for the range axis. This is usually represented as a horizontal line on the plot (assuming a vertical orientation for the plot). To clear all domain markers: å public void clearDomainMarkers(); Clears all the domain markers. Likewise, to clear all range markers: å public void clearRangeMarkers(); Clears all the range markers. 33.44.16 Annotations You can add annotations to a plot to highlight particular data items. For example, to add the text “Hello World!” to a plot: XYPlot plot = (XYPlot) chart.getPlot(); XYAnnotation annotation = new XYTextAnnotation("Hello World!", 10.0, 25.0); plot.addAnnotation(annotation); Annotations added directly to the plot are drawn relative to the plot’s primary axes. If you need an annotation drawn against different axes, you should assign the annotation to the appropriate XYItemRenderer (see section 37.23.17). The following methods are used to control the annotations for a plot: å public void addAnnotation(XYAnnotation annotation); Adds an annotation to the plot and sends a PlotChangeEvent to all registered listeners. If annotation is null, this method throws an IllegalArgumentException. During rendering the annotations are drawn last, so they always overwrite any other items drawn by the plot. å public boolean removeAnnotation(XYAnnotation annotation); Removes a specific annotation from the plot and, if the annotation is successfully removed, sends a PlotChangeEvent to all registered listeners. If annotation is null, this method throws an IllegalArgumentException. This method returns true if annotation was removed, and false otherwise (this usually indicates that annotation was never assigned to the plot in the first place). å public List getAnnotations(); [1.0.1] Returns a list of the annotations that have been assigned to the plot. The returned list may be empty, but never null. Modifying the returned list has no effect on the plot. å public void clearAnnotations(); Clears all annotations from the plot and sends a PlotChangeEvent to all registered listeners. CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT 33.44.17 392 Zooming To support the zooming operations implemented in the ChartPanel class, this plot implements the Zoomable interface: å public boolean isDomainZoomable(); Returns true to indicate that the domain axis (or axes) are, in fact, zoomable. å public boolean isRangeZoomable(); Returns true to indicate that the range axis (or axes) are, in fact, zoomable. å public PlotOrientation getOrientation(); Returns the orientation of the plot. The ChartPanel class uses this to determine whether a “horizontal” zoom maps to the domain or range axis, and likewise for a “vertical” zoom. å public void zoomDomainAxes(double factor, PlotRenderingInfo state, Point2D source); Calls resizeRange(double) for each domain axis in the plot. Note that the state and source arguments are currently ignored. å public void zoomDomainAxes(double lowerPercent, double upperPercent, PlotRenderingInfo state, Point2D source); Calls zoom(lowerPercent, upperPercent) for each domain axis in the plot. Note that the state and source arguments are currently ignored. å public void zoomRangeAxes(double factor, PlotRenderingInfo state, Point2D source); Calls resizeRange(double) for each range axis in the plot. Note that the state and source arguments are currently ignored. å public void zoomRangeAxes(double lowerPercent, double upperPercent, PlotRenderingInfo state, Point2D source); Calls zoom(lowerPercent, upperPercent) for each range axis in the plot. Note that the state and source arguments are currently ignored. 33.44.18 Quadrants The XYPlot class provides an optional facility to specify a background color for each quadrant in the plot. å public Point2D getQuadrantOrigin(); Returns the quadrant origin, in data space. By default, the origin is (0, 0). å public void setQuadrantOrigin(Point2D origin); Sets the quadrant origin, in data space, and sends a PlotChangeEvent to all registered listeners. This method throws an IllegalArgumentException if origin is null. å public Paint getQuadrantPaint(int index); Returns the paint for the specified quadrant (possibly null). This method throws an IllegalArgumentException if index is not in the range 0 to 3. å public void setQuadrantPaint(int index, Paint paint); Sets the paint for the specified quadrant and sends a PlotChangeEvent to all registered listeners. There is a demo (PlotOrientationDemo1.java) in the JFreeChart demo collection that shows this facility in use. 33.44.19 Other Methods Other methods defined by XYPlot include: å public int getWeight(); Returns the weight for a plot which is used to determine how much space to allocate to the plot when it is being used as a subplot within a combined plot. å public void setWeight(int weight); Sets the weight for the plot and sends a PlotChangeEvent to all registered listeners. CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT 393 The following methods are used by the combined plot classes to align the axes of subplots: å public void setFixedDomainAxisSpace(AxisSpace space); Equivalent to setFixedDomainAxisSpace(space, true)—see the next method. å public void setFixedDomainAxisSpace(AxisSpace space, boolean notify); [1.0.9] Sets the fixed amount of space to reserve for the domain axes on this plot and, if requested, sends a PlotChangeEvent to all registered listeners. å public void setFixedRangeAxisSpace(AxisSpace space); Equivalent to setFixedRangeAxisSpace(space, true)—see the next method. å public void setFixedRangeAxisSpace(AxisSpace space, boolean notify); [1.0.9] Sets the fixed amount of space to reserve for the range axes on this plot and, if requested, sends a PlotChangeEvent to all registered listeners. 33.44.20 Notes It is possible to display time series data with XYPlot by employing a DateAxis in place of the usual NumberAxis. In this case, the x-values are interpreted as “milliseconds since 1-Jan-1970” as used in java.util.Date. See Also Plot, XYItemRenderer, CombinedDomainXYPlot, CombinedRangeXYPlot. 33.45 Zoomable 33.45.1 Overview This interface is designed to allow a caller (in particular, the ChartPanel class) to determine the zooming functions supported by a plot, and to invoke those zooming operations as required. This interface is implemented by the following plots: • CategoryPlot; • CombinedDomainCategoryPlot; • CombinedDomainXYPlot; • CombinedRangeCategoryPlot; • CombinedRangeXYPlot; • FastScatterPlot; • PolarPlot; • ThermometerPlot; • XYPlot. If a plot doesn’t implement this interface, the ChartPanel will assume that no zooming is possible. CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT 33.45.2 394 Interface Methods To determine whether or not the domain and range axes are zoomable: å public boolean isDomainZoomable(); Returns true if the plot’s domain (x-axis) is zoomable, and false otherwise. å public boolean isRangeZoomable(); Returns true if the plot’s range (y-axis) is zoomable, and false otherwise. To determine the orientation of the plot: å public PlotOrientation getOrientation(); Returns the plot’s orientation. To invoke zooming operations: å public void zoomDomainAxes(double factor, PlotRenderingInfo state, Point2D source); Performs a zoom operation on the plot’s domain axes. å public void zoomDomainAxes(double lowerPercent, double upperPercent, PlotRenderingInfo state, Point2D source); Performs a zoom operation on the plot’s domain axes. å public void zoomRangeAxes(double factor, PlotRenderingInfo state, Point2D source); Performs a zoom operation on the plot’s range axes. å public void zoomRangeAxes(double lowerPercent, double upperPercent, PlotRenderingInfo state, Point2D source); Performs a zoom operation on the plot’s range axes. Two new methods have been added to the interface in JFreeChart version 1.0.7—these allow the caller to specify whether the zooming anchor point is the supplied source point, or just the centre of the plot: å public void zoomDomainAxes(double factor, PlotRenderingInfo state, Point2D source, boolean useAnchor); [1.0.7] Performs a zoom operation on the plot’s domain axes. å public void zoomRangeAxes(double factor, PlotRenderingInfo state, Point2D source, boolean useAnchor); [1.0.7] Performs a zoom operation on the plot’s range axes. See Also ChartPanel. Chapter 34 Package: org.jfree.chart.plot.dial 34.1 Overview The org.jfree.chart.plot.dial package (new in version 1.0.7) contains a collection of classes dedicated to creating dial plots—see figure 34.1 for an example. The main class in this package is the DialPlot class. Demo Dial 1 10.0 0.0 20.0 -10.0 30.0 -20.0 40.0 18.0 -30.0 -40.0 50.0 60.0 Temperature Figure 34.1: Dial Plot 34.2 AbstractDialLayer 34.2.1 Overview A base class for creating the layers that make up a dial. This class provides an event notification mechanism so that changes to a layer can be communicated to the plot that the layer belongs to. Subclasses include: • ArcDialFrame; • DialBackground; • DialCap; 395 CHAPTER 34. PACKAGE: ORG.JFREE.CHART.PLOT.DIAL 396 • DialPointer; • DialTextAnnotation; • DialValueIndicator; • SimpleDialFrame; • StandardDialRange. • StandardDialScale. This class implements the DialLayer interface. 34.2.2 Constructors To create a new instance: å protected AbstractDialLayer(); Creates a new instance. Note that this constructor is protected—it can only be called by subclasses. 34.2.3 Attributes Every layer has a flag that controls the visibility of the layer: å public boolean isVisible(); Returns true if the layer is currently visible, and false otherwise. The default value is true. å public void setVisible(boolean visible); Sets the flag that controls whether or not the layer is visible, and sends a DialLayerChangeEvent to all registered listeners. 34.2.4 Event Notification A typical dial plot is constructed from a number of layers. Whenever a layer is modified, the plot needs to detect this so it can pass on a PlotChangeEvent to its listeners. å public void addChangeListener(DialLayerChangeListener listener); Registers a listener so that it receives change events from this layer. å public void removeChangeListener(DialLayerChangeListener listener); Deregisters a listener so that it no longer receives change events from this layer. To determine if a listener is currently registered with a layer: å public boolean hasListener(EventListener listener); Returns true if the specified listener is registered with the layer, and false otherwise. å protected void notifyListeners(DialLayerChangeEvent event); Sends the specified event to all registered listeners. 34.2.5 Equals, Cloning and Serialization This class overrides the equals() method: å public boolean equals(Object obj); Tests this layer for equality with an arbitrary object. This method returns true if and only if: • obj is an instance of AbstractDialLayer; • the visible flag is the same for both instances. Instances of this class are Cloneable and Serializable. CHAPTER 34. PACKAGE: ORG.JFREE.CHART.PLOT.DIAL 34.3 ArcDialFrame 34.3.1 Overview 397 This frame is an alternative to the SimpleDialFrame class. Rather than a circular frame, it draws an arc-like frame. 34.3.2 Constructors To create a new instance: å public ArcDialFrame(); Equivalent to ArcDialFrame(0, 180.0)—see the next constructor. å public ArcDialFrame(double startAngle, double extent); Creates a new frame spanning the specified arc. The startAngle and extent are specified in degrees, using the same encoding as Java’s Arc2D class. 34.3.3 General Attributes The start angle defines where the arc for the frame begins: å public double getStartAngle(); Returns the start angle, in degrees. The initial value is specified in the constructor. å public void setStartAngle(double angle); Sets the start angle and sends a DialLayerChangeEvent to all registered listeners. The extent is the angle through which the arc extends: å public double getExtent(); Returns the extent, in degrees. The initial value is specified in the constructor. å public void setExtent(double extent); Sets the extent, in degrees, and sends a DialLayerChangeEvent to all registered listeners. The background paint determines the colour used to fill the area between the frame outlines: å public Paint getBackgroundPaint(); Returns the background paint (never null). The default value is Color.gray. å public void setBackgroundPaint(Paint paint); Sets the background paint for the frame and sends a DialLayerChangeEvent to all registered listeners. If paint is null, this method throws an IllegalArgumentException. The foreground paint determines the colour used to draw the frame outline: å public Paint getForegroundPaint(); Returns the foreground paint (never null). The default value is Color(100, 100, 150). å public void setForegroundPaint(Paint paint); Sets the foreground paint for the frame and sends a DialLayerChangeEvent to all registered listeners. If paint is null, this method throws an IllegalArgumentException. To control the stroke used to draw the frame outline: å public Stroke getStroke(); Returns the stroke (never null) used to draw the frame outline. The default value is BasicStroke(2.0f). å public void setStroke(Stroke stroke); Sets the stroke used to draw the frame outline and sends a DialLayerChangeEvent to all registered listeners. If stroke is null, this method throws an IllegalArgumentException. To control the radius of the inner edge of the frame: å public double getInnerRadius(); Returns the inner radius, expressed as a percentage within the dial’s framing rectangle. The default value is 0.25. CHAPTER 34. PACKAGE: ORG.JFREE.CHART.PLOT.DIAL 398 å public void setInnerRadius(double radius); Sets the inner radius and sends a DialLayerChangeEvent to all registered listeners. To control the radius of the outer edge of the frame: å public double getOuterRadius(); Returns the outer radius, expressed as a percentage within the dial’s framing rectangle. The default value is 0.75. å public void setOuterRadius(double radius); Sets the outer radius and sends a DialLayerChangeEvent to all registered listeners. 34.3.4 Other Methods The following methods are typically called by the DialPlot class—you shouldn’t need to call them directly: å public Shape getWindow(Rectangle2D frame); Returns the shape for the frame’s window. Other layers in the DialPlot may be clipped to this window shape. å public boolean isClippedToWindow(); Returns false to indicate that this layer should not be clipped to the frame’s window. å public void draw(Graphics2D g2, DialPlot plot, Rectangle2D frame, Rectangle2D view); Draws the frame. 34.3.5 Equals, Cloning and Serialization This class overrides the equals() method: å public boolean equals(Object obj); Tests this frame for equality with an arbitrary object. Instances of this class are Cloneable and Serializable. See Also SimpleDialFrame. 34.4 DialBackground 34.4.1 Overview A dial plot layer that fills the background with a single colour or a gradient. 34.4.2 Constructors To create a new instance: å public DialBackground(); Equivalent to DialBackground(Color.white)—see the next constructor. å public DialBackground(Paint paint); Creates a new dial background layer with the specified colour. If paint is null, this constructor throws an IllegalArgumentException. CHAPTER 34. PACKAGE: ORG.JFREE.CHART.PLOT.DIAL 34.4.3 399 General Attributes The main attribute for this class is the background colour: å public Paint getPaint(); Returns the paint used to fill the background. The default value is specified in the constructor. å public void setPaint(Paint paint); Sets the paint used to fill the background, and sends a DialLayerChangeEvent to all registered listeners. If paint is null, this method throws an IllegalArgumentException. If the background paint is an instance of GradientPaint, a transformer is used to dynamically modify the gradient paint coordinates to match the size and shape of the dial plot: å public GradientPaintTransformer getGradientPaintTransformer(); Returns the current transformer (never null). The default value is an instance of StandardGradientPaintTransformer. å public void setGradientPaintTransformer(GradientPaintTransformer t); Sets the transformer used for GradientPaint instances, and sends a DialLayerChangeEvent to all registered listeners. If t is null, this method throws an IllegalArgumentException. 34.4.4 Other Methods The plot will call the following method to determine whether the layer is clipped to the dial frame window: å public boolean isClippedToWindow(); Returns true, to indicate that this layer is clipped to the dial frame window. The plot will call the following method to draw the layer: å public void draw(Graphics2D g2, DialPlot plot, Rectangle2D frame, Rectangle2D view); Draws the background within the specified frame and view rectangles. 34.4.5 Equals, Cloning and Serialization This class overrides the equals() method: å public boolean equals(Object obj); Tests this instance for equality with an arbitrary object. Instances of this class are cloneable (PublicCloneable) and serializable. 34.4.6 Notes Some points to note: • this class extends AbstractDialLayer; • use the setBackground() method in the DialPlot class to add an instance of this class to a plot. 34.5 DialCap 34.5.1 Overview A small circular graphic that represents the “cap” over the rotation point of a dial’s needle. 34.5.2 Constructors To create a new instance: å public DialCap(); Creates a new cap with default attributes. CHAPTER 34. PACKAGE: ORG.JFREE.CHART.PLOT.DIAL 34.5.3 400 General Attributes The size of the cap is controlled by the radius: å public double getRadius(); Returns the radius for the cap, as a percentage of the size of the plot’s framing rectangle. The default value is 0.05 (five percent). å public void setRadius(double radius); Sets the radius for the cap and sends a DialLayerChangeEvent to all registered listeners. To control the colour of the cap: å public Paint getFillPaint(); Returns the colour used to fill the cap. The default value is Color.white. å public void setFillPaint(Paint paint); Sets the colour used to fill the cap and sends a DialLayerChangeEvent to all registered listeners. If paint is null, this method throws an IllegalArgumentException. To control the colour of the cap’s outline: å public Paint getOutlinePaint(); Returns the colour used to draw the cap outline. The default value is Color.black. å public void setOutlinePaint(Paint paint); Sets the colour used to draw the cap outline and sends a DialLayerChangeEvent to all registered listeners. If paint is null, this method throws an IllegalArgumentException. To control the pen stroke used to draw the cap’s outline: å public Stroke getOutlineStroke(); Returns the stroke used to draw the cap’s outline (never null). The default value is BasicStroke(2.0f). å public void setOutlineStroke(Stroke stroke); Sets the stroke used to draw the cap’s outline and sends a DialLayerChangeEvent to all registered listeners. If stroke is null, this method throws an IllegalArgumentException. 34.5.4 Other Methods The plot will call the following method to determine whether the layer is clipped to the dial frame window: å public boolean isClippedToWindow(); Returns true to indicate that this layer should be clipped to the dial plot’s window. The plot will call the following method to draw the layer: å public void draw(Graphics2D g2, DialPlot plot, Rectangle2D frame, Rectangle2D view); Draws the cap relative to the specified frame and view rectangles. 34.5.5 Equals, Cloning and Serialization This class overrides the equals() method: å public boolean equals(Object obj); Tests this instance for equality with an arbitrary object. Instances of this class are cloneable (PublicCloneable) and serializable. 34.5.6 Notes Some points to note: • this class extends AbstractDialLayer; • use the setCap() method in the DialPlot class to add an instance of this class to a plot. CHAPTER 34. PACKAGE: ORG.JFREE.CHART.PLOT.DIAL 34.6 DialFrame 34.6.1 Overview 401 A dial frame is the layer on the DialPlot that is drawn last, over top of everything else on the plot. Two implementations of this interface are provided: • SimpleDialFrame – a simple circular dial; • StandardDialFrame – allows more complex dial shapes; This interface extends DialLayer. 34.6.2 Interface Methods This interface adds one method to those inherited from the DialLayer interface: å public Shape getWindow(Rectangle2D frame); Returns the shape representing the viewing window for the frame. Other layers in the DialPlot may be clipped to this window. 34.6.3 Notes Classes that implement this interface should also implement Serializable, otherwise serialization for the dial plots will not work. 34.7 DialLayer 34.7.1 Overview A DialPlot is composed of a number of layers. This interface defines the methods common to all layers. Classes that implement this interface include: • DialBackground; • DialCap; • DialPointer; • DialTextAnnotation; • DialValueIndicator; • SimpleDialFrame; • StandardDialFrame; • StandardDialRange. • StandardDialScale. See also the AbstractDialLayer class. 34.7.2 General Methods All dial layers have a flag that controls visibility: å public boolean isVisible(); Returns true if the layer is currently visible, and false otherwise. CHAPTER 34. PACKAGE: ORG.JFREE.CHART.PLOT.DIAL 34.7.3 402 Change Notification A simple change notification mechanism is provided by all layers so that the DialPlot can track changes to any of its layers: å public void addChangeListener(DialLayerChangeListener listener); Registers a listener so that it receives notification of changes to this layer. å public void removeChangeListener(DialLayerChangeListener listener); Deregisters a listener so that it no longer receives notification of changes to this layer. å public boolean hasListener(EventListener listener); Returns true if the specified listener is registered with this layer. This method is provided mainly for unit testing purposes. You won’t typically need to use this mechanism directly. 34.7.4 Drawing The drawing methods are called by the DialPlot class, which first determines whether or not the drawing for a layer should be clipped to the plot’s window (the window itself is defined by the DialFrame): å public boolean isClippedToWindow(); Returns true if drawing should be clipped, and false otherwise. To draw the layer: å public void draw(Graphics2D g2, DialPlot plot, Rectangle2D frame, Rectangle2D view); Draws the layer within the specified frame. 34.7.5 Notes The DialFrame and DialScale interfaces extend this interface. 34.8 DialLayerChangeEvent 34.8.1 Overview An event that originates from a DialLayer and received by a DialLayerChangeListener. This is part of the change notification mechanism that allows the DialPlot class to track changes to the DialLayer instances that it manages. By default, the dial plot will respond to layer changes by forwarding a PlotChangeEvent to all its own listeners. 34.8.2 Constructors To create a new instance: å public DialLayerChangeEvent(DialLayer layer); Creates a new event with the specified layer as the source. 34.8.3 Methods To find the layer from which this event originated: å public DialLayer getDialLayer(); Returns the layer from which this event originated. See Also DialLayerChangeListener. CHAPTER 34. PACKAGE: ORG.JFREE.CHART.PLOT.DIAL 34.9 DialLayerChangeListener 34.9.1 Overview 403 This interface is implemented by classes that which to receive change event notifications from a DialLayer. 34.9.2 Methods This interface declares a single method: å public void dialLayerChanged(DialLayerChangeEvent event); Called to indicate that a change has been made to a DialLayer (the layer itself can be retrieved from the event instance). See Also DialLayerChangeEvent. 34.10 DialPlot 34.10.1 Overview A plot that displays a value (from a ValueDataset) in a dial format. The plot is composed of multiple layers, providing a lot of scope to customise the appearance of the plot. 34.10.2 Constructors This class defines two constructors: å public DialPlot(); Equivalent to DialPlot(null)—see the next constructor. å public DialPlot(ValueDataset dataset); Creates a new plot based on the specified dataset (which may be null). 34.10.3 General Attributes To control the background for the dial: å public DialLayer getBackground(); Returns the background for the plot. The default value is null, which means no background is drawn. å public void setBackground(DialLayer background); Sets the background for the dial (null is permitted) and sends a PlotChangeEvent to all registered listeners. If you set the background to null, no background is drawn. Any DialLayer can be used for the background, but a common choice is the DialBackground class. The dial frame is a special layer that is drawn last on the dial, possibly covering parts of the layers drawn earlier: å public DialFrame getDialFrame(); Returns the dial frame (never null). The default value is a new instance of StandardDialFrame. å public void setDialFrame(DialFrame frame); Sets the dial frame and sends a PlotChangeEvent to all registered listeners. The cap is a layer that is drawn immediately after the dial’s needle is drawn: å public DialLayer getCap(); Returns the dial’s cap, which may be null (which means no cap is drawn). The cap is a layer that is drawn immediately after the dial pointer, and is very often a small shape covering the point where the needle is attached to the dial. The default value is null. CHAPTER 34. PACKAGE: ORG.JFREE.CHART.PLOT.DIAL å public void setCap(DialLayer cap); Sets the cap and sends a PlotChangeEvent to all registered listeners. If you set the cap to null, no cap will be drawn. 34.10.4 General Layers The following methods allow general layers to be added to and removed from a plot: å public void addLayer(DialLayer layer); Adds a new layer to the plot and sends a PlotChangeEvent to all registered listeners. If layer is null, this method throws an IllegalArgumentException. å public int getLayerIndex(DialLayer layer); Returns the index for the specified layer. å public void removeLayer(int index); Removes the layer at the specified index. å public void removeLayer(DialLayer layer); Removes the specified layer from the plot. 34.10.5 Datasets and Scales The plot displays data from a ValueDataset (or possibly multiple datasets): å public ValueDataset getDataset(); Returns the primary dataset for the plot. This may be null. å public ValueDataset getDataset(int index); Returns the dataset at the specified index, or null if there is no dataset. å public void setDataset(ValueDataset dataset); Sets the main dataset for the plot (null is permitted) and sends a PlotChangeEvent to all registered listeners. å public void setDataset(int index, ValueDataset dataset); Sets the dataset at the specified index (dataset may be null) and sends a PlotChangeEvent to all registered listeners. å public double getValue(int datasetIndex); A convenience method that returns the current value for the specified dataset. If there is no dataset at the specified index, this method will return Double.NaN. å public int getDatasetCount(); Returns the number of datasets in the plot. Data values are plotted against a scale. Scales are added to the plot as special layers: å public DialScale getScale(int index); Returns the scale with the specified index, or null. å public void addScale(int index, DialScale scale); Adds a scale to the plot at the specified index, and sends a PlotChangeEvent to all registered listeners. å public void mapDatasetToScale(int index, int scaleIndex); Maps a dataset to a particular scale (necessary when the plot has multiple scales). å public DialScale getScaleForDataset(int datasetIndex); Returns the scale that applies to the specified dataset. 404 CHAPTER 34. PACKAGE: ORG.JFREE.CHART.PLOT.DIAL 34.10.6 405 Pointers The plot displays a pointer to indicate the current value of the corresponding dataset: å public void addPointer(DialPointer pointer); Adds a pointer to the plot. å public int getPointerIndex(DialPointer pointer); Returns the index of the specified pointer. å public void removePointer(int index); Removes the pointer at the specified index. å public void removePointer(DialPointer pointer); Removes the specified pointer. 34.10.7 Frame and View Rectangles The dimensions of the dial plot are calculated relative to a framing rectangle, but in some cases you only want a subset of the dial to be presented in the plot area—the viewing rectangle defines this visible subset: å public double getViewX(); The relative position of the viewing rectangle’s x-coordinate with reference to the framing rectangle. This will be a value in the range 0.0 to 1.0, with the default value being 0.0. å public double getViewY(); Returns the relative position of the viewing rectangle’s y-coordinate with reference to the framing rectangle. This will be a value in the range 0.0 to 1.0, with the default value being 0.0. å public double getViewWidth(); Returns the relative width of the viewing rectangle with reference to the framing rectangle. This will be a value in the range 0.0 to 1.0, with the default value being 1.0. å public double getViewHeight(); Returns the relative height of the viewing rectangle with reference to the framing rectangle. This will be a value in the range 0.0 to 1.0, with the default value being 1.0. å public void setView(double x, double y, double w, double h); Sets the viewing rectangle relative to the plot’s (not known until rendering time) framing rectangle, and sends a PlotChangeEvent to all registered listeners. 34.10.8 Other Methods A range of other methods in this class are typically called by JFreeChart rather than user code. å public String getPlotType(); Returns a human readable string describing the plot type. A listener method is called whenever a layer belonging to the plot is changed: å public void dialLayerChanged(DialLayerChangeEvent event); Receives notification of a change to one of the layers managed by the plot (you shouldn’t need to call this method yourself). This method responds by forwarding a PlotChangeEvent to all registered listeners. A utility method calculates rectangles using radius values that are specified as a percentage of the height and width of a reference rectangle—see figure 34.2: å public static Rectangle2D rectangleByRadius(Rectangle2D rect, double radiusW, double radiusH); Returns a new rectangle centered on the same point as rect, which the width and height cal- culated using the specified radius values (which are expressed as a percentage of the width and height of the reference rectangle). Note that 0.75 is interpreted as seventy five percent. JFreeChart will draw the plot by calling the following method: å public void draw(Graphics2D g2, Rectangle2D area, Point2D anchor, PlotState parentState, PlotRenderingInfo info); Draws the plot within the specified area. CHAPTER 34. PACKAGE: ORG.JFREE.CHART.PLOT.DIAL 406 Reference rectangle radiusH radiusW Calculated rectangle Figure 34.2: Calculating a rectangle “by radius” 34.10.9 Equals, Cloning and Serialization This class overrides the equals() method: å public boolean equals(Object obj); Tests this plot for equality with an arbitrary object. Instances of this class are Cloneable and Serializable. 34.10.10 Notes Some points to note: • some demos (DialPlotDemo1-5.java) are included in the JFreeChart demo collection. 34.11 DialPointer 34.11.1 Overview The base class for a pointer indicating the current value on the dial. This class implements the DialLayer interface. Subclasses include: • DialPointer.Pin; • DialPointer.Pointer. 34.11.2 Constructors The two constructors defined by this class are protected—they can only be called by subclasses: å protected DialPointer(); Equivalent to DialPointer(0)—see the next constructor. å protected DialPointer(int datasetIndex); Creates a new pointer associated with the specified dataset. 34.11.3 General Attributes The pointer is associated with a specific dataset: å public int getDatasetIndex(); Returns the dataset index for this pointer. The default value is specified in the constructor. CHAPTER 34. PACKAGE: ORG.JFREE.CHART.PLOT.DIAL 407 å public void setDatasetIndex(int index); Sets the dataset that this pointer is associated with and sends a DialLayerChangeEvent to all registered listeners. The length of the pointer is determined by the radius, which is specified relative to the dial’s framing rectangle: å public double getRadius(); Returns the radius of the pointer, as a percentage of the dial’s framing rectangle. The default value is 0.95 (ninety five percent). å public void setRadius(double radius); Sets the radius of the pointer, and sends a DialLayerChangeEvent to all registered listeners. 34.11.4 Other Methods The DialPlot class will call the following method to determine whether or not this layer should be clipped: å public boolean isClippedToWindow(); Returns true to indicate that this layer is clipped to the dial frame window. 34.11.5 Equals, Cloning and Serialization This class overrides the equals() method: å public boolean equals(Object obj); Tests this pointer for equality with an arbitrary object. 34.12 DialPointer.Pin 34.12.1 Overview A dial pointer that is drawn as a thin straight line. This class extends DialPointer and implements the DialLayer interface. 34.12.2 Constructors To create a new instance: å public Pin(); Equivalent to Pin(0)—see the next constructor. å public Pin(int datasetIndex); Creates a new dial pointer associated with the specified dataset. By default, the pointer is drawn as a thin line (BasicStroke(3.0f)) in red. 34.12.3 General Attributes To control the colour of the pointer: å public Paint getPaint(); Returns the paint (never null) used to draw the pointer. The default value is Color.red. å public void setPaint(Paint paint); Sets the paint used to draw the pointer, and sends a DialLayerChangeEvent to all registered listeners. If paint is null, this method throws an IllegalArgumentException. To control the stroke used to draw the pointer: å public Stroke getStroke(); Returns the stroke used to draw the pointer. The default value is BasicStroke(3.0f, BasicStroke.CAP ROUND, BasicStroke.JOIN BEVEL). CHAPTER 34. PACKAGE: ORG.JFREE.CHART.PLOT.DIAL 408 å public void setStroke(Stroke stroke); Sets the stroke used to draw the pointer, and sends a DialLayerChangeEvent to all registered listeners. If stroke is null, this method throws an IllegalArgumentException. 34.12.4 Other Methods The DialPlot will call the following method to draw the pointer: å public void draw(Graphics2D g2, DialPlot plot, Rectangle2D frame, Rectangle2D view); Draws the pointer. 34.12.5 Equals, Cloning and Serialization This class overrides the equals() method: å public boolean equals(Object obj); Tests this pointer for equality with an arbitrary object. Instances of this class are Cloneable and Serializable. 34.12.6 Notes The length of the pointer is controlled by the inherited radius attribute. See Also DialPointer.Pointer. 34.13 DialPointer.Pointer 34.13.1 Overview A dial pointer that is drawn in a long triangular shape. 34.13.2 Constructors To create a new instance: å public Pointer(); Equivalent to Pointer(0)—see the next constructor. å public Pointer(int datasetIndex); Creates a new pointer that is associated with the specified dataset. 34.13.3 General Attributes The width of the base of the pointer is specified as a radius, in percentage terms relative to the å public double getWidthRadius(); Returns the radius used to calculate the width of the base of the pointer. The default value is 0.05 (five percent). å public void setWidthRadius(double radius); Sets the radius used to calculate the width of the base of the pointer, and sends a DialLayerChangeEvent to all registered listeners. To control the paint used to fill the pointer: å public Paint getFillPaint(); [1.0.8] Returns the paint (never null) used to fill the pointer. The default value is Color.gray. CHAPTER 34. PACKAGE: ORG.JFREE.CHART.PLOT.DIAL 409 å public void setFillPaint(Paint paint); [1.0.8] Sets the paint used to fill the pointer and sends a DialLayerChangeEvent to all registered listeners. If paint is null, this method throws an IllegalArgumentException. To control the paint used to draw the pointer outline: å public Paint getOutlinePaint(); [1.0.8] Returns the paint (never null) used to draw the outline of the paint. The default value is Color.black. å public void setOutlinePaint(Paint paint); [1.0.8] Sets the paint used to draw the pointer outline and sends a DialLayerChangeEvent to all registered listeners. If paint is null, this method throws an IllegalArgumentException. 34.13.4 Other Methods The DialPlot will call the following method during chart rendering—you won’t normally need to call this method directly: å public void draw(Graphics2D g2, DialPlot plot, Rectangle2D frame, Rectangle2D view) Draws the pointer. 34.13.5 Equals, Cloning and Serialization This class overrides the equals() method: å public boolean equals(Object obj); Tests this pointer for equality with an arbitrary object. Instances of this class are Cloneable and Serializable. See Also DialPointer.Pin. 34.14 DialScale 34.14.1 Overview A DialScale is a specialised DialLayer that has the ability to convert data values into a corresponding angle, and vice versa. The DialPlot uses this scale to position a dial pointer that indicates the current value of the dataset that is mapped to this scale. A typical dial scale implementation will include drawing code to display the scale within the dial (see StandardDialScale, for example). 34.14.2 Interface Methods To convert a data value to an angle: å public double valueToAngle(double value); Returns the angle (in degrees) that corresponds to the specified value. To convert an angle to a data value: å public double angleToValue(double angle); Returns the value that corresponds to the given angle (which is specified in degrees). 34.14.3 Notes This interface extends the DialLayer interface. See Also StandardDialScale. CHAPTER 34. PACKAGE: ORG.JFREE.CHART.PLOT.DIAL 34.15 DialTextAnnotation 34.15.1 Overview 410 A dial layer that draws a text string at an arbitrary location on a dial. For example, in figure 34.1, the “Temperature” label is drawn by an instance of this class. 34.15.2 Constructors To create a new annotation: å public DialTextAnnotation(String label); Creates a new text annotation with default attributes. If label is null, this constructor throws an IllegalArgumentException. 34.15.3 General Attributes To control the text displayed by the annotation: å public String getLabel(); Returns the text (never null) displayed by the annotation. The initial value is specified in the constructor. å public void setLabel(String label); Sets the text to be displayed by the annotation and sends a DialLayerChangeEvent to all registered listeners. If label is null, this method throws an IllegalArgumentException. To control the font used to display the label: å public Font getFont(); Returns the font (never null) used to display the label. The default value is Font("Dialog", Font.BOLD, 14). å public void setFont(Font font); Sets the font used to display the label and sends a DialLayerChangeEvent to all registered listeners. If font is null, this method throws an IllegalArgumentException. To control the foreground colour of the label: å public Paint getPaint(); Returns the paint (never null) used to display the label. The default value is Color.black. å public void setPaint(Paint paint); Sets the paint used to display the label and sends a DialLayerChangeEvent to all registered listeners. If paint is null, this method throws an IllegalArgumentException. The anchor point for the text label is defined by an angle and a radius: å public double getAngle(); Returns the angle (in degrees) that determines the text anchor point. The encoding is the same as for Java’s Arc2D class. The default value is -90.0. å public void setAngle(double angle); Sets the angle (in degrees) that determines the text anchor point, and sends a DialLayerChangeEvent to all registered listeners. å public double getRadius(); Returns the radius as a percentage relative to the dial’s framing rectangle. The default value is 0.30 (thirty percent). å public void setRadius(double radius); Sets the radius as a percentage of the dial’s framing rectangle and sends a DialLayerChangeEvent to all registered listeners. Having determined the anchor point, the text is aligned according to its anchor: CHAPTER 34. PACKAGE: ORG.JFREE.CHART.PLOT.DIAL 411 å public TextAnchor getAnchor(); Returns the text anchor (never null) for the annotation. The default value is TextAnchor.TOP CENTER. å public void setAnchor(TextAnchor anchor); Sets the text anchor and sends a DialLayerChangeEvent to all registered listeners. If anchor is null, this method throws an IllegalArgumentException. 34.15.4 Other Methods The following methods are typically called by the DialPlot class during chart rendering, you won’t normally call these methods directly: å public boolean isClippedToWindow(); Returns true to indicate that this layer should be clipped to the dial frame window. å public void draw(Graphics2D g2, DialPlot plot, Rectangle2D frame, Rectangle2D view); Draws the text annotation. 34.15.5 Equals, Cloning and Serialization This class overrides the equals() method: å public boolean equals(Object obj); Tests this text annotation for equality with an arbitrary object. Instances of this class are Cloneable and Serializable. 34.16 DialValueIndicator 34.16.1 Overview A dial layer that displays the value from a dataset. 34.16.2 Constructors To create a new instance: å public DialValueIndicator(); Equivalent to DialValueIndicator(0)—see the next constructor. å public DialValueIndicator(int datasetIndex); Creates a new instance that will display the value from the specified dataset. 34.16.3 General Attributes To control the dataset from which the indicator obtains the current value: å public int getDatasetIndex(); Returns the index of the dataset from which the indicator obtains the current value. The initial value is specified in the constructor. å public void setDatasetIndex(int index); Sets the index of the dataset from which the indicator obtains the current value and sends a DialLayerChangeEvent to all registered listeners. To control the formatter used to convert the dataset value into a string for display purposes: å public NumberFormat getNumberFormat(); Returns the number formatter (never null) used to convert the dataset value into a String for the display. The default value is DecimalFormat("0.0"). CHAPTER 34. PACKAGE: ORG.JFREE.CHART.PLOT.DIAL 412 å public void setNumberFormat(NumberFormat formatter); Sets the number formatter used to convert the dataset value into a String for the display, and sends a DialLayerChangeEvent to all registered listeners. If formatter is null, this method throws an IllegalArgumentException. To control the font used to display the dataset value: å public Font getFont(); Returns the font (never null) used to display the dial value. The default value is Font("Dialog", Font.BOLD, 14). å public void setFont(Font font); Sets the font used to display the dial value and sends a DialLayerChangeEvent to all registered listeners. If font is null, this method throws an IllegalArgumentException. To control the colour used to display the dataset value: å public Paint getPaint(); Returns the paint (never null) used to display the dial value. The default value is Color.black. å public void setPaint(Paint paint); Sets the paint used to display the dial value, and sends a DialLayerChangeEvent to all registered listeners. If paint is null, this method throws an IllegalArgumentException. To control the background colour for the indicator: å public Paint getBackgroundPaint(); Returns the paint (never null) used to fill the background of the indicator. The default value is Color.white. å public void setBackgroundPaint(Paint paint); Sets the paint used to fill the background of the indicator and sends a DialLayerChangeEvent to all registered listeners. If paint is null, this method throws an IllegalArgumentException. To control the stroke used to draw the outline for the indicator: å public Stroke getOutlineStroke(); Returns the stroke (never null) used to draw the outline around the indicator. The default value is BasicStroke(1.0f). å public void setOutlineStroke(Stroke stroke); Sets the stroke used to draw the outline around the indicator and sends a DialLayerChangeEvent to all registered listeners. If stroke is null, this method throws an IllegalArgumentException. To control the colour used to draw the outline for the indicator: å public Paint getOutlinePaint(); Returns the paint (never null) used to draw the outline around the indicator. The default value Color.blue. å public void setOutlinePaint(Paint paint); Sets the paint used to draw the outline around the indicator and sends a DialLayerChangeEvent to all registered listeners. If paint is null, this method throws an IllegalArgumentException. 34.16.4 Indicator Position The anchor point for positioning the indicator is specified in terms of an angle and a radius. To control the angle: å public double getAngle(); Returns the angle, in degrees, for calculating the anchor point. The default value is -90.0, which corresponds to six o’clock on a clock face. å public void setAngle(double angle); Sets the angle (in degrees, using the same encoding as Java’s Arc2D class) for calculating the anchor point used to position the indicator, and sends a DialLayerChangeEvent to all registered listeners. CHAPTER 34. PACKAGE: ORG.JFREE.CHART.PLOT.DIAL 413 To control the radius: å public double getRadius(); Returns the radius, relative to the dial’s framing rectangle. The default value is 0.3. å public void setRadius(double radius); Sets the radius used to calculate the anchor point for the indicator, and sends a DialLayerChangeEvent to all registered listeners. The radius is specified as a percentage relative to the dial’s framing rectangle. The value indicator is displayed as a text item in a frame. The frame anchor specifies the point on this frame that will be aligned to the anchor point (which is calculated from the angle and radius described previously): å public RectangleAnchor getFrameAnchor(); Returns the frame anchor (never null). The default value is RectangleAnchor.CENTER. å public void setFrameAnchor(RectangleAnchor anchor); Sets the frame anchor and sends a DialLayerChangeEvent to all registered listeners. If anchor is null, this method throws an IllegalArgumentException. 34.16.5 Indicator Dimensions To ensure that the value indicator has a fixed width regardless of the current value in the dataset, a template value is used to calculate the dimensions of the indicator. This template value will be formatted using the current number formatter, then the dimensions of the string will be used to determine the dimensions of the value indicator: å public Number getTemplateValue(); Returns the template value (never null). The default value is Double(100.0). å public void setTemplateValue(Number value); Sets the template value and sends a DialLayerChangeEvent to all registered listeners. If value is null, this method throws an IllegalArgumentException. You should set the template value to the largest number that is likely to be displayed in the indicator (if negative values are possible, make the template negative to allow for the sign in the formatted string). To control the white space around the indicator value (but within the outline): å public RectangleInsets getInsets(); Returns the insets (never null) which determine the white-space around the indicator value. The default value is RectangleInsets(4, 4, 4, 4). å public void setInsets(RectangleInsets insets); Sets the insets which determine the white space around the indicator value and sends a DialLayerChangeEvent to all registered listeners. 34.16.6 Aligning the Indicator Value The value anchor determines the point to which the value text will be aligned—you’ll typically set this to RectangleAnchor.LEFT or RectangleAnchor.RIGHT: å public RectangleAnchor getValueAnchor(); Returns the token (never null) which determines the anchor point for the value text. The default value is RectangleAnchor.RIGHT. å public void setValueAnchor(RectangleAnchor anchor); Sets the token that determines the anchor point for the value text, and sends a DialLayerChangeEvent to all registered listeners. If anchor is null, this method throws an IllegalArgumentException. The text anchor determines the point on the text that will be aligned to the value anchor: CHAPTER 34. PACKAGE: ORG.JFREE.CHART.PLOT.DIAL 414 å public TextAnchor getTextAnchor(); Returns the token (never null) that determines the point on the text that is aligned to the value anchor. The default value is TextAnchor.CENTER RIGHT. å public void setTextAnchor(TextAnchor anchor); Sets the token that determines the point on the text that is aligned to the value anchor, and sends a DialLayerChangeEvent to all registered listeners. If anchor is null, this method throws an IllegalArgumentException. 34.16.7 Other Methods The following methods are typically called by the DialPlot class during chart rendering, you won’t normally call these methods directly: å public boolean isClippedToWindow(); Returns true to indicate that this layer should be clipped to the dial frame window. å public void draw(Graphics2D g2, DialPlot plot, Rectangle2D frame, Rectangle2D view); Draws the dial value indicator. 34.16.8 Equals, Cloning and Serialization This class overrides the equals() method: å public boolean equals(Object obj); Tests this indicator for equality with an arbitrary object. 34.16.9 Notes To add an indicator to a DialPlot, use the addLayer() method. 34.17 SimpleDialFrame 34.17.1 Overview A plain circular dial frame. This class implements the DialFrame interface. 34.17.2 Constructors To create a new instance: å public SimpleDialFrame(); Creates a new dial frame with default attributes. 34.17.3 General Attributes To control the radius of the dial frame: å public double getRadius(); Returns the radius, expressed as a percentage relative to the framing rectangle. The default value is 0.95 (ninety-five percent). å public void setRadius(double radius); Sets the radius of the circular dial, as a percentage relative to the framing rectangle, and sends a DialLayerChangeEvent to all registered listeners. To control the background paint: å public Paint getBackgroundPaint(); Returns the paint (never null) used to fill the space between the double lines around the outer edge of the circle. The default value is Color.gray. CHAPTER 34. PACKAGE: ORG.JFREE.CHART.PLOT.DIAL 415 å public void setBackgroundPaint(Paint paint); Sets the paint used to fill the space between the double lines around the edge of the dial, and sends a DialLayerChangeEvent to all registered listeners. If paint is null, this method throws an IllegalArgumentException. To control the foreground paint: å public Paint getForegroundPaint(); Returns the paint (never null) used to draw the double lines around the outside of the dial. The default value is Color.black. å public void setForegroundPaint(Paint paint); Sets the paint used to draw the double lines around the outside of the circular dial, and sends a DialLayerChangeEvent to all registered listeners. If paint is null, this method throws an IllegalArgumentException. To control the stroke used to draw the dial outline: å public Stroke getStroke(); Returns the stroke (never null) used to draw the dial outline. The default value is BasicStroke(2.0f). å public void setStroke(Stroke stroke); Sets the stroke used to draw the dial outline and sends a DialLayerChangeEvent to all registered listeners. If stroke is null, this method throws an IllegalArgumentException. 34.17.4 Other Methods The plot will fetch the window for this dial frame using the following method: å public Shape getWindow(Rectangle2D frame); Returns the window for this frame, in this case an Ellipse2D that fits within the specified frame. å public boolean isClippedToWindow(); Returns false—this layer does not need to be clipped. å public void draw(Graphics2D g2, DialPlot plot, Rectangle2D frame, Rectangle2D view); Draws the dial frame within the specified frame and view rectangles. 34.17.5 Equals, Cloning and Serialization This class overrides the equals() method: å public boolean equals(Object obj); Tests this frame for equality with an arbitrary object. Instances of this class are cloneable (PublicCloneable) and serializable. See Also StandardDialFrame. 34.18 StandardDialRange 34.18.1 Overview A layer for a DialPlot that highlights (statically) a range of values. You could use this to indicate ranges on a dial such as, for example, “normal”, “high” and “extreme”. CHAPTER 34. PACKAGE: ORG.JFREE.CHART.PLOT.DIAL 34.18.2 416 Constructors This class defines two constructors: å public StandardDialRange(); Equivalent to StandardDialRange(0.0, 100.0, Color.white)—see the next constructor. å public StandardDialRange(double lower, double upper, Paint paint); Creates a new instance with the specified bounds. If paint is null, this constructor throws an IllegalArgumentException. 34.18.3 General Attributes The range is measured relative to a specific scale on the DialPlot: å public int getScaleIndex(); Returns the scale index. The default value is 0. å public void setScaleIndex(int index); Sets the scale index and sends a DialLayerChangeEvent to all registered listeners. The range is primarily defined by its lower and upper bounds, which are specified in data units: å public double getLowerBound(); Returns the lower bound for the range, in data units. å public void setLowerBound(double bound); Sets the lower bound for the range and sends a DialLayerChangeEvent to all registered listeners. If bound is not less than getUpperBound(), this method throws an IllegalArgumentException. å public double getUpperBound(); Returns the upper bound for the range, in data units. å public void setUpperBound(double bound); Sets the upper bound for the range and sends a DialLayerChangeEvent to all registered listeners. If bound is not greater than getLowerBound(), this method throws an IllegalArgumentException. å public void setBounds(double lower, double upper); Sets the bounds for the range and sends a DialLayerChangeEvent to all registered listeners. If lower is not less than upper, this method throws an IllegalArgumentException. To control the colour used to highlight the range: å public Paint getPaint(); Returns the paint (never null) used to highlight the range. The initial value is specified in the constructor. å public void setPaint(Paint paint); Sets the paint used to highlight the range and sends a DialLayerChangeEvent to all registered listeners. If paint is null, this method throws an IllegalArgumentException. The range highlights are drawn at a specified radius within the dial: å public double getInnerRadius(); Returns the radius for the inner highlight on the range. The default value is 0.48. å public void setInnerRadius(double radius); Sets the radius for the inner highlight and sends a DialLayerChangeEvent to all registered listeners. å public double getOuterRadius(); Returns the radius for the inner highlight on the range. The default value is 0.52. å public void setOuterRadius(double radius); Sets the radius for the outer highlight and sends a DialLayerChangeEvent to all registered listeners. CHAPTER 34. PACKAGE: ORG.JFREE.CHART.PLOT.DIAL 34.18.4 417 Other Methods The following methods are typically called by the DialPlot class during chart rendering, you won’t normally call these methods directly: å public boolean isClippedToWindow(); Returns true to indicate that this layer should be clipped to the dial frame window. å public void draw(Graphics2D g2, DialPlot plot, Rectangle2D frame, Rectangle2D view); Draws the range indicator. 34.18.5 Equals, Cloning and Serialization This class overrides the equals() method: å public boolean equals(Object obj); Tests this dial range for equality with an arbitrary object. Instances of this class are Cloneable (PublicCloneable) and Serializable. 34.19 StandardDialScale 34.19.1 Overview A standard scale that can be used on a DialPlot. The scale can display major and minor tick marks at user-specified intervals, and numerical labels for the major tick marks. 34.19.2 Constructors To create a new instance: å public StandardDialScale(); Equivalent to StandardDialScale(0.0, 100.0, 175, -170, 10.0, 4)—see the next constructor. å public StandardDialScale(double lowerBound, double upperBound, double startAngle, double extent, double majorTickIncrement, int minorTickCount); Creates a new dial scale covering the values lowerBound to upperBound. 34.19.3 General Attributes To control the arc through which the scale is drawn on the dial, you can specify the starting angle and the extent (in degrees, using the same encoding as Java’s Arc2D class): å public double getStartAngle(); Returns the angle (in degrees) for the starting point of the scale. The initial value is specified in the constructor. å public void setStartAngle(double angle); Sets the angle (in degrees, same encoding as Java’s Arc2D class) for the starting point of the scale, and sends a DialLayerChangeEvent to all registered listeners. To control the extent: å public double getExtent(); Returns the extent (in degrees) for the scale. The initial value is specified in the constructor. å public void setExtent(double extent); Sets the extent (in degrees, same encoding as Java’s Arc2D class) for the scale, and sends a DialLayerChangeEvent to all registered listeners. To control the lower bound: å public double getLowerBound(); [1.0.8] Returns the lower bound for the scale. CHAPTER 34. PACKAGE: ORG.JFREE.CHART.PLOT.DIAL 418 å public void setLowerBound(double lower); [1.0.8] Sets the lower bound for the scale and sends a DialLayerChangeEvent to all registered listeners. To control the upper bound: å public double getUpperBound(); [1.0.8] Returns the upper bound for the scale. å public void setUpperBound(double upper); [1.0.8] Sets the upper bound for the scale and sends a DialLayerChangeEvent to all registered listeners. 34.19.4 Tick Marks and Labels The tick radius determines how far out on the dial the tick marks are drawn (typically they will appear near the outer edge of the dial, but for a dial that shows more than one scale you might want to show a scale closer to the centre): å public double getTickRadius(); Returns the radius as a percentage of the dial’s framing rectangle. The default value is 0.70 (seventy percent). å public void setTickRadius(double radius); Sets the radius used to position the tick marks, and sends a DialLayerChangeEvent to all registered listeners. The tick radius defines the reference point for the major and minor tick marks, as well as the labels for the major tick marks. These are all described in the following sections. 34.19.5 Major Tick Marks The scale will draw tick marks at regular (user-definable) intervals along the range. To control the interval between tick marks: å public double getMajorTickIncrement(); Returns the interval between major tick marks. The initial value is specified in the constructor. å public void setMajorTickIncrement(double increment); Sets the interval between major tick marks and sends a DialLayerChangeEvent to all registered listeners. To control the length of the major tick marks: å public double getMajorTickLength(); Returns the length of the major tick marks, expressed as an amount to be subtracted from the tick radius (see getTickRadius()). The default value is 0.04. å public void setMajorTickLength(double length); Sets the length of the major tick marks and sends a DialLayerChangeEvent to all registered listeners. The length must be greater than or equal() to zero. To control the paint used to draw the major tick marks: å public Paint getMajorTickPaint(); Returns the paint (never null) used to draw the major tick marks. Color.black. The default value is å public void setMajorTickPaint(Paint paint); Sets the paint used to draw the major tick marks and sends a DialLayerChangeEvent to all registered listeners. If paint is null, this method throws an IllegalArgumentException. To control the stroke used to draw the major tick marks: å public Stroke getMajorTickStroke(); Returns the stroke (never null) used to draw the major tick marks. BasicStroke(3.0f). The default value is å public void setMajorTickStroke(Stroke stroke); Sets the stroke used to draw the major tick marks, and sends a DialLayerChangeEvent to all registered listeners. If stroke is null, this method throws an IllegalArgumentException. CHAPTER 34. PACKAGE: ORG.JFREE.CHART.PLOT.DIAL 34.19.6 419 Tick Labels The scale will display numerical labels for the major tick marks. There is a flag to enable/disable this feature: å public boolean getTickLabelsVisible(); Returns the flag that controls whether or not the tick labels are visible. The default value is true. å public void setTickLabelsVisible(boolean visible); Sets the flag that controls whether or not the tick labels are visible and sends a DialLayerChangeEvent to all registered listeners. The anchor point for each label is determined using the tick radius (see getTickRadius()) adjusted by an offset value. Once the anchor point is determined, the value label is centred on the anchor point: å public double getTickLabelOffset(); Returns the tick label offset. The default value is 0.10. å public void setTickLabelOffset(double offset); Sets the tick label offset and sends a DialLayerChangeEvent to all registered listeners. To control the font used to display the tick labels: å public Font getTickLabelFont(); Returns the font (never null) used to display the tick labels. The default value is Font("Dialog", Font.BOLD, 16). å public void setTickLabelFont(Font font); Sets the font used to display the tick labels, and sends a DialLayerChangeEvent to all registered listeners. If font is null, this method throws an IllegalArgumentException. To control the foreground colour of the tick labels: å public Paint getTickLabelPaint(); Returns the paint (never null) used to display the tick labels. The default value is Color.black. å public void setTickLabelPaint(Paint paint); Sets the paint used to display the tick labels, and sends a DialLayerChangeEvent to all registered listeners. If paint is null, this method throws an IllegalArgumentException. There is a flag that controls whether or not the first tick label is displayed—this is intended for dials that are fully circular (in which case the first and last labels occupy the same position): å public boolean getFirstTickLabelVisible(); Returns the flag that controls whether or not the first tick label is visible. The default value is true. å public void setFirstTickLabelVisible(boolean visible); Sets the flag that controls whether or not the first tick label is visible, and sends a DialLayerChangeEvent to all registered listeners. 34.19.7 Minor Tick Marks The scale can display minor tick marks (with no labels). å public int getMinorTickCount(); Returns the number of minor tick marks to display between each pair of major tick marks. The initial value is specified in the constructor. å public void setMinorTickCount(int count); Sets the minor tick count and sends a DialLayerChangeEvent to all registered listeners. If count is less than zero, this method throws an IllegalArgumentException. To control the length of the minor tick marks: CHAPTER 34. PACKAGE: ORG.JFREE.CHART.PLOT.DIAL 420 å public double getMinorTickLength(); Returns the length of minor tick marks, as a radius specified as a percentage of the dial’s framing rectangle. The default value is 0.02 (two percent). å public void setMinorTickLength(double length); Sets the minor tick length and sends a DialLayerChangeEvent to all registered listeners. If you set the length to 0.0, no minor tick marks will be drawn. To control the paint used for the minor tick marks: å public Paint getMinorTickPaint(); Returns the paint (never null) used for the minor tick marks. The default value is Color.black. å public void setMinorTickPaint(Paint paint); Sets the paint used to display the minor tick marks, and sends a DialLayerChangeEvent to all registered listeners. If paint is null, this method throws an IllegalArgumentException. To control the stroke used for the minor tick marks: å public Stroke getMinorTickStroke(); [1.0.8] Returns the stroke (null) used for the minor tick marks. The default value is BasicStroke(1.0f). å public void setMinorTickStroke(Stroke stroke); [1.0.8] Sets the stroke used to draw the minor tick marks and sends a DialLayerChangeEvent to all registered listeners. If stroke is null, this method throws an IllegalArgumentException. 34.19.8 Conversion Methods The following methods are used to convert from data values to angles and back again—these are used by the plot, and you won’t typically need to call these methods yourself: å public double valueToAngle(double value); Returns the angle (in degrees) that corresponds to the specified data value. This is a function of the lower and upper bounds for the scale, and the starting angle and extent. å public double angleToValue(double angle); Returns the value that corresponds to the given angle (which is specified in degrees). This is a function of the starting angle and extent, and the lower and upper bounds for the scale. 34.19.9 Other Methods The following methods are typically called by the DialPlot class during chart rendering, you won’t normally call these methods directly: å public boolean isClippedToWindow(); Returns true to indicate that the scale should be clipped to the dial frame’s window. å public void draw(Graphics2D g2, DialPlot plot, Rectangle2D frame, Rectangle2D view); Draws the scale within the specified frame and view rectangles. 34.19.10 Equals, Cloning and Serialization This class overrides the equals() method: å public boolean equals(Object obj); Tests this scale for equality with an arbitrary object. Instances of this class are Cloneable and Serializable. Chapter 35 Package: org.jfree.chart.renderer 35.1 Overview This package contains interfaces and classes that are used to implement renderers, plug-in objects that are responsible for drawing individual data items on behalf of a plot. Renderers offer a lot of scope for changing the appearance of your charts, either by changing the attributes of an existing renderer, or by implementing a completely new renderer. 35.2 AbstractRenderer 35.2.1 Overview An abstract class that provides support for the features common to all renderer implementations: • colors, line styles and shapes for each series (section 35.2.3); – – – – – – paint (section 35.2.5); fill paint (section 35.2.6); outline paint (section 35.2.7); stroke (section 35.2.8); outline stroke (section 35.2.9); shape (section 35.2.11); • series visibility (section 35.2.12); • series in legend visibility (section 35.2.13); • item labels (section 35.2.14); – – – – – item labels visible (section 35.2.15); item label font (section 35.2.16); item label paint (section 35.2.17); positive item label positions (section 35.2.18); negative item label positions (section 35.2.19); • chart entity generation (section 35.2.21); This base class is extended by: • AbstractCategoryItemRenderer; • AbstractXYItemRenderer. 421 CHAPTER 35. PACKAGE: ORG.JFREE.CHART.RENDERER 35.2.2 422 Per Series Attribute Mechanism Many renderer attributes need to have a value defined for each series in the dataset that is assigned to the renderer. In addition to the per-series attributes, JFreeChart will typically define a “base” (or default) attribute value, that will be used in the event that no attribute value is defined for a particular series. In version 1.0.5 and earlier, many attributes also define an override setting which takes precedence over the per-series and base settings. This, however, has caused confusion and is mostly unnecessary, so the overrides settings have been deprecated from version 1.0.6 onwards.1 35.2.3 Common Attributes All renderers use a common set of attributes as listed in Table 35.1. Attribute: Description: paint paintList The paint override (null permitted, deprecated from 1.0.6 onwards). A list of paints that apply to individual series (only referenced if paint is null). A flag that controls whether or not the per-series settings are autopopulated (the default is true). The paint that is used if there is no other setting. autoPopulateSeriesPaint basePaint fillPaint fillPaintList autoPopulateSeriesXXX baseFillPaint outlinePaint outlinePaintList autoPopulateSeriesXXX baseOutlinePaint stroke strokeList autoPopulateSeriesXXX baseStroke outlineStroke outlineStrokeList autoPopulateSeriesXXX baseOutlineStroke shape shapeList autoPopulateSeriesXXX baseShape The fill paint override (null permitted, deprecated from 1.0.6 onwards). A list of fill paints that apply to individual series (only referenced if paint is null). A flag that controls whether or not the per-series settings are autopopulated. The fill paint that is used if there is no other setting. The outline paint override (null permitted, deprecated from 1.0.6 onwards). A list of outline paints that apply to individual series (only referenced if outlinePaint is null). A flag that controls whether or not the per-series settings are autopopulated. The outline paint that is used if there is no other setting. The stroke override (null permitted, deprecated from 1.0.6 onwards). A list of stroke objects that apply to individual series (only referenced if stroke is null). A flag that controls whether or not the per-series settings are autopopulated. The stroke that is used if there is no other setting. The outline stroke override (null permitted, deprecated from 1.0.6 onwards). A list of outline strokes that apply to individual series (only referenced if outlineStroke is null). A flag that controls whether or not the per-series settings are autopopulated. The outline stroke override. The shape override (null permitted, deprecated from 1.0.6 onwards). A list of shapes that apply to individual series (only referenced if shape is null). A flag that controls whether or not the per-series settings are autopopulated. The shape that is used if there is no other setting. Table 35.1: Attributes for the AbstractRenderer class 1 You can still use them, but they may be removed in a future release of JFreeChart. CHAPTER 35. PACKAGE: ORG.JFREE.CHART.RENDERER 35.2.4 423 Setting Series Colours Renderers are responsible for drawing the data items within a plot, so this class provides attributes for controlling the colours that will be used. Colours are typically defined on a “per series” basis, and stored in a lookup table. There is a default mechanism to automatically populate the lookup table with default colours (using the DrawingSupplier interface). However, you can manually update the paint list at any time. First, you need to obtain a reference to the renderer(s) (note that many charts do not use more than one renderer). Here is the code for a CategoryPlot: CategoryPlot plot = (CategoryPlot) chart.getPlot(); AbstractRenderer r1 = (AbstractRenderer) plot.getRenderer(0); AbstractRenderer r2 = (AbstractRenderer) plot.getRenderer(1); The code is similar for charts that use XYPlot: XYPlot plot = (XYPlot) chart.getPlot(); AbstractRenderer r1 = (AbstractRenderer) plot.getRenderer(0); AbstractRenderer r2 = (AbstractRenderer) plot.getRenderer(1); To update the series paint used by a renderer: // change the paint for series 0, 1 and 2... r1.setSeriesPaint(0, Color.red); r1.setSeriesPaint(1, Color.green); r1.setSeriesPaint(2, Color.blue); 35.2.5 Paint The paint attribute defines the main colour used to identify a series in a chart: Attribute: Description: paint paintList The paint override (null permitted). Deprecated since 1.0.6. A list of paints that apply to individual series (only referenced if paint is null). A flag that controls whether or not the per-series settings are autopopulated (the default is true). The paint that is used if there is no other setting. autoPopulateSeriesPaint basePaint Table 35.2: Paint attributes for the AbstractRenderer class å public Paint getItemPaint(int row, int column); This method is called by JFreeChart to obtain a paint instance for each item that the renderer draws. By default, it calls lookupSeriesPaint(row) which checks the current paint setting for the series. If this is null and autoPopulateSeriesPaint is true, the drawing supplier is queried for a new paint instance, otherwise the default paint (getBasePaint()) is returned. You can override this method to return an arbitrary colour for any data item. å public Paint getSeriesPaint(int series); Returns the paint to use for all items in the specified series. Some renderers will also use the fill and/or outline paint attributes for the renderer. Override Paint The override paint attribute can be used to override the per-series and base settings, but is seldom used in practice (it defaults to null): å public void setPaint(Paint paint); [Deprecated, 1.0.6] Equivalent to setPaint(paint, true), see the next method for details. CHAPTER 35. PACKAGE: ORG.JFREE.CHART.RENDERER 424 å public void setPaint(Paint paint, boolean notify); [Deprecated, 1.0.6] Sets the override paint attribute and, if requested, sends a RendererChangeEvent to all registered listeners. A call to setPaint(Paint) forces the renderer to use the same colour for ALL series in a dataset. To achieve the same result with non-deprecated methods, you need to set the base paint and also switch of the auto-population of the per-series paint: renderer.setBasePaint(Color.BLUE); renderer.setAutoPopulateSeriesPaint(false); Per Series Paint The paint attribute is typically defined on a per-series basis with the following methods: å public void setSeriesPaint(int series, Paint paint); Equivalent to setSeriesPaint(series, paint, true), see the next method for details. å public void setSeriesPaint(int series, Paint paint, boolean notify); Sets the paint for a series and, if requested, sends a RendererChangeEvent to all registered listeners. Base Paint The base paint is used as the default when the override and series paint settings are null: å public Paint getBasePaint(); Returns the base paint (never null). The default value is defined by AbstractRenderer.DEFAULT PAINT (Color.blue). å public void setBasePaint(Paint paint); Equivalent to setBasePaint(paint, true), see the next method for details. å public void setBasePaint(Paint paint, boolean notify); Sets the base paint and, if requested, sends a RendererChangeEvent to all registered listeners. An IllegalArgumentException is thrown if paint is null. 35.2.6 Fill Paint The fill paint attribute defines the color used to fill shapes that are drawn by the renderer: Attribute: Description: fillPaint fillPaintList The fill paint override (null permitted). Deprecated as of 1.0.6. A list of fill paints that apply to individual series (only referenced if fillPaint is null). The fill paint that is used if there is no other setting. baseFillPaint Table 35.3: Fill paint attributes for the AbstractRenderer class å public Paint getItemFillPaint(int row, int column); This method is called to obtain the fill paint for each item that the renderer draws. By default, it simply returns the series fill paint obtained by calling getSeriesFillPaint(row). However, you can override this method to return an arbitrary color for any data item. å public Paint getSeriesFillPaint(int series); Returns the fill paint to use for all items in the specified series. Not all renderers will use the fill paint attribute. CHAPTER 35. PACKAGE: ORG.JFREE.CHART.RENDERER 425 Override Fill Paint The override fill paint attribute can be used to override the per-series and base settings (the default is null): å public void setFillPaint(Paint paint); [Deprecated, 1.0.6.] Equivalent to setFillPaint(paint, true), see the next method for details. å public void setFillPaint(Paint paint, boolean notify); [Deprecated, 1.0.6.] Sets the override fill paint attribute and, if requested, sends a RendererChangeEvent to all regis- tered listeners. Per Series Fill Paint The fill paint attribute is typically defined on a per-series basis with the following methods: å public void setSeriesFillPaint(int series, Paint paint); Equivalent to setSeriesFillPaint(series, paint, true), see the next method for details. å public void setSeriesFillPaint(int series, Paint paint, boolean notify); Sets the fill paint for a series and, if requested, sends a RendererChangeEvent to all registered listeners. Base Fill Paint The base fill paint is used as the default when the override and series paint settings are null: å public Paint getBaseFillPaint(); Returns the base fill paint (never null). The default value is Color.white. å public void setBaseFillPaint(Paint paint); Equivalent to setBaseFillPaint(paint, true), see the next method for details. å public void setBaseFillPaint(Paint paint, boolean notify); Sets the base fill paint and, if requested, sends a RendererChangeEvent to all registered listeners. An IllegalArgumentException is thrown if paint is null. 35.2.7 OutlinePaint The outline paint attribute defines the color used to outline shapes that are drawn by the renderer: Attribute: Description: outlinePaint outlinePaintList The outline paint override (null permitted). Deprecated as of 1.0.6. A list of outline paints that apply to individual series (only referenced if outlinePaint is null). The outline paint that is used if there is no other setting. baseOutlinePaint Table 35.4: Outline paint attributes for the AbstractRenderer class å public Paint getItemOutlinePaint(int row, int column); This method is called to obtain the outline paint for each item that the renderer draws. By default, it simply returns the series outline paint obtained by calling getSeriesOutlinePaint(row). However, you can override this method to return an arbitrary color for any data item. å public Paint getSeriesOutlinePaint(int series); Returns the outline paint to use for all items in the specified series. CHAPTER 35. PACKAGE: ORG.JFREE.CHART.RENDERER 426 Override Outline Paint The override outline paint attribute can be used to override the per-series and base settings (the default is null): å public void setOutlinePaint(Paint paint); [Deprecated, 1.0.6] Equivalent to setOutlinePaint(paint, true), see the next method for details. å public void setOutlinePaint(Paint paint, boolean notify); [Deprecated, 1.0.6] Sets the override outline paint attribute and, if requested, sends a RendererChangeEvent to all registered listeners. Per Series Outline Paint The outline paint attribute is typically defined on a per-series basis with the following methods: å public void setSeriesOutlinePaint(int series, Paint paint); Equivalent to setSeriesOutlinePaint(series, paint, true), see the next method for details. å public void setSeriesOutlinePaint(int series, Paint paint, boolean notify); Sets the outline paint for a series and, if requested, sends a RendererChangeEvent to all registered listeners. Base Outline Paint The base outline paint is used as the default when the override and series paint settings are null: å public Paint getBaseOutlinePaint(); Returns the base paint (never null). The default value is defined by AbstractRenderer.DEFAULT OUTLINE PAINT (Color.gray). å public void setBaseOutlinePaint(Paint paint); Equivalent to setBaseOutlinePaint(paint, true), see the next method for details. å public void setBaseOutlinePaint(Paint paint, boolean notify); Sets the base outline paint and, if requested, sends a RendererChangeEvent to all registered listeners. An IllegalArgumentException is thrown if paint is null. 35.2.8 Stroke The stroke attributes control the pen style (width and dash pattern among other things) used by the renderer for drawing lines: å public Stroke getItemStroke(int row, int column); Returns the stroke used for the specified item. This method simply returns the result from getSeriesStroke(row), but you can override it to implement a different behaviour. å public Stroke getSeriesStroke(int series); Returns the stroke to use for the specified series. Some renderers won’t use this at all, while other renderers may also make use of the outline stroke attribute—refer to the documentation for the specific renderer for more details. Override Stroke The override stroke attribute can be used to override the per-series and base settings, but is seldom used in practice (it defaults to null): å public void setStroke(Stroke stroke); [Deprecated, 1.0.6] Equivalent to setStroke(stroke, true), see the next method for details. å public void setStroke(Stroke stroke, boolean notify); [Deprecated, 1.0.6] Sets the override stroke and, if requested, sends a RendererChangeEvent to all registered listeners. CHAPTER 35. PACKAGE: ORG.JFREE.CHART.RENDERER 427 Per Series Stroke The stroke attribute is typically defined on a per series basis using the following method: å public void setSeriesStroke(int series, Stroke stroke); Equivalent to setSeriesStroke(series, stroke, true), see the next method for details. å public void setSeriesStroke(int series, Stroke stroke, boolean notify); Sets the stroke for the specified series and, if requested, sends a RendererChangeEvent to all registered listeners. You can set the stroke for a series to null, in which case the base stroke will be used for that series. Base Stroke The base stroke setting is used for any series where both the override and per series settings are not specified: å public Stroke getBaseStroke(); Returns the base stroke (never null). The default value is defined by AbstractRenderer.DEFAULT STROKE (BasicStroke(1.0f)). å public void setBaseStroke(Stroke stroke); Equivalent to setBaseStroke(stroke, true), see the next method for details. å public void setBaseStroke(Stroke stroke, boolean notify); Sets the base stroke and, if requested, sends a RendererChangeEvent to all registered listeners. 35.2.9 Outline Stroke The outline stroke attributes control the pen style (width and dash pattern among other things) used by the renderer for drawing shape outlines: å public Stroke getItemOutlineStroke(int row, int column); [Deprecated, 1.0.6] Returns the outline stroke used for the specified item. This method simply returns the result from getSeriesOutlineStroke(row), but you can override it to implement a different behaviour. å public Stroke getSeriesOutlineStroke(int series); [Deprecated, 1.0.6] Returns the outline stroke to use for the specified series. Some renderers won’t use this at all—refer to the documentation for the specific renderer for more details. Override Outline Stroke The override outline stroke attribute can be used to override the per-series and base settings, but is seldom used in practice (it defaults to null): å public void setOutlineStroke(Stroke stroke); Equivalent to setOutlineStroke(stroke, true), see the next method for details. å public void setOutlineStroke(Stroke stroke, boolean notify); Sets the override outline stroke and, if requested, sends a RendererChangeEvent to all registered listeners. Per Series Outline Stroke The outline stroke attribute is typically defined on a per series basis using the following method: å public void setSeriesOutlineStroke(int series, Stroke stroke); Equivalent to setSeriesOutlineStroke(series, stroke, true), see the next method for details. å public void setSeriesOutlineStroke(int series, Stroke stroke, boolean notify); Sets the outline stroke for the specified series and, if requested, sends a RendererChangeEvent to all registered listeners. You can set the outline stroke for a series to null, in which case the base outline stroke will be used for that series. CHAPTER 35. PACKAGE: ORG.JFREE.CHART.RENDERER 428 Base Outline Stroke The base outline stroke setting is used for any series where both the override and per series settings are not specified: å public Stroke getBaseOutlineStroke(); Returns the base outline stroke (possibly null). The default value is is BasicStroke(1.0f) (defined by the constant AbstractRenderer.DEFAULT OUTLINE STROKE). å public void setBaseOutlineStroke(Stroke stroke); Equivalent to setBaseOutlineStroke(stroke, true), see the next method for details. å public void setBaseOutlineStroke(Stroke stroke, boolean notify); Sets the base outline stroke and, if requested, sends a RendererChangeEvent to all registered listeners. If you set this to null, the renderer will not draw an outline. 35.2.10 Setting Series Shapes Renderers are initialised so that a range of default shapes are available if required. These are stored in a lookup table that is initially empty. The lookup table has two rows (one for the primary dataset, and one for the secondary dataset), and can have any number of columns (one per series). When the renderer requires a Shape, it uses the dataset index (primary or secondary) and the series index to read a shape from the lookup table. If the value is null, then the renderer turns to the DrawingSupplier for a new shape—the next shape is returned by the getNextShape() method. If you require more control over the shapes that are used for your plots, you can populate the lookup table yourself using the setSeriesShape(...) method. The shape you supply can be any instance of Shape, but should be centered on (0, 0) in Java2D space (so that JFreeChart can position the shape at any data point). Here is some sample code that sets four custom shapes for the primary dataset in an XYPlot: XYPlot plot = chart.getXYPlot(); XYItemRenderer r = plot.getRenderer(); if (r instanceof StandardXYItemRenderer) { StandardXYItemRenderer renderer = (StandardXYItemRenderer) r; renderer.setPlotShapes(true); renderer.setDefaultShapeFilled(true); renderer.setSeriesShape(0, new Ellipse2D.Double(-3.0, -3.0, 6.0, 6.0)); renderer.setSeriesShape(1, new Rectangle2D.Double(-3.0, -3.0, 6.0, 6.0)); GeneralPath s2 = new GeneralPath(); s2.moveTo(0.0f, -3.0f); s2.lineTo(3.0f, 3.0f); s2.lineTo(-3.0f, 3.0f); s2.closePath(); renderer.setSeriesShape(2, s2); GeneralPath s3 = new GeneralPath(); s3.moveTo(-1.0f, -3.0f); s3.lineTo(1.0f, -3.0f); s3.lineTo(1.0f, -1.0f); s3.lineTo(3.0f, -1.0f); s3.lineTo(3.0f, 1.0f); s3.lineTo(1.0f, 1.0f); s3.lineTo(1.0f, 3.0f); s3.lineTo(-1.0f, 3.0f); s3.lineTo(-1.0f, 1.0f); s3.lineTo(-3.0f, 1.0f); s3.lineTo(-3.0f, -1.0f); s3.lineTo(-1.0f, -1.0f); s3.closePath(); renderer.setSeriesShape(3, s3); } 35.2.11 Shape Many renderers (though not all) will display a shape at each data point, so this class includes a mechanism for storing the shapes that will be used. Be aware that any shapes you supply should be centred around the origin ((0, 0)), as this is assumed in the code that translates shapes into position at chart rendering time. For example, a rectangle centred at the origin would be Rectangle(-3.0, -4.0, 6.0, 8.0): CHAPTER 35. PACKAGE: ORG.JFREE.CHART.RENDERER 429 å public Shape getItemShape(int row, int column); Returns the shape to use for the specified item. This method simply returns the value from getSeriesShape(row), but you can override this if you want to return a custom shape for a specific item. å public Shape getSeriesShape(int series); Returns the shape to use for items in the specified series. Override Shape The override shape, if non-null, applies to all series: å public void setShape(Shape shape); [Deprecated, 1.0.6] Equivalent to setShape(shape, true), see the next method for details. å public void setShape(Shape shape, boolean notify); [Deprecated, 1.0.6] Sets the override shape and, if requested, sends a RendererChangeEvent to all registered listeners. Set this to null for no override. Series Shapes The renderer can store shape attributes on a per-series basis: å public void setSeriesShape(int series, Shape shape); Equivalent to setSeriesShape(series, shape, true), see the next method for details. å public void setSeriesShape(int series, Shape shape, boolean notify); Sets the shape for the specified series and, if requested, sends a RendererChangeEvent to all registered listeners. You can set the shape to null, in which case the base shape (see the next section) will be used for the specified series. Base Shape The base shape is used as the default if no override or series shape is specified: å public Shape getBaseShape(); Returns the current base shape (never null). The default base shape is a Rectangle(-3.0, -3.0, 6.0, 6.0). å public void setBaseShape(Shape shape); Equivalent to setBaseShape(shape, true), see the next method for details. å public void setBaseShape(Shape shape, boolean notify); Sets the base shape and, if requested, sends a RendererChangeEvent to all registered listeners. An IllegalArgumentException is thrown if shape is null. 35.2.12 Series Visibility By default, a renderer will display all the series in a dataset, but it is possible to change this behaviour by changing the series visibility flags—see table 35.5.2 Attribute: Description: seriesVisible The override flag (null permitted). This field is redundant and deprecated from version 1.0.6 onwards. A list of flags that apply to individual series (these are only referenced if seriesVisible is null). The default visibility for all series. seriesVisibleList baseSeriesVisible Table 35.5: Series visibility attributes for the AbstractRenderer class To determine the current visibility of an item or series: 2 Note that not all renderers respect these flags yet, but eventually they all will. CHAPTER 35. PACKAGE: ORG.JFREE.CHART.RENDERER 430 å public boolean getItemVisible(int series, int item); Returns true if the specified item should be displayed by the renderer, and false otherwise. The default implementation of this method just returns the value from isSeriesVisible(series). For different behaviour, subclass the renderer you are using and override this method. å public boolean isSeriesVisible(int series); Returns true if the specified series is visible, and false otherwise. This method checks the override, per-series and base settings as appropriate. Override Flag An override flag is provided for the series visibility. This is mainly for completeness, typically you won’t need to set this (it defaults to null). This flag is deprecated from version 1.0.6 onwards. å public Boolean getSeriesVisible(); [Deprecated 1.0.6] Returns the override flag for series visibility. If this is non-null, the isSeriesVisible(int) method returns the boolean value of this flag. å public void setSeriesVisible(Boolean visible); [Deprecated 1.0.6] Equivalent to setSeriesVisible(visible, true), see the method below. å public void setSeriesVisible(Boolean visible, boolean notify); [Deprecated 1.0.6] Sets the override flag for series visibility and, if requested, sends a RendererChangeEvent to all registered listeners. If you don’t need an override, set this flag to null. Per Series Flags The per-series visibility flags allow complete control over which series are displayed in a chart (provided that the renderer subclass supports this feature): å public Boolean getSeriesVisible(int series); Returns the flag that controls the visibility of the specified series. This can be null, in which case the base level setting will apply. å public void setSeriesVisible(int series, Boolean visible); Calls setSeriesVisible(series, visible, true)—see below. å public void setSeriesVisible(int series, Boolean visible, boolean notify); Sets the visibility flag for the specified series and, if requested, sends a RendererChangeEvent to all registered listeners. This flag can be set to null, in which case the base level flag applies. Base Flag The base flag, which defaults to true, applies when there is no override flag set and no series level flag set: å public boolean getBaseSeriesVisible(); Returns the default series visibility. å public void setBaseSeriesVisible(boolean visible); Calls setBaseSeriesVisible(visible, true). See the next method description for details. å public void setBaseSeriesVisible(boolean visible, boolean notify); Sets the default series visibility and, if requested, sends a RendererChangeEvent to all registered listeners. 35.2.13 Series Visibility in Legend By default, a renderer will create legend items for all series when asked (see the createLegendItems() method implemented by AbstractCategoryItemRenderer and AbstractXYItemRenderer), but it is possible to change this behaviour by changing the series visibility flags—see table 35.6. To determine the current visibility of a series in the legend: CHAPTER 35. PACKAGE: ORG.JFREE.CHART.RENDERER Attribute: Description: seriesVisibleInLegend seriesVisibleInLegendList The override flag (null permitted). Deprecated as of version 1.0.6. A list of flags that apply to individual series (these are only referenced if seriesVisibleInLegend is null). The default legend visibility for all series. baseSeriesVisibleInLegend 431 Table 35.6: Legend visibility attributes for the AbstractRenderer class å public boolean isSeriesVisibleInLegend(int series); Returns true if the specified series is visible, and false otherwise. This method checks the override, per-series and base level flags as appropriate (take care not to confuse this method with getSeriesVisibleInLegend(int), which only returns the series level flag). Override Flag An override flag is provided for the series visibility in the legend. This is mainly for completeness, typically you won’t need to set this (it defaults to null): å public Boolean getSeriesVisibleInLegend(); [Deprecated, 1.0.6] Returns the override flag for series visibility in the legend. This may be null. å public void setSeriesVisibleInLegend(Boolean visible); [Deprecated, 1.0.6] Equivalent to setSeriesVisibleInLegend(visible, true), see the next method for details. å public void setSeriesVisibleInLegend(Boolean visible, boolean notify); [Deprecated, 1.0.6] Sets the override flag and, if requested, sends a RendererChangeEvent to all registered listeners. You can set the override flag to null (the default) if you want the per-series flags to take effect. Per Series Settings The per-series visibility flags allow complete control over which series are displayed in the legend: å public Boolean getSeriesVisibleInLegend(int series); Returns the per-series flag controlling visibility in the legend, for the specified series. Don’t confuse this method with the similarly named isSeriesVisibleInLegend(int) method. å public void setSeriesVisibleInLegend(int series, Boolean visible); Equivalent to setSeriesVisibleInLegend(series, visible, true), see the next method for de- tails. å public void setSeriesVisibleInLegend(int series, Boolean visible, boolean notify); Sets the flag controlling visibility of the specified series in the legend and, if requested, sends a RendererChangeEvent to all registered listeners. If the flag for a series is set to null, the value defined by the base flag (see the next section) will apply for that series when calling the isSeriesVisibleInLegend(int) method. Base Flag The base flag provides the default visibility for a series in the legend. This value (the default is true) is used only if the override and per-series flags are both null: å public boolean getBaseSeriesVisibleInLegend(); Returns the base flag controlling the visibility of series in the legend. This value is returned by the isSeriesVisibleInLegend(int) method when both the override flag and the series flag are null. å public void setBaseSeriesVisibleInLegend(boolean visible); Equivalent to setBaseSeriesVisibleInLegend(visible, true), see the next method for details. å public void setBaseSeriesVisibleInLegend(boolean visible, boolean notify); Sets the base flag controlling the visibility of series in the legend and sends a RendererChangeEvent to all registered listeners. CHAPTER 35. PACKAGE: ORG.JFREE.CHART.RENDERER 35.2.14 432 Item Label Attributes All renderers use a common set of item label attributes (some renderers may ignore these settings): Attribute: Description: itemLabelsVisible The itemLabelsVisible override flag (null permitted). Deprecated as of 1.0.6. A list of flags that apply to individual series (only referenced if itemLabelsVisible is null). The flag that is used if there is no other setting. itemLabelsVisibleList baseItemLabelsVisible itemLabelFont The itemLabelFont override (null permitted). Deprecated as of 1.0.6. A list of fonts that apply to individual series (only referenced if itemLabelFont is null). The font that is used if there is no other setting. itemLabelFontList baseItemLabelFont itemLabelPaint The itemLabelPaint override (null permitted). Deprecated as of 1.0.6. A list of paints that apply to individual series (only referenced if itemLabelPaint is null). The font that is used if there is no other setting. itemLabelPaintList baseItemLabelPaint itemLabelAnchor The itemLabelAnchor override (null permitted). Deprecated as of 1.0.6. A list of anchors that apply to individual series (only referenced if itemLabelAnchor is null). The anchor that is used if there is no other setting. itemLabelAnchorList baseItemLabelAnchor itemLabelTextAnchor itemLabelTextAnchorList baseItemLabelTextAnchor itemLabelRotationAnchor itemLabelRotationAnchorList baseItemLabelRotationAnchor itemLabelAngle itemLabelAngleList baseItemLabelAngle The itemLabelTextAnchor override (null permitted). Deprecated as of 1.0.6. A list of text anchors that apply to individual series (only referenced if itemLabelTextAnchor is null). The text anchor that is used if there is no other setting. The itemLabelRotationAnchor override (null permitted). Deprecated as of 1.0.6. A list of rotation anchors that apply to individual series (only referenced if itemLabelRotationAnchor is null). The anchor that is used if there is no other setting. The itemLabelAngle override (null permitted). Deprecated as of 1.0.6. A list of angles that apply to individual series (only referenced if itemLabelAnchor is null). The angle that is used if there is no other setting. Table 35.7: Attributes for the AbstractRenderer class 35.2.15 Item Label Visibility The item label visibility attributes control the visibility of individual item labels: Attribute: Description: itemLabelsVisible itemLabelsVisibleList The override visibility flag (null permitted). A list of flags that apply to individual series (these are only referenced if itemLabelsVisible is null). The default item label visibility for all series. baseItemLabelsVisible Table 35.8: Item label visibility attributes for the AbstractRenderer class å public boolean isItemLabelVisible(int row, int column); Returns true if the item label is visible for the specified item, and false otherwise. Note that CHAPTER 35. PACKAGE: ORG.JFREE.CHART.RENDERER 433 the row index corresponds to the series and the column index corresponds to the item within the series (or the category). The default implementation of this method simply returns the value from isSeriesItemLabelsVisible(row), but you can override the method to control label visibility on a per-item basis. å public boolean isSeriesItemLabelsVisible(int series); Returns true if item labels are visible for the specified series, and false otherwise. Override Item Label Visibility The override item labels visible attribute can be used to override the per-series and base settings, but is seldom used in practice (it defaults to null): å public void setItemLabelsVisible(boolean visible); [Deprecated, 1.0.6] Equivalent to setItemLabelsVisible(Boolean.valueOf(visible), see the next method for details. å public void setItemLabelsVisible(Boolean visible); [Deprecated, 1.0.6] Equivalent to setItemLabelsVisible(visible, true), see the next method for details. å public void setItemLabelsVisible(Boolean visible, boolean notify); [Deprecated, 1.0.6] Sets the override item labels visible flag and, if requested, sends a RendererChangeEvent to all registered listeners. Per Series Item Label Visibility The item labels attribute can be defined on a per series basis using the following methods: å public void setSeriesItemLabelsVisible(int series, boolean visible); Equivalent to setSeriesStroke(series, Boolean.valueOf(visible)), see the next method for de- tails. å public void setSeriesItemLabelsVisible(int series, Boolean visible); Equivalent to setSeriesStroke(series, Boolean.valueOf(visible), true), see the next method for details. å public void setSeriesItemLabelsVisible(int series, Boolean visible, boolean notify); Sets the item labels visible flag for the specified series and, if requested, sends a RendererChangeEvent to all registered listeners. You can set the flag for a series to null, in which case the base item labels visible flag will be used for that series. Base Item Label Visibility The base item labels visible setting is used for any series where both the override and per series settings are not specified: å public Boolean getBaseItemLabelsVisible(); Returns the base item labels flag. A null value should be interpreted as Boolean.FALSE.3 å public void setBaseItemLabelsVisible(boolean visible); Equivalent to setBaseItemLabelsVisible(Boolean.valueOf(visible)), see the next method for details. å public void setBaseItemLabelsVisible(Boolean visible); Equivalent to setBaseItemLabelsVisible(visible, true), see the next method for details. å public void setBaseItemLabelsVisible(Boolean visible, boolean notify); Sets the base item labels visible flag and, if requested, sends a RendererChangeEvent to all registered listeners. You can set this flag to null, but that will be interpreted as equivalent to Boolean.FALSE. CHAPTER 35. PACKAGE: ORG.JFREE.CHART.RENDERER Attribute: Description: itemLabelFont itemLabelFontList The override font (null permitted). Deprecated as of 1.0.6. A list of fonts that apply to individual series (these are only referenced if itemLabelFont is null). The default item label font for all series. baseItemLabelFont 434 Table 35.9: Item label font attributes for the AbstractRenderer class 35.2.16 Item Label Font The item label font attributes control the font that is used by the renderer to draw item labels. For most applications, a single font will be used for all labels, so you can just set the base item label font, and leave the override and per series settings at their default null values. To determine the item label font: å public Font getItemLabelFont(int row, int column); Returns the item label font for the specified item. Override Item Label Font The override item label font overrides the per series and base level settings, unless it is null (which is the default). å public Font getItemLabelFont(); [Deprecated, 1.0.6] Returns the override item label font. The default value is null. å public void setItemLabelFont(Font font); [Deprecated, 1.0.6] Equivalent to setItemLabelFont(font, true)—see the next method. å public void setItemLabelFont(Font font, boolean notify); [Deprecated, 1.0.6] Sets the override item label font and, if requested, sends a RendererChangeEvent to all registered listeners. Per Series Item Label Font To control the item label font on a per series basis: å public Font getSeriesItemLabelFont(int series); Returns the item label font for the specified series, or null if no font has been explicitly set for the series. å public void setSeriesItemLabelFont(int series, Font font); Equivalent to setSeriesItemLabelFont(series, font, true)—see the next method. å public void setSeriesItemLabelFont(int series, Font font, boolean notify); Sets the item label font for a series and, if requested, sends a RendererChangeEvent to all regis- tered listeners. Base Item Label Font The base item label font is used when no per series or override settings are in place (which is the default): å public Font getBaseItemLabelFont(); Returns the base item label font (never null). The default is Font("SansSerif", Font.PLAIN, 10). å public void setBaseItemLabelFont(Font font); Equivalent to setBaseItemLabelFont(font, true)—see the next method. å public void setBaseItemLabelFont(Font font, boolean notify); Sets the base item label font and, if requested, sends a RendererChangeEvent to all registered listeners. 3 This field should have been defined as a boolean, but is now part of the published API so we have to support it. CHAPTER 35. PACKAGE: ORG.JFREE.CHART.RENDERER 35.2.17 435 Item Label Paint The item label paint attributes control the paint that is used by the renderer to draw item labels. For most applications, a single paint will be used for all labels, so you can just set the base item label paint, and leave the override and per series settings at their default null values. Attribute: Description: itemLabelPaint itemLabelPaintList The override paint (null permitted). Deprecated as of 1.0.6. A list of paints that apply to individual series (these are only referenced if itemLabelPaint is null). The default item label paint for all series. baseItemLabelPaint Table 35.10: Item label paint attributes for the AbstractRenderer class To determine the item label paint for an item: å public Paint getItemLabelPaint(int row, int column); Returns the item label paint (never null) for an item. Override Item Label Paint The override item label font overrides the per series and base settings, unless it is null (which is the default): å public Paint getItemLabelPaint(); [Deprecated, 1.0.6] Returns the override item label font. The default value is null. å public void setItemLabelPaint(Paint paint); [Deprecated, 1.0.6] Equivalent to setItemLabelPaint(paint, true)—see the next method. å public void setItemLabelPaint(Paint paint, boolean notify); [Deprecated, 1.0.6] Sets the override item label paint and, if requested, sends a RendererChangeEvent to all registered listeners. Per Series Item Label Paint To control the item label paint on a per series basis: å public Paint getSeriesItemLabelPaint(int series); Returns the item label paint (possibly null) for a series. å public void setSeriesItemLabelPaint(int series, Paint paint); Equivalent to setSeriesItemLabelPaint(series, paint, true)—see the next method. å public void setSeriesItemLabelPaint(int series, Paint paint, boolean notify); Sets the item label paint for a series and, if requested, sends a RendererChangeEvent to all registered listeners. Base Item Label Paint The base item label paint is the default paint used to draw the item labels (if they are visible). It is used when there is no per-series or override setting: å public Paint getBaseItemLabelPaint(); Returns the default item label paint. The default value is Color.black. å public void setBaseItemLabelPaint(Paint paint); Equivelant to setBaseItemLabelPaint(paint, true)—see the next method. å public void setBaseItemLabelPaint(Paint paint, boolean notify); Sets the base item label paint and, if notify is true, sends a RendererChangeEvent to all registered listeners. If paint is null, this method throws an IllegalArgumentException. CHAPTER 35. PACKAGE: ORG.JFREE.CHART.RENDERER 35.2.18 436 Positive Item Label Position The positive item label position attributes (see table 35.11) control the position of item labels for those items that have a data value that is positive. Attribute: Description: positiveItemLabelPosition The positiveItemLabelPosition override flag (null permitted). Deprecated as of 1.0.6. A list of positions that apply to individual series (only referenced if positiveItemLabelPosition is null). The base position for all series, the default value is ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.BOTTOM CENTER) seriesPositiveItemLabelPositionList basePositiveItemLabelPosition Table 35.11: Positive item label position attributes To determine the label position for an item with a positive value, JFreeChart calls the following method: å public ItemLabelPosition getPositiveItemLabelPosition(int row, int column); Returns the position for the specified item. The return value is derived from the override, per series and base level settings. Override Positive Item Label Position The override positive item label position attribute provides a mechanism to override all other settings (this is rarely required): å public ItemLabelPosition getPositiveItemLabelPosition(); [Deprecated, 1.0.6] Returns the positive item label position override. The default value is null. å public void setPositiveItemLabelPosition(ItemLabelPosition position); [Deprecated, 1.0.6] Equivalent to setPositiveItemLabelPosition(position, true)—see the next method. å public void setPositiveItemLabelPosition(ItemLabelPosition position, boolean notify); [Deprecated, 1.0.6] Sets the positive item label position for the specified series and, if requested, sends a RendererChangeEvent to all registered listeners. Per Series Positive Item Label Position The per series positive item label positions apply when no override is set. å public ItemLabelPosition getSeriesPositiveItemLabelPosition(int series); Returns the positive item label position for the specified series (this may be null). å public void setSeriesPositiveItemLabelPosition(int series, ItemLabelPosition position); Equivalent to setSeriesPositiveItemLabelPosition(series, position, true)—see the next method. å public void setSeriesPositiveItemLabelPosition(int series, ItemLabelPosition position, boolean notify); Sets the positive item label position for the specified series and, if requested, sends a RendererChangeEvent to all registered listeners. Base Positive Item Label Position The base setting for the positive item label position attribute is used when no per series or override setting is specified: å public ItemLabelPosition getBasePositiveItemLabelPosition(); Returns the base positive item label position. The default value is ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.BOTTOM CENTER). CHAPTER 35. PACKAGE: ORG.JFREE.CHART.RENDERER 437 å public void setBasePositiveItemLabelPosition(ItemLabelPosition position); Equivalent to setBasePositiveItemLabelPosition(position, true)—see the next method. å public void setBasePositiveItemLabelPosition(ItemLabelPosition position, boolean notify); Sets the base positive item label position and, if requested, sends a RendererChangeEvent to all registered listeners. 35.2.19 Negative Item Label Position The negative item label position attributes (see table 35.12) control the position of item labels for those items that have a data value that is negative. Attribute: Description: negativeItemLabelPosition The negativeItemLabelPosition override flag (null permitted). Deprecated as of 1.0.6. A list of positions that apply to individual series (only referenced if negativeItemLabelPosition is null). The base position for all series, the default value is ItemLabelPosition(ItemLabelAnchor.OUTSIDE6, TextAnchor.TOP CENTER)) seriesNegativeItemLabelPositionList baseNegativeItemLabelPosition Table 35.12: Negative item label position attributes To determine the label position for an item with a negative value, JFreeChart calls the following method: å public ItemLabelPosition getNegativeItemLabelPosition(int row, int column); Returns the position for the specified item. The return value is derived from the override, per series and base level settings. Override Negative Item Label Position The override negative item label position attribute provides a mechanism to override all other settings (this is rarely required): å public ItemLabelPosition getNegativeItemLabelPosition(); [Deprecated, 1.0.6] Returns the negative item label position override. The default value is null. å public void setNegativeItemLabelPosition(ItemLabelPosition position); [Deprecated, 1.0.6] Equivalent to setNegativeItemLabelPosition(position, true)—see the next method. å public void setNegativeItemLabelPosition(ItemLabelPosition position, boolean notify); [Deprecated, 1.0.6] Sets the negative item label position for the specied series and, if requested, sends a RendererChangeEvent to all registered listeners. Per Series Negative Item Label Position The per series negative item label positions apply when no override is set: å public ItemLabelPosition getSeriesNegativeItemLabelPosition(int series); Returns the negative item label position for the specied series (this may be null). å public void setSeriesNegativeItemLabelPosition(int series, ItemLabelPosition position); Equivalent to setSeriesNegativeItemLabelPosition(series, position, true)—see the next method. å public void setSeriesNegativeItemLabelPosition(int series, ItemLabelPosition position, boolean notify); Sets the negative item label position for the specified series and, if requested, sends a RendererChangeEvent to all registered listeners. CHAPTER 35. PACKAGE: ORG.JFREE.CHART.RENDERER 438 Base Negative Item Label Position The base setting for the negative item label position attribute is used when no per series or override setting is specied: å public ItemLabelPosition getBaseNegativeItemLabelPosition(); Returns the base negative item label position. The default value is ItemLabelPosition(ItemLabelAnchor.OUTSIDE6, TextAnchor.TOP CENTER). å public void setBaseNegativeItemLabelPosition(ItemLabelPosition position); Equivalent to setBaseNegativeItemLabelPosition(position, true)—see the next method. å public void setBaseNegativeItemLabelPosition(ItemLabelPosition position, boolean notify); Sets the base negative item label position and, if requested, sends a RendererChangeEvent to all registered listeners. 35.2.20 Item Label Anchor Offset The item label anchor offset allows some control over the position of item labels, by controlling how far the anchor point is shifted from its natural position: å public double getItemLabelAnchorOffset(); Returns the offset (in Java2D units). The default value is 2.0. å public void setItemLabelAnchorOffset(double offset); Sets the item label anchor offset and sends a RendererChangeEvent to all registered listeners. The following utility method calculates the item label anchor point relative to the given (x, y) location: å protected Point2D calculateLabelAnchorPoint(ItemLabelAnchor anchor, double x, double y, PlotOrientation orientation); Calculates the item label anchor point relative to the specified data point. Some renderers override this method if there is a more natural way to calculate the anchor point (for instance, the BarRenderer can calculate the anchor points relative to the bar rectangle). 35.2.21 Entity Generation Support for tooltips, mouse events, and URLs in HTML image maps relies on the generation of a ChartEntity for each item in a series. In some situations, it can be useful to generate entities for a subset of the series in a dataset only. All renderers inherit a set of flags that make this possible. Attribute: Description: createEntities The createEntities override flag (null permitted). Deprecated as of 1.0.6. A list of flags that apply to individual series (only referenced if createEntities is null). The default flag for all series. seriesCreateEntitiesList baseCreateEntities Table 35.13: Attributes for the AbstractRenderer class To determine whether or not an entity should be created for an item in a chart, JFreeChart calls the following method: å public boolean getItemCreateEntity(int series, int item); Returns true if an entity should be created for the specified item, and false otherwise. The result is determined by looking at the override, per series and base level settings for this attribute. CHAPTER 35. PACKAGE: ORG.JFREE.CHART.RENDERER 439 Override Create Entities Flag The override create entities flag can be used to override the per series and base level flags. It is rarely needed, and is typically left at its default value of null: å public Boolean getCreateEntities(); [Deprecated, 1.0.6] Returns the override flag. This is null by default. å public void setCreateEntities(Boolean create); [Deprecated, 1.0.6] Equivalent to setCreateEntities(create, true)—see the next method. å public void setCreateEntities(Boolean create, boolean notify); [Deprecated, 1.0.6] Sets the override flag (null is permitted) and, if requested, sends a RendererChangeEvent to all registered listeners. Per Series Create Entities Flag The per series flags apply when no override is defined. If the per series flag is null, then the base flag will be used. å public Boolean getSeriesCreateEntities(int series); Returns the create entities flag for the specified series (possible null). å public void setSeriesCreateEntities(int series, Boolean create); Equivalent to setSeriesCreateEntities(series, create, true)—see the next method. å public void setSeriesCreateEntities(int series, Boolean create, boolean notify); Sets the create series flag for the specified series (null is permitted) and, if requested, sends a RendererChangeEvent to all registered listeners. Base Create Entities Flag The base create entities flag is used when no other setting is defined. å public boolean getBaseCreateEntities(); Returns the base create entities flag. The default value is true. å public void setBaseCreateEntities(boolean create); Equivalent to setBaseCreateEntities(true)—see the next method. å public void setBaseCreateEntities(boolean create, boolean notify); Sets the base create entities flag and, if requested, sends a RendererChangeEvent to all registered listeners. 35.2.22 Equals, Cloning and Serialization The equals() method is overridden: å public boolean equals(Object obj); Returns true if this renderer is equal to obj, and false otherwise. An object is considered “equal” to this renderer if: • it is not null; • it is an instance of AbstractRenderer; • it has the same attribute settings as this renderer; Registered listeners are not included in the equality test. By design, all renderers should be Cloneable and Serializable. Some Java classes (particularly those that implement the Java2D Shape and Paint interfaces) do not provide built-in support for cloning and serialization. Where possible, special code has been written to handle these cases. CHAPTER 35. PACKAGE: ORG.JFREE.CHART.RENDERER 35.2.23 440 Notes Some points to note: • subclasses include AbstractCategoryItemRenderer and AbstractXYItemRenderer. 35.3 AreaRendererEndType 35.3.1 Overview This class defines the tokens that can be used to specify the representation of the ends of an area chart. There are three tokens defined, as listed in table 35.14. Token: Description: AreaRendererEndType.TAPER AreaRendererType.TRUNCATE AreaRendererType.LEVEL Taper down to zero. Truncates at the first and last values. Fill to the edges of the chart level with the first and last data values. Table 35.14: AreaRendererEndType tokens 35.3.2 Usage The AreaRenderer class has a method named setEndType() that accepts the tokens defined by this class. 35.4 DefaultPolarItemRenderer 35.4.1 Overview A default renderer for use by the PolarPlot class. This class extends AbstractRenderer and implements the PolarItemRenderer interface. 35.4.2 Constructor To create a new renderer: å public DefaultPolarItemRenderer(); Creates a new renderer instance. 35.4.3 General Attributes Most attributes are inherited from the AbstractRenderer class. To control whether or not each series is drawn as a “filled” polygon: å public boolean isSeriesFilled(int series); Returns true if the area “inside” the series should be filled, and false otherwise. å public void setSeriesFilled(int series, boolean filled); Sets the flag that controls whether or not the specified series is “filled”. By default, the setting is false. CHAPTER 35. PACKAGE: ORG.JFREE.CHART.RENDERER 35.4.4 441 Other Methods The remaining methods are called by JFreeChart—you won’t normally call these methods directly. To find the plot that the renderer is assigned to: å public PolarPlot getPlot(); Returns the plot that the renderer is assigned to. å public void setPlot(PolarPlot plot); Sets the plot that the renderer is assigned to. Typically the plot will set this when the renderer is added to the plot. å public DrawingSupplier getDrawingSupplier(); A convenience method that returns the drawing supplier from the plot that the renderer is assigned to. å public LegendItem getLegendItem(int series); Returns a legend item for the specified series. å public void drawAngularGridLines(Graphics2D g2, PolarPlot plot, List ticks, Rectangle2D dataArea); Draws the gridlines representing the angles around the plot. å public void drawRadialGridLines(Graphics2D g2, PolarPlot plot, ValueAxis radialAxis, List ticks, Rectangle2D dataArea); Draws the circular gridlines showing the units along the axis. å public void drawSeries(Graphics2D g2, Rectangle2D dataArea, PlotRenderingInfo info, PolarPlot plot, XYDataset dataset, int seriesIndex); Draws a series within the specified dataArea. 35.4.5 Equals, Cloning and Serialization This class overrides the equals() method: å public boolean equals(Object obj); Tests this renderer for equality with an arbitrary object. Instances of this class are Cloneable and Serializable. See Also PolarPlot. 35.5 GrayPaintScale 35.5.1 Overview A PaintScale implementation that returns shades of gray to represent the values in a range. This class was first introduced in JFreeChart version 1.0.4. 35.5.2 Constructors To create a new instance: å public GrayPaintScale(); [1.0.4] Equivalent to GrayPaintScale(0.0, 1.0)—see the next constructor. å public GrayPaintScale(double lowerBound, double upperBound); [1.0.4] Creates a new scale covering the specified value range. CHAPTER 35. PACKAGE: ORG.JFREE.CHART.RENDERER 35.5.3 442 Methods The following methods are defined: å public double getLowerBound(); [1.0.4] Returns the lower bound for the value range. å public double getUpperBound(); [1.0.4] Returns the upper bound for the value range. å public Paint getPaint(double value); [1.0.4] Returns a shade of gray for the specified value. A value at the lower bound will return black, a value at the upper bound will return white. 35.5.4 Equals, Cloning and Serialization This class overrides the equals() method: å public boolean equals(Object obj); [1.0.4] Tests this paint scale for equality with an arbitrary object. 35.5.5 Notes This class can be used with the XYBlockRenderer class. See Also PaintScale, PaintScaleLegend. 35.6 LookupPaintScale 35.6.1 Overview A PaintScale implementation that uses a lookup table to convert values to corresponding Paint instances. This class is intended for use by the XYBlockRenderer class. This class was first introduced in JFreeChart version 1.0.4. 35.6.2 Constructors To create a new instance: å public LookupPaintScale(); [1.0.4] Equivalent to LookupPaintScale(0.0, 1.0, Color.lightGray)—see the next constructor. å public LookupPaintScale(double lowerBound, double upperBound, Paint defaultPaint); [1.0.4] Creates a new scale covering the specified range and with the given default paint. If defaultPaint is null, this method throws an IllegalArgumentException. 35.6.3 Methods The following methods are defined: å public Paint getDefaultPaint(); [1.0.4] Returns the default paint, as specified in the constructor. This is never null. å public double getLowerBound(); [1.0.4] Returns the lower bound for the value range. å public double getUpperBound(); [1.0.4] Returns the upper bound for the value range. To fetch a Paint instance from the lookup table: CHAPTER 35. PACKAGE: ORG.JFREE.CHART.RENDERER 443 å public Paint getPaint(double value); [1.0.4] Returns the color for the specified value. For any value outside the bounds specified in the constructor, this method will return getDefaultPaint(). To add a new entry to the lookup table: å public void add(Number n, Paint p); [1.0.4] Adds a new entry to the lookup table (or replaces an existing entry if n matches an existing value). The entries are stored in ascending order by value—a look up for a given value will return p if the value is greater than or equal to n, but less than the value for the next entry in the lookup table). 35.6.4 Equals, Cloning and Serialization This class overrides the equals() method: å public boolean equals(Object obj); [1.0.4] Tests this paint scale for equality with an arbitrary object. Instances of this class are Cloneable and Serializable. 35.6.5 Notes Some points to note: • this class is designed for use with the XYBlockRenderer class; • a couple of demos (XYBlockRendererDemo1-2.java) are included in the JFreeChart demo collection. See Also PaintScale, PaintScaleLegend. 35.7 NotOutlierException 35.7.1 Overview An exception that is, in fact, never used in JFreeChart. 35.8 Outlier 35.8.1 Overview Represents an outlier in a box-and-whisker plot. Instances of this class are created on a temporary basis during chart drawing. 35.8.2 Constructor To create a new instance: å public Outlier(double xCoord, double yCoord, double radius); Creates a new outlier at the specified coordinates (in Java2D space). CHAPTER 35. PACKAGE: ORG.JFREE.CHART.RENDERER 35.8.3 444 Methods The following methods are defined: å public Point2D getPoint(); Returns the location of the outlier, in Java2D space. å public void setPoint(Point2D point); Sets the location of the outlier, in Java2D space. å public double getX(); Returns the x-coordinate for the outlier, in Java2D space. å public double getY(); Returns the y-coordinate for the outlier, in Java2D space. å public double getRadius(); Returns the radius of the outlier, in Java2D units. å public void setRadius(double radius); Sets the radius of the outlier, in Java2D units. å public int compareTo(Object o); Compares this Outlier to an arbitrary object. å public boolean overlaps(Outlier other); Tests if this outlier overlaps with the specified outlier. å public String toString(); Returns a string representation of this outlier, useful for debugging. See Also BoxAndWhiskerRenderer, XYBoxAndWhiskerRenderer. 35.9 OutlierList 35.9.1 Overview Represents a collection of outliers for a single item in a box-and-whisker plot. See Also Outlier, OutlierListCollection. 35.10 OutlierListCollection 35.10.1 Overview Represents a collection of outlier lists for a box-and-whisker plot. See Also OutlierList. 35.11 PaintScale 35.11.1 Overview An interface used by the XYBlockRenderer class to convert values (within a certain range) to Paint instances. Current implementations include: • GrayPaintScale; • LookupPaintScale; This interface was first introduced in JFreeChart version 1.0.4. CHAPTER 35. PACKAGE: ORG.JFREE.CHART.RENDERER 35.11.2 445 Interface Methods This interface defines the following methods: å public double getLowerBound(); [1.0.4] Returns the lower bound of the value range. å public double getUpperBound(); [1.0.4] Returns the upper bound of the value range. å public Paint getPaint(double value); [1.0.4] Returns the color associated with the specified value. If value is outside the range getLowerBound() to getUpperBound(), the behaviour is implementation dependent—check the documentation for the implementing class for details. See Also PaintScaleLegend. 35.12 PolarItemRenderer 35.12.1 Overview A renderer that is used by the PolarPlot class. The DefaultPolarItemRenderer class provides an implementation of this interface. 35.12.2 Change Listeners You can register any number of RendererChangeListener objects with the renderer and they will receive notification of any changes to the renderer: å public void addChangeListener(RendererChangeListener listener); Registers a listener with the renderer. å public void removeChangeListener(RendererChangeListener listener); Deregisters a listener so that it no longer receives change notifications from the renderer. It is not common that you need to do this yourself, but the mechanism is used by the PolarPlot class to monitor changes to the renderer (in order to trigger automatic chart updates). 35.12.3 Methods To create a legend item for a series (this method is called by the plot): å public LegendItem getLegendItem(int series); Creates a legend item for the specified series. To draw the representation of a series (this method is called by the plot): å public void drawSeries(Graphics2D g2, Rectangle2D dataArea, PlotRenderingInfo info, PolarPlot plot, XYDataset dataset, int seriesIndex); Draws a series within the specified dataArea. To draw the angle grid lines (this method is called by the plot): å public void drawAngularGridLines(Graphics2D g2, PolarPlot plot, List ticks, Rectangle2D dataArea); Draws the angle gridlines for the plot. å public void drawRadialGridLines(Graphics2D g2, PolarPlot plot, ValueAxis radialAxis, List ticks, Rectangle2D dataArea); Draws the radius (circular) gridlines for the plot. å public PolarPlot getPlot(); Returns the plot that the renderer is assigned to (or null). CHAPTER 35. PACKAGE: ORG.JFREE.CHART.RENDERER 446 å public void setPlot(PolarPlot plot); Sets the plot that the renderer is assigned to. Typically the plot will set this itself when the renderer is added to the plot. 35.13 RendererState 35.13.1 Overview A base class for maintaining state information that is initialised at the start of the chart drawing process, and passed to each invocation of the renderer’s drawItem() method. Subclasses include: • CategoryItemRendererState; • XYItemRendererState. 35.13.2 Constructors To create a new instance: å public RendererState(PlotRenderingInfo info); Creates a new instance that maintains a reference to the plot rendering info (which may be null). 35.13.3 Methods This class defines two methods: å public PlotRenderingInfo getInfo(); Returns the object that collects plot rendering information for the current chart drawing. If this is null, no information is recorded. å public EntityCollection getEntityCollection(); Returns the object that collects chart entity information for the current rendering. This may be null, in which case no entity information is recorded. Chart entities are used to support tooltips, drill-down charts and HTML image maps. 35.13.4 Equals, Cloning and Serialization As this class is intended to represent temporary state information, it is neither cloneable nor serializable, and it does not override the equals() method. See Also CategoryItemRendererState, XYItemRendererState. 35.14 WaferMapRenderer 35.14.1 Overview A renderer used by the WaferMapPlot class. Chapter 36 Package: org.jfree.chart.renderer.category 36.1 Overview This package contains interfaces and classes that are used to implement renderers for the CategoryPlot class. Renderers offer a lot of scope for changing the appearance of your charts, either by changing the attributes of an existing renderer, or by implementing a completely new renderer. 36.2 AbstractCategoryItemRenderer 36.2.1 Overview A base class (extending AbstractRenderer) that can be used to implement a new CategoryItemRenderer. Subclasses include: • AreaRenderer; • BarRenderer; • LevelRenderer; • LineAndShapeRenderer. To create a CategoryItemRenderer implementation requires a lot of methods to be written—by extending this base class, you can save yourself a lot of effort. 36.2.2 Constructors The default constructor creates a renderer with no tooltip generator and no URL generator. The constructor is protected. 36.2.3 Attributes The attributes maintained by this class are listed in Table 36.1. 36.2.4 The Pass Count Most renderers draw data items in a single pass through the dataset. However, some renderers might require two or more passes through the dataset, in order to draw items in a layered fashion. The plot will call the following method to determine how many passes the renderer requires: 447 CHAPTER 36. PACKAGE: ORG.JFREE.CHART.RENDERER.CATEGORY Attribute: Description: plot toolTipGenerator The CategoryPlot that the renderer is assigned to. The CategoryToolTipGenerator that generates tool tips for ALL series (can be null). A list of CategoryToolTipGenerator objects used to create tool tips for individual series. The base CategoryToolTipGenerator used to create tool tips when there is no other generator available. The CategoryItemLabelGenerator that generates item labels for ALL series (can be null). A list of CategoryItemLabelGenerator objects used to create item labels for individual series. If null, the baseLabelGenerator is used instead. The base CategoryItemLabelGenerator used to create item labels when no other generator is available. The CategoryURLGenerator that applies to ALL series. A list of CategoryURLGenerator objects that apply to individual series. If null, the baseItemURLGenerator is used instead. The base CategoryURLGenerator, used when no other generator is available. The generator for the series name in the legend. The generator for the tool tips for the legend items. The generator for the URL for hyperlinks for the legend items(in HTML image maps) toolTipGeneratorList baseToolTipGenerator itemLabelGenerator itemLabelGeneratorList baseItemLabelGenerator itemURLGenerator itemURLGeneratorList baseItemURLGenerator legendItemLabelGenerator legendItemToolTipGenerator legendItemURLGenerator 448 Table 36.1: Attributes for the AbstractCategoryItemRenderer class å public int getPassCount(); Returns 1, which is the default number of passes required by a renderer. If a subclass requires more than one pass through the dataset, it must override this method. Standard renderers that require multiple passes through the dataset include: • LineAndShapeRenderer; • StackedAreaRenderer; • StackedBarRenderer; • StackedBarRenderer3D. 36.2.5 Methods The following method is called once every time the chart is drawn: å public CategoryItemRendererState initialise(Graphics2D g2, Rectangle2D dataArea, CategoryPlot plot, Integer index, PlotRenderingInfo info); Performs any initialisation required by the renderer. The default implementation simply stores a local reference to the info object (which may be null). The number of rows and columns in the dataset (a CategoryDataset) is cached by the renderer in the initialise() method. To draw the plot background: å public void drawBackground(Graphics2D g2, CategoryPlot plot, Rectangle2D dataArea); Draws the plot background. Some renderers will choose to override this method, but for most the default behaviour is OK. To draw the plot outline: å public void drawOutline(Graphics2D g2, CategoryPlot plot, Rectangle2D dataArea); Draws the plot outline. Some renderers will choose to override this method, but for most the default behaviour is OK. CHAPTER 36. PACKAGE: ORG.JFREE.CHART.RENDERER.CATEGORY To draw a domain gridline: å public void drawDomainGridline(Graphics2D g2, CategoryPlot plot, Rectangle2D dataArea, double value); Draws a domain gridline at the specified value. This method is called by the CategoryPlot class. To draw a range gridline: å public void drawRangeGridline(Graphics2D g2, CategoryPlot plot, ValueAxis axis, Rectangle2D dataArea, double value); Draws a range gridline at the specified value. This method is called by the CategoryPlot class. To draw a range marker: å public void drawRangeMarker(Graphics2D g2, CategoryPlot plot, ValueAxis axis, Marker marker, Rectangle2D dataArea); Draws a range marker. This method is called by the CategoryPlot class. To get a legend item: å public LegendItem getLegendItem(int datasetIndex, int series); Returns a legend item for the specified series. The datasetIndex is zero for the primary dataset, and 1..N for the secondary datasets. To get the CategoryItemLabelGenerator for a data item: å public CategoryItemLabelGenerator getItemLabelGenerator(int row, int column); Returns the item label generator for a specific data item. By default, this method just calls the getSeriesLabelGenerator() method. To get the CategoryItemLabelGenerator for a series: å public CategoryItemLabelGenerator getSeriesItemLabelGenerator(int series); Returns the item label generator for a series. This method returns the labelGenerator if it is set, otherwise it looks up the labelGeneratorList to get a generator specific to the series. If the series-specific generator is null, the baseLabelGenerator is returned. To get the CategoryURLGenerator for a data item: å public CategoryURLGenerator getItemURLGenerator(int row,int column); Returns the item URL generator for a specific data item. By default, this method just calls the getSeriesItemURLGenerator() method. To get the CategoryURLGenerator for a series: å public CategoryURLGenerator getSeriesItemURLGenerator(int series); Returns the item URL generator for a series. This method returns the itemURLGenerator if it is set, otherwise it looks up the itemURLGeneratorList to get a generator specific to the series. If the series-specific generator is null, the baseItemURLGenerator is returned. To get the row count: å public int getRowCount(); Returns the row count. To get the column count: å public int getColumnCount(); Returns the column count. 449 CHAPTER 36. PACKAGE: ORG.JFREE.CHART.RENDERER.CATEGORY 36.2.6 450 Legend Items All renderers should implement the LegendItemSource interface, to allow a legend to fetch the relevant items for display. This requires the provision of the following method: å public LegendItemCollection getLegendItems(); Returns the legend items for this renderer. This implementation returns one item for each series that the renderer is responsible for, taking into account the series visibility flags. The individual legend items are created with a call to the following method: å public LegendItem getLegendItem(int datasetIndex, int series); Creates a legend item for the specified series.1 This method can return null, in which case no legend item will be added to the series (in this default implementation, null is returned if either isSeriesVisible(series) or isSeriesVisibleInLegend(series) returns false). Subclasses may override this method to provide customised legend items. A plug-in generator is used to create each legend item label, so that you can customise the label if necessary: å public CategorySeriesLabelGenerator getLegendItemLabelGenerator(); Returns the legend item label generator (never null). The default generator simply returns the series key converted to a string using the key’s toString() method. å public void setLegendItemLabelGenerator(CategorySeriesLabelGenerator generator); Sets the legend item label generator and sends a RendererChangeEvent to all registered listeners. If generator is null, this method throws an IllegalArgumentException. Each legend item can (optionally) have a tool tip associated with it. If you require tool tips, you need to specify a tool tip generator: å public CategorySeriesLabelGenerator getLegendItemToolTipGenerator(); Returns the tool tip generator for the legend items created by this renderer. The default is null. å public void setLegendItemToolTipGenerator(CategorySeriesLabelGenerator generator); Sets the tool tip generator for the legend items created by this renderer, and sends a RendererChangeEvent to all registered listeners. If you set this to null, no tool tips will be generated. Similarly, each legend item can (optionally) have a URL associated with it (these are used only in HTML image maps). If you require URLs, you need to specified a URL generator: å public CategorySeriesLabelGenerator getLegendItemURLGenerator(); Returns the URL generator for the legend items created by this renderer. The default is null. The URLs are used to provide hyperlinks in HTML image maps. å public void setLegendItemURLGenerator(CategorySeriesLabelGenerator generator); Sets the URL generator for the legend items created by this renderer, and sends a RendererChangeEvent to all registered listeners. If you set this to null, no URLs will be generated. 36.2.7 Equals, Cloning and Serialization This class overrides the equals() method: å public boolean equals(Object obj); Tests this renderer for equality with an arbitrary object. Note that the test does NOT take into account the plot that the renderer is assigned to. Instances of this class are cloneable and serializable. 36.2.8 Notes If you are implementing your own renderer, you do not have to use this base class, but it does save you some work. 1 The dataset argument is passed in because the renderer itself has no state information to know which dataset it is rendering. CHAPTER 36. PACKAGE: ORG.JFREE.CHART.RENDERER.CATEGORY 36.3 AreaRenderer 36.3.1 Overview 451 A renderer that represents the items in a CategoryDataset using a polygon that fills the area between the x-axis and the data points—an example is shown in figure 36.1. This renderer is designed for use with the CategoryPlot class. Area Chart An area chart demonstration. We use this subtitle as an example of what happens when you get a really long title or subtitle. 8 7 6 Value 5 4 3 2 1 8 Ty pe 7 Ty pe 6 Ty pe 5 Ty pe 4 Ty pe 3 Ty pe 2 pe Ty Ty pe 1 0 Category Series 1 Series 2 Series 3 Figure 36.1: An area chart (see AreaChartDemo1.java) 36.3.2 Constructor To create a new renderer: å public AreaRenderer(); Creates a new renderer with default attributes. The ChartFactory.createAreaChart() method can also be used to create a chart that uses this type of renderer. 36.3.3 General Attributes To control how the end points of the area chart are represented: å public AreaRendererEndType getEndType(); Returns a token indicating how the ends of the area drawn by this renderer are handled (never null). The default value is AreaRendererEndType.TAPER. å public void setEndType(AreaRendererEndType type); Sets the token that controls how the end points are drawn on the area chart and sends a RendererChangeEvent to all registered listeners. If type is null, this method throws an IllegalArgumentException. Other attributes are inherited from AbstractCategoryItemRenderer. 36.3.4 Other Methods The following methods are typically called by JFreeChart—you shouldn’t need to call them directly: CHAPTER 36. PACKAGE: ORG.JFREE.CHART.RENDERER.CATEGORY 452 å public LegendItem getLegendItem(int datasetIndex, int series); Overridden to use a custom graphic in the legend item. å public void drawItem(Graphics2D g2, CategoryItemRendererState state, Rectangle2D dataArea, CategoryPlot plot, CategoryAxis domainAxis, ValueAxis rangeAxis, CategoryDataset dataset, int row, int column, int pass); Draws one item from the dataset. 36.3.5 Equals, Cloning and Serialization This class overrides the equals() method: å public boolean equals(Object obj); Tests this renderer for equality with an arbitrary object. Instances of this class are Cloneable and Serializable. 36.3.6 Notes Some points to note: • the createAreaChart() method in the ChartFactory class will create a default chart that uses this renderer; • this class extends AbstractCategoryItemRenderer; • a demo (AreaChartDemo1.java) is included in the JFreeChart demo collection. See Also AbstractCategoryItemRenderer, XYAreaRenderer. 36.4 BarRenderer 36.4.1 Overview This renderer is used in conjunction with a CategoryPlot to create bar charts from data in a CategoryDataset. The renderer will handle plots with a vertical orientation (see figure 36.2) or a horizontal orientation (see figure 36.3). The renderer will recognise the use of GradientPaint instances for series colors and use a special transformer to apply these to bar regions. This class extends the AbstractCategoryItemRenderer base class. 36.4.2 Constructor The constructor creates a new renderer with default settings: å public BarRenderer(); Creates a new renderer with a default settings. By default, the renderer will draw outlines around the bars, will have an item margin of 20% (this controls the amount of space allocated to the gaps between bars within a single category), and will use a StandardGradientPaintTransformer when a series color is an instance of GradientPaint. CHAPTER 36. PACKAGE: ORG.JFREE.CHART.RENDERER.CATEGORY 453 Bar Chart Demo 1 8 7 6 Value 5 4 3 2 1 0 Ca teg ory 1 Ca teg ory 2 Ca teg ory 3 Ca teg ory 4 Ca teg ory 5 Category First Second Third Figure 36.2: A vertical bar chart (see BarChartDemo1.java) Prison Population Rates - Selected Countries Source: http://www.homeoffice.gov.uk/rds/pdfs2/r188.pdf Norway 59 Switzerland 69 France 85 Syria 93 Germany 96 Country China 111 Australia 116 Egypt 121 England & Wales 129 New Zealand 157 Chile 205 Iran 229 Singapore 359 South Africa 404 Ukraine 406 USA 686 0 50 100 150 200 250 300 350 400 450 500 550 600 650 700 750 Prisoners Per 100,000 National Population Prison Population Rates Figure 36.3: A horizontal bar chart (see BarChartDemo5.java) 36.4.3 The Base Value By default, the renderer draws a bar between zero (the base value) and the data value of the item to be displayed. Some specialised bar charged require a non-zero base value—you can use the following methods to access/modify the base value: å public double getBase(); Returns the base value for the bars. The default value is 0.0. å public void setBase(double base); Sets the base value for the bars and sends a RendererChangeEvent to all registered listeners. The includeBaseInRange flag controls whether or not JFreeChart will include the base value when calculating the bounds for the chart’s range axis: CHAPTER 36. PACKAGE: ORG.JFREE.CHART.RENDERER.CATEGORY 454 å public boolean getIncludeBaseInRange(); [1.0.1] Returns true if the base value should be included in the auto range calculation for the chart’s range axis, and false otherwise. The default value is true. å public void setIncludeBaseInRange(boolean include); [1.0.1] Sets the flag that controls whether or not the base value is included in the auto range calculation for the range axis, and sends a RendererChangeEvent to all registered listeners. 36.4.4 Controlling the Width of Bars The renderer automatically calculates the width of the bars to fit the available space for the plot, so you cannot directly control how wide the bars are. However, the bar width is a function of the following attributes that you can control: • the lowerMargin, upperMargin and categoryMargin attributes, all defined by the CategoryAxis (see figure 24.8.1 for more information about the purpose of these attributes); • the itemMargin attribute belonging to the renderer (see below). The itemMargin attribute controls the amount of space between bars within a category: å public double getItemMargin(); Returns the item margin as a percentage of the overall length of the category axis (the default is 0.20, or twenty percent). This controls the amount of space that is allocated to the gaps between bars within the same category. å public void setItemMargin(double percent); Sets the item margin and sends a RendererChangeEvent to all registered listeners. The dynamic bar width calculation can result in very wide bars if you have only a few data values in a chart. If you would like to specify a “cap” for the bar width, use the maximumBarWidth attribute: å public double getMaximumBarWidth(); Returns the maximum bar width allowed, as a percentage of the length of the category axis. The default is 1.00 (100 percent) which means that the bar widths are never capped. å public void setMaximumBarWidth(double percent); Sets the maximum bar width as a percentage of the axis length and sends a RendererChangeEvent to all registered listeners. For example, setting this to 0.05 will ensure that the bars never exceed five percent of the length of the axis. This can improve the appearance of charts where there is a possibility that only one or two bars will be displayed. 36.4.5 Bar Outlines The drawBarOutline flag controls whether the bars drawn by the renderer are outlined: å public boolean isDrawBarOutline(); Returns the flag that controls whether an outline is added to each bar drawn by this renderer. The default value is false. å public void setDrawBarOutline(boolean draw); Sets the flag that controls whether or not an outline is drawn around each bar and sends a RendererChangeEvent to all registered listeners. The Paint and Stroke used for the bar outline is specified using methods in the superclass. 36.4.6 Gradient Paint Support You can set the colour for the bars in a series using the setSeriesPaint() method inherited from the AbstractRenderer class.2 2 Note that the setSeriesFillPaint() method does NOT change the bar colour—the fill paint is ignored by this renderer. CHAPTER 36. PACKAGE: ORG.JFREE.CHART.RENDERER.CATEGORY 455 To provide better support for the use of GradientPaint objects to color the bars drawn by this renderer, you can specify a transformer that will dynamically adjust the GradientPaint to fit each bar: å public GradientPaintTransformer getGradientPaintTransformer(); Returns the transformer used for GradientPaint instances. If this is null, any GradientPaint instance will be used in its raw form (i.e. with fixed coordinates), which you typically don’t want. å public void setGradientPaintTransformer(GradientPaintTransformer transformer); Sets the transformer (null is permitted) used to transform GradientPaint instances and sends a RendererChangeEvent to all registered listeners. The BarChartDemo1.java application, included in the JFreeChart demo collection, provides an example of the use of this attribute. 36.4.7 Item Labels This renderer supports the display of item labels. For the most part, these are controlled using methods defined in the super class, but there are some settings that are specific to the bar renderer. Due to the rectangular nature of the bars, the renderer calculates anchor points that are arranged as shown in figure 36.4. Note that the numbers correspond (roughly) to the position of the hours on a clock face. OUTSIDE_11 OUTSIDE_12 OUTSIDE_10 OUTSIDE_1 OUTSIDE_2 INSIDE_12 OUTSIDE_9 OUTSIDE_3 CENTER OUTSIDE_8 OUTSIDE_7 INSIDE_6 OUTSIDE_6 OUTSIDE_4 OUTSIDE_5 Figure 36.4: Item Label Anchors for Bars When an item label is displayed inside a bar, the renderer will calculate if the bar is large enough to contain the text. If not, the renderer will check to see if a “fallback” label position has been specified. If there is a fallback position, the label is displayed there, and if there is no fallback position the label is not displayed at all. Two fallback positions can be specified, one for positive values and one for negative values (this covers the standard case where positive value labels that don’t fit within a bar should be displayed above the bar, and negative value labels that don’t fit within a bar should be displayed below the bar). å public ItemLabelPosition getPositiveItemLabelPositionFallback(); Returns the fallback position for positive value labels that don’t fit within a bar. This can be null, in which case the label won’t be displayed at all. CHAPTER 36. PACKAGE: ORG.JFREE.CHART.RENDERER.CATEGORY 456 å public void setPositiveItemLabelPositionFallback(ItemLabelPosition position); Sets the fallback position for positive item labels (null is permitted) and sends a RendererChangeEvent to all registered listeners. Set the fallback position to null if you prefer labels to be hidden if they don’t fit within the bar. å public ItemLabelPosition getNegativeItemLabelPositionFallback(); Returns the fallback position for negative value labels that don’t fit within a bar. This can be null, in which case the label won’t be displayed at all. å public void setNegativeItemLabelPositionFallback(ItemLabelPosition position); Sets the fallback position for negative item labels (null is permitted) and sends a RendererChangeEvent to all registered listeners. Set the fallback position to null if you prefer labels to be hidden if they don’t fit within the bar. 36.4.8 Other Methods This class implements all the methods in the CategoryItemRenderer interface. å public CategoryItemRendererState initialise(Graphics2D g2, Rectangle2D dataArea, CategoryPlot plot, int rendererIndex, PlotRenderingInfo info); This method is called by the plot at the start of every chart drawing run (you shouldn’t need to call this method yourself). It initialises the renderer and creates a state object that will be passed to each invocation of the drawItem() method for this drawing run only. å public void drawItem(Graphics2D g2, CategoryItemRendererState state, Rectangle2D dataArea, CategoryPlot plot, CategoryAxis domainAxis, ValueAxis rangeAxis, CategoryDataset dataset, int row, int column); This method is called (by the plot) once for each item in the dataset. The renderer state is the same object that was created in the initialise() method. For very small data values (relative to the axis range), you can have bars with a length of less than 1 pixel (on-screen)—when the value gets too small, the bar will disappear. If you want to ensure that a line is always drawn so that the small bar is visible, you can specify a minimum bar length with this method: å public void setMinimumBarLength(double min); Sets the minimum length that will be used for a bar, specified in Java 2D units. You can set this to 1.0, for example, to ensure that very short bars do not disappear. 36.4.9 Internal Methods The following methods are used internally by the renderer: å protected void calculateBarWidth(CategoryPlot plot, Rectangle2D dataArea, int rendererIndex, CategoryItemRendererState state) This method is called during the initialisation of each drawing run to calculate the width of each bar. The calculated value is stored in the renderer state so it doesn’t need to be recalculated for every bar in the chart. 36.4.10 Equals, Cloning and Serialization This class overrides the equals() method: å public boolean equals(Object obj); Tests this renderer for equality with an arbitrary object. This method returns true if and only if: • obj is not null; • obj is an instance of BarRenderer; • obj has the same attributes as this renderer; Instances of this class are Cloneable and Serializable. CHAPTER 36. PACKAGE: ORG.JFREE.CHART.RENDERER.CATEGORY 36.4.11 457 Notes Some points to note: • this renderer inherits seriesPaint and seriesFillPaint attributes from AbstractRenderer. The bar colour is determined by the former—the seriesFillPaint attribute is never used by this renderer; • the ChartFactory class uses this renderer when it constructs bar charts via the createBarChart() method; • a range of demos (for example, BarChartDemo1.java) is included in the JFreeChart demo collection. See Also BarRenderer3D, StackedBarRenderer, StackedBarRenderer3D. 36.5 BarRenderer3D 36.5.1 Overview A renderer that draws items from a CategoryDataset using bars with a 3D effect—see figure 36.5. 3D Bar Chart Demo 17.5 15.0 12.5 10.0 Value 7.5 5.0 2.5 0.0 -2.5 -5.0 -7.5 -10.0 -12.5 Ca teg ory 1 Ca teg ory 2 Ca teg ory 3 Ca teg ory 4 Category Series 1 Series 2 Series 3 Series 4 Series 5 Series 6 Series 7 Series 8 Series 9 Figure 36.5: A bar chart with 3D effect (see BarChart3DDemo1.java) This renderer is a subclass of BarRenderer and is designed for use with the CategoryPlot class. 36.5.2 Constructors There are two constructors: å public BarRenderer3D(); Equivalent to BarRenderer(12.0, 8.0)—see below. å public BarRenderer3D(double xOffset, double yOffset); Creates a new renderer with the specified offsets for the 3D effect (specified in Java2D units). CHAPTER 36. PACKAGE: ORG.JFREE.CHART.RENDERER.CATEGORY 36.5.3 458 Attributes To access the 3D offset (which is defined in the constructor): å public double getXOffset(); Returns the x-offset for the 3D effect, in Java2D units. The default value is 12.0. This attribute can only be set via the class constructor. å public double getYOffset(); Returns the y-offset for the 3D effect, in Java2D units. The default value is 8.0. This attribute can only be set via the class constructor. The “wall paint” is the color used to highlight the inner wall of the data area in the plot: å public Paint getWallPaint(); Returns the paint used to draw the inside walls of the plot area, highlighting the 3D effect. The default value is Color(0xDD, 0xDD, 0xDD). This method never returns null. å public void setWallPaint(Paint paint); Sets the paint used to draw the inside walls of the plot area, highlighting the 3D effect, and sends a RendererChangeEvent to all registered listeners. If paint is null, this method throws an IllegalArgumentException. 36.5.4 Other Methods Several methods are overridden to add support for the 3D effect. JFreeChart calls these methods, you won’t normally call them directly: å public CategoryItemRendererState initialise(Graphics2D g2, Rectangle2D dataArea, CategoryPlot plot, int rendererIndex, PlotRenderingInfo info); Overridden for the purpose of adjusting the dataArea, some of which is taken away by the 3D effect. å public void drawItem(Graphics2D g2, CategoryItemRendererState state, Rectangle2D dataArea, CategoryPlot plot, CategoryAxis domainAxis, ValueAxis rangeAxis, CategoryDataset dataset, int row, int column, int pass); Draws a single bar with 3D effect. å public void drawBackground(Graphics2D g2, CategoryPlot plot, Rectangle2D dataArea); Draws the background area, taking into account the 3D effect. å public void drawOutline(Graphics2D g2, CategoryPlot plot, Rectangle2D dataArea); Draws the plot outline, taking into account the 3D effect. å public void drawDomainGridline(Graphics2D g2, CategoryPlot plot, Rectangle2D dataArea, double value); Draws a domain gridline, taking into account the 3D effect. å public void drawRangeGridline(Graphics2D g2, CategoryPlot plot, ValueAxis axis, Rectangle2D dataArea, double value); Draws a range gridline, taking into account the 3D effect. å public void drawRangeMarker(Graphics2D g2, CategoryPlot plot, ValueAxis axis, Marker marker, Rectangle2D dataArea); Draws a range marker, taking into account the 3D effect. 36.5.5 Equals, Cloning and Serialization This class overrides the equals() method: å public boolean equals(Object obj); Tests this renderer for equality with an arbitrary object, returning true if and only if: • • • • obj is not null; obj is an instance of BarRenderer3D; obj has the same x- and y-offset and wall paint settings; super.equals(obj) returns true. Instances of this class are Cloneable (PublicCloneable) and Serializable. CHAPTER 36. PACKAGE: ORG.JFREE.CHART.RENDERER.CATEGORY 36.5.6 459 Notes Some points to note: • this class is a subclass of BarRenderer and implements the CategoryItemRenderer interface. • the 3D effect drawn by this renderer is sensitive to the order in which the data items are drawn (see section 33.3.8); • a couple of demos (BarChart3DDemo1.java and BarChart3DDemo2.java) are included in the JFreeChart demo collection. See Also BarRenderer, StackedBarRenderer3D, CategoryAxis3D. 36.6 BoxAndWhiskerRenderer 36.6.1 Overview A renderer that is used to create a box-and-whisker chart using data from a special dataset (BoxAndWhiskerCategoryDataset). A sample chart is shown in Figure 36.6. Figure 36.6: A chart generated with a BoxAndWhiskerRenderer The chart indicates the following data items: • the mean value is drawn as a filled circle (with a diameter equal to half the width of the box); • the median is drawn as a short horizontal line; • the box highlights the range from quartile 1 to quartile 3; • the capped line extending from each end of the box indicates the full range of regular values; • hollow circles are used to indicate outlier values; • triangles at each extreme indicate the presence of far out values. Note that a similar renderer (XYBoxAndWhiskerRenderer) is available for use with the XYPlot class. 36.6.2 Constructors To create a new renderer: å public BoxAndWhiskerRenderer(); Creates a new renderer. CHAPTER 36. PACKAGE: ORG.JFREE.CHART.RENDERER.CATEGORY 36.6.3 460 Methods To control the color of the median and mean indicators: å public Paint getArtifactPaint(); Returns the Paint used to draw the median and mean indicators. The default is Color.black. å public void setArtifactPaint(Paint paint); Sets the Paint used to draw the median and mean indicators and sends a RendererChangeEvent to all registered listeners. If paint is null, this method throws an IllegalArgumentException. To determine whether or not the boxes are filled: å public boolean getFillBox(); Returns true if the boxes are filled, and false otherwise. The default is true. å public void setFillBox(boolean flag); Sets the flag that controls whether or not the boxes are filled, and sends a RendererChangeEvent to all registered listeners. To control the spacing between items within a category:3 å public double getItemMargin(); Returns the item margin as a percentage of the overall length of the category axis (the default is 0.20, or twenty percent). This controls the amount of space that is allocated to the gaps between items within the same category. å public void setItemMargin(double margin); Sets the item margin and sends a RendererChangeEvent to all registered listeners. The method that creates legend items is overridden: å public LegendItem getLegendItem(int datasetIndex, int series); Returns a legend item for the specified series. This method is overridden to return a box as the legend item shape. 36.6.4 Notes Some points to note: • a demo application (BoxAndWhiskerDemo1.java) is included in the JFreeChart demo collection. See Also XYBoxAndWhiskerRenderer. 36.7 CategoryItemRenderer 36.7.1 Overview A category item renderer is an object that is assigned to a CategoryPlot and assumes responsibility for drawing the visual representation of individual data items in a dataset. This interface defines the methods that must be provided by all category item renderers—the plot will only use the methods defined in this interface. A number of different renderers have been developed, allowing different chart types to be generated easily. The following table lists the renderers that have been implemented to date: 3 The spacing between categories is controlled by the CategoryAxis. CHAPTER 36. PACKAGE: ORG.JFREE.CHART.RENDERER.CATEGORY AbstractCategoryItemRenderer 461 CategoryItemRenderer AreaRenderer LineAndShapeRenderer StackedAreaRenderer DefaultCategoryItemRenderer MinMaxCategoryRenderer BarRenderer BarRenderer3D StackedBarRenderer IntervalBarRenderer StackedBarRenderer3D Figure 36.7: Category item renderers Class: Description: AreaRenderer BarRenderer BarRenderer3D BoxAndWhiskerRenderer CategoryStepRenderer GanntRenderer GroupedStackedBarRenderer IntervalBarRenderer Used to create area charts. Represents data using bars (anchored at zero). Represents data using bars (anchored at zero) with a 3D effect. A box-and-whisker plot. Connects data values using a stepped line. For displaying simple Gantt charts. Stacked bar charts with custom groupings. Draws intervals using bars. This renderer can be used to create simple Gantt charts. For layered bar charts. Displays levels (usually overlaid on top of a regular bar chart). Draws lines and/or shapes to represent data. A line chart with 3D effect. For plotting min-max ranges. For stacked area charts. Used to create a stacked bar charts. For stacked bar charts with a 3D effect. For bar charts with an error indicator. For line charts with an error indicator. LayeredBarRenderer LevelRenderer LineAndShapeRenderer LineRenderer3D MinMaxCategoryRenderer StackedAreaRenderer StackedBarRenderer StackedBarRenderer3D StatisticalBarRenderer StatisticalLineAndShapeRenderer The AbstractCategoryItemRenderer is a useful base class for implementing this interface, if you are developing your own renderer. 36.7.2 General Methods To find the plot that the renderer is currently assigned to: å public CategoryPlot getPlot(); Returns the plot that the renderer is currently assigned to. å public void setPlot(CategoryPlot plot); Sets the plot that the renderer is currently assigned to. This method is called by the CategoryPlot class, you shouldn’t need to call this yourself. The following method returns the range of values that will be spanned by the visual representation of the specified dataset, as drawn by this renderer: å public Range findRangeBounds(CategoryDataset dataset); Returns the range of values that will be spanned by ths visual representation of the data values in the specified dataset, as drawn by this renderer. This method is used to determine an appropriate default range for the y-axis on a plot. The interface defines an initialisation method: CHAPTER 36. PACKAGE: ORG.JFREE.CHART.RENDERER.CATEGORY 462 å public CategoryItemRendererState initialise(Graphics2D g2, Rectangle2D dataArea, CategoryPlot plot, Integer index, PlotRenderingInfo info); This method is called exactly once at the start of every chart redraw. The method returns a state object that the plot will pass to the drawItem() method for each data item that the renderer needs to draw. Thus, it gives the renderer a chance to precalculate any information it might require later when rendering individual data items. The pass count refers to the number of passes that the renderer makes through the dataset. The majority of renderers use just a single pass, but some renderers make two or more passes, drawing the data items in several layers: å public int getPassCount(); Returns the number of passes through the dataset that need to be made by this renderer. The most important method is the one that actually draws a data item: å public void drawItem(...); Draws one item on a category plot. The CategoryPlot class will iterate through the data items, passing them to the renderer one at a time. å public LegendItem getLegendItem(int datasetIndex, int series); Returns a legend item for the specified series. 36.7.3 The Paint and Outline Paint This interface assumes that the renderer stores values for the paint and outline paint attributes on a per-series basis, with a default value that can be used when no value is specified for a particular series. By convention, the CategoryPlot will always call the following method to obtain the paint value for a data item: å public Paint getItemPaint(int row, int column); Returns the paint to use for the specified data item. This method should never return null. The per-series paint settings can be controlled via the following methods: å public Paint getSeriesPaint(int series); Returns the paint for the specified series (possibly null). å public void setSeriesPaint(int series, Paint paint); Sets the paint for the specified series (null is permitted) and sends a RendererChangeEvent to all registered listeners. The default value (to be used in the case that there is no value specified for a particular series) is controlled via the following methods: å public Paint getBasePaint(); Returns the default paint, typically used when no per-series paint is defined. This method should never return null. å public void setBasePaint(Paint paint); Sets the default paint to be used when no per-series paint is defined. If paint is null, this method should throw an IllegalArgumentException. If the new paint value is different to the existing value, this method should send a RendererChangeEvent to all registered listeners. Similarly for the outline paint, the CategoryPlot will always call the following method to obtain the outline paint for a data item: å public Paint getItemOutlinePaint(int row, int column); Returns the outline paint to use for the specified data item. This method should never return null. The per-series outline paint settings can be controlled via the following methods: å public Paint getSeriesOutlinePaint(int series); Returns the paint for the specified series (possibly null). CHAPTER 36. PACKAGE: ORG.JFREE.CHART.RENDERER.CATEGORY 463 å public void setSeriesOutlinePaint(int series, Paint paint); Sets the paint for the specified series (null is permitted) and sends a RendererChangeEvent to all registered listeners. The default outline paint value (to be used in the case that there is no value specified for a particular series) is controlled via the following methods: å public Paint getBaseOutlinePaint(); Returns the default outline paint, typically used when no per-series outline paint is defined. This method should never return null. å public void setBaseOutlinePaint(Paint paint); Sets the default outline paint to be used when no per-series outline paint is defined. If paint is null, this method should throw an IllegalArgumentException. If the new paint value is different to the existing value, this method should send a RendererChangeEvent to all registered listeners. 36.7.4 The Stroke The style of lines (if any) drawn by the renderer is controlled by the stroke attribute. A renderer should always call the following method to determine the stroke on a per-item basis: å public Stroke getItemStroke(int row, int column); Returns the stroke for the specified data item. This method should never return null. For the convenience of developers using the renderer API, the interface assumes that a renderer stores stroke attributes on a per-series basis (at least), with a default val