JFreeChart 1.0.4 Developer Guide

JFreeChart 1.0.4 Developer Guide
The JFreeChart Class Library
Version 1.0.4
Developer Guide
Written by David Gilbert
February 9, 2007
c 2000-2007, Object Refinery Limited. All rights reserved.
IMPORTANT NOTICE:
If you choose to use this document you do so entirely at your own risk.
Contents
1 Introduction
1.1 What is JFreeChart? . . . .
1.2 This Document . . . . . . .
1.3 Acknowledgements . . . . .
1.4 Comments and Suggestions
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
15
15
17
17
17
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 . . . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
18
18
18
20
22
23
24
25
26
26
28
29
30
31
32
3 Downloading and Installing JFreeChart
3.1 Introduction . . . . . . . . . . . . . . . . .
3.2 Download . . . . . . . . . . . . . . . . . .
3.3 Unpacking the Files . . . . . . . . . . . .
3.4 Running the Demonstration Applications
3.5 Compiling the Source . . . . . . . . . . .
3.6 Generating the Javadoc Documentation .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
33
33
33
33
34
35
35
.
.
.
.
4 Using JFreeChart
36
4.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
4.2 Creating Your First Chart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
5 Pie
5.1
5.2
5.3
5.4
5.5
5.6
5.7
5.8
Charts
Introduction . . . . . . . . . . .
Creating a Simple Pie Chart . .
Section Colours . . . . . . . . .
Section Outlines . . . . . . . .
Null, Zero and Negative Values
Section and Legend Labels . . .
Exploded Sections . . . . . . .
3D Pie Charts . . . . . . . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
1
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
39
39
39
39
40
40
41
41
42
CONTENTS
5.9
6 Bar
6.1
6.2
6.3
6.4
6.5
2
Multiple Pie Charts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
42
Charts
Introduction . . . . . . . . .
A Bar Chart . . . . . . . .
The ChartFactory Class . .
Simple Chart Customisation
Customising the Renderer .
44
44
44
47
48
48
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
7 Line Charts
50
7.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
7.2 A Line Chart Based On A Category Dataset . . . . . . . . . . . . . . . . . . . . . . 50
7.3 A Line Chart Based On An XYDataset . . . . . . . . . . . . . . . . . . . . . . . . . 55
8 Time Series Charts
60
8.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
8.2 Time Series Charts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
9 Customising Charts
9.1 Introduction . . .
9.2 Chart Attributes
9.3 Plot Attributes .
9.4 Axis Attributes .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
66
66
66
68
69
10 Dynamic Charts
71
10.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
10.2 Background . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
10.3 The Demo Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
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
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
76
76
76
77
77
77
77
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 .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
78
78
79
80
81
82
83
86
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
13 Multiple Axes and Datasets
90
13.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
13.2 An Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
13.3 Hints and Tips . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
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
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
98
. 98
. 98
. 98
. 99
. 100
. 101
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 .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
93
93
93
94
95
96
102
102
102
102
102
103
103
107
107
Format
110
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110
18 Applets
113
18.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113
18.2 Issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113
18.3 A Sample Applet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114
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 . . . . . . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
117
117
117
119
120
120
125
126
20 Miscellaneous
20.1 Introduction . . . . .
20.2 X11 / Headless Java
20.3 Java Server Pages . .
20.4 Loading Images . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
128
128
128
128
128
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
21 Packages
129
21.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
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.13JFreeChart . . . . . .
22.14LegendItem . . . . . .
22.15LegendItemCollection
22.16LegendItemSource . .
22.17LegendRenderingOrder
22.18PolarChartPanel . . .
4
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
130
130
130
130
133
133
134
134
138
140
141
142
142
142
146
149
150
150
150
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 . . . . . . . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
151
151
151
152
153
154
156
157
158
159
160
160
162
163
164
166
167
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 . . . . . . .
24.16CyclicNumberAxis . . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
169
169
169
174
174
174
175
175
176
179
180
180
181
182
182
182
183
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
CONTENTS
24.17DateAxis . . . . . . . .
24.18DateTickMarkPosition .
24.19DateTick . . . . . . . .
24.20DateTickUnit . . . . . .
24.21ExtendedCategoryAxis .
24.22LogarithmicAxis . . . .
24.23MarkerAxisBand . . . .
24.24ModuloAxis . . . . . . .
24.25MonthDateFormat . . .
24.26NumberAxis . . . . . . .
24.27NumberAxis3D . . . . .
24.28NumberTick . . . . . . .
24.29NumberTickUnit . . . .
24.30PeriodAxis . . . . . . .
24.31PeriodAxisLabelInfo . .
24.32QuarterDateFormat . .
24.33SegmentedTimeline . . .
24.34StandardTickUnitSource
24.35SubCategoryAxis . . . .
24.36SymbolAxis . . . . . . .
24.37Tick . . . . . . . . . . .
24.38TickUnit . . . . . . . . .
24.39TickUnits . . . . . . . .
24.40TickUnitSource . . . . .
24.41Timeline . . . . . . . . .
24.42ValueAxis . . . . . . . .
24.43ValueTick . . . . . . . .
5
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
184
188
188
188
189
190
192
192
193
194
198
199
199
200
203
204
205
205
206
206
208
208
208
209
209
210
213
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 BlockParams . . . . . . . . .
25.8 BlockResult . . . . . . . . . .
25.9 BorderArrangement . . . . .
25.10CenterArrangement . . . . .
25.11ColorBlock . . . . . . . . . .
25.12ColumnArrangement . . . . .
25.13EmptyBlock . . . . . . . . . .
25.14EntityBlockParams . . . . . .
25.15EntityBlockResult . . . . . .
25.16FlowArrangement . . . . . . .
25.17GridArrangement . . . . . . .
25.18LabelBlock . . . . . . . . . .
25.19LengthConstraintType . . . .
25.20RectangleConstraint . . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
214
214
214
215
216
217
217
218
219
219
219
219
220
220
221
221
221
222
222
224
224
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
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
226
226
226
226
227
227
227
228
228
229
229
229
229
230
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 . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
231
231
231
232
232
233
233
234
234
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 . . . . . . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
236
236
236
236
237
238
238
239
239
240
241
241
242
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 . . . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
243
243
243
243
244
244
245
245
246
246
247
247
248
248
248
249
.
.
.
.
.
.
.
.
.
.
.
.
.
CONTENTS
7
29.16TitleChangeListener . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249
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 . . . . . . . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
250
250
250
250
251
251
251
252
252
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 . . . . . . . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
254
254
254
255
256
258
258
258
259
259
260
260
260
261
262
262
263
264
264
265
266
267
267
269
269
270
271
272
273
274
274
274
275
275
276
32 Package: org.jfree.chart.needle
32.1 Overview . . . . . . . . . . .
32.2 ArrowNeedle . . . . . . . . .
32.3 LineNeedle . . . . . . . . . .
32.4 LongNeedle . . . . . . . . . .
32.5 MeterNeedle . . . . . . . . . .
32.6 PinNeedle . . . . . . . . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
277
277
277
278
278
278
279
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
CONTENTS
32.7 PlumNeedle .
32.8 PointerNeedle
32.9 ShipNeedle .
32.10WindNeedle .
8
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
279
280
280
280
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.34PolarPlot . . . . . . . . . . . .
33.35RainbowPalette . . . . . . . . .
33.36RingPlot . . . . . . . . . . . . .
33.37SeriesRenderingOrder . . . . .
33.38SpiderWebPlot . . . . . . . . .
33.39ThermometerPlot . . . . . . . .
33.40ValueAxisPlot . . . . . . . . . .
33.41ValueMarker . . . . . . . . . .
33.42WaferMapPlot . . . . . . . . .
33.43XYPlot . . . . . . . . . . . . .
33.44Zoomable . . . . . . . . . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
282
282
282
284
288
289
290
292
293
294
297
298
298
298
298
299
300
301
302
305
305
306
310
311
316
318
318
319
326
326
326
331
332
333
333
338
338
339
340
344
347
347
348
348
358
CONTENTS
34 Package: org.jfree.chart.renderer
34.1 Overview . . . . . . . . . . . . .
34.2 AbstractRenderer . . . . . . . . .
34.3 AreaRendererEndType . . . . . .
34.4 DefaultPolarItemRenderer . . . .
34.5 GrayPaintScale . . . . . . . . . .
34.6 LookupPaintScale . . . . . . . . .
34.7 NotOutlierException . . . . . . .
34.8 Outlier . . . . . . . . . . . . . . .
34.9 OutlierList . . . . . . . . . . . .
34.10OutlierListCollection . . . . . . .
34.11PaintScale . . . . . . . . . . . . .
34.12PolarItemRenderer . . . . . . . .
34.13RendererState . . . . . . . . . . .
34.14WaferMapRenderer . . . . . . . .
9
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
359
359
359
377
377
378
379
380
380
380
381
381
381
382
383
35 Package: org.jfree.chart.renderer.category
35.1 Overview . . . . . . . . . . . . . . . . . . .
35.2 AbstractCategoryItemRenderer . . . . . . .
35.3 AreaRenderer . . . . . . . . . . . . . . . . .
35.4 BarRenderer . . . . . . . . . . . . . . . . .
35.5 BarRenderer3D . . . . . . . . . . . . . . . .
35.6 BoxAndWhiskerRenderer . . . . . . . . . .
35.7 CategoryItemRenderer . . . . . . . . . . . .
35.8 CategoryItemRendererState . . . . . . . . .
35.9 CategoryStepRenderer . . . . . . . . . . . .
35.10DefaultCategoryItemRenderer . . . . . . . .
35.11GanttRenderer . . . . . . . . . . . . . . . .
35.12GroupedStackedBarRenderer . . . . . . . .
35.13IntervalBarRenderer . . . . . . . . . . . . .
35.14LayeredBarRenderer . . . . . . . . . . . . .
35.15LevelRenderer . . . . . . . . . . . . . . . . .
35.16LineAndShapeRenderer . . . . . . . . . . .
35.17LineRenderer3D . . . . . . . . . . . . . . .
35.18MinMaxCategoryRenderer . . . . . . . . . .
35.19StackedAreaRenderer . . . . . . . . . . . . .
35.20StackedBarRenderer . . . . . . . . . . . . .
35.21StackedBarRenderer3D . . . . . . . . . . . .
35.22StatisticalBarRenderer . . . . . . . . . . . .
35.23StatisticalLineAndShapeRenderer . . . . . .
35.24WaterfallBarRenderer . . . . . . . . . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
384
384
384
387
388
392
394
395
398
399
400
400
401
402
403
404
406
409
410
412
413
414
416
417
419
36 Package: org.jfree.chart.renderer.xy
36.1 Overview . . . . . . . . . . . . . . .
36.2 AbstractXYItemRenderer . . . . . .
36.3 CandlestickRenderer . . . . . . . . .
36.4 ClusteredXYBarRenderer . . . . . .
36.5 CyclicXYItemRenderer . . . . . . . .
36.6 DefaultXYItemRenderer . . . . . . .
36.7 HighLowRenderer . . . . . . . . . .
36.8 StackedXYAreaRenderer . . . . . . .
36.9 StackedXYBarRenderer . . . . . . .
36.10StandardXYItemRenderer . . . . . .
36.11WindItemRenderer . . . . . . . . . .
36.12XYAreaRenderer . . . . . . . . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
421
421
421
422
423
425
425
425
426
427
428
429
429
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
CONTENTS
10
36.13XYBarRenderer . . . . . . . .
36.14XYBlockRenderer . . . . . .
36.15XYBoxAndWhiskerRenderer
36.16XYBubbleRenderer . . . . . .
36.17XYDifferenceRenderer . . . .
36.18XYDotRenderer . . . . . . .
36.19XYErrorRenderer . . . . . . .
36.20XYItemRenderer . . . . . . .
36.21XYItemRendererState . . . .
36.22XYLineAndShapeRenderer .
36.23XYStepRenderer . . . . . . .
36.24XYStepAreaRenderer . . . .
36.25YIntervalRenderer . . . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
431
433
435
436
437
439
440
442
443
444
446
447
447
37 Package: org.jfree.chart.servlet
37.1 Overview . . . . . . . . . . . .
37.2 ChartDeleter . . . . . . . . . .
37.3 DisplayChart . . . . . . . . . .
37.4 ServletUtilities . . . . . . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
449
449
449
449
449
38 Package: org.jfree.chart.title
38.1 Overview . . . . . . . . . .
38.2 Events . . . . . . . . . . . .
38.3 CompositeTitle . . . . . . .
38.4 DateTitle . . . . . . . . . .
38.5 ImageTitle . . . . . . . . . .
38.6 LegendGraphic . . . . . . .
38.7 LegendItemBlockContainer
38.8 LegendTitle . . . . . . . . .
38.9 PaintScaleLegend . . . . . .
38.10TextTitle . . . . . . . . . .
38.11Title . . . . . . . . . . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
451
451
451
451
452
453
453
455
456
459
461
462
39 Package: org.jfree.chart.urls
39.1 Overview . . . . . . . . . . . . .
39.2 CategoryURLGenerator . . . . .
39.3 CustomPieURLGenerator . . . .
39.4 CustomXYURLGenerator . . . .
39.5 PieURLGenerator . . . . . . . .
39.6 StandardCategoryURLGenerator
39.7 StandardPieURLGenerator . . .
39.8 StandardXYURLGenerator . . .
39.9 StandardXYZURLGenerator . .
39.10TimeSeriesURLGenerator . . . .
39.11XYURLGenerator . . . . . . . .
39.12XYZURLGenerator . . . . . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
464
464
464
465
466
466
466
468
469
469
469
469
470
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
40 Package: org.jfree.chart.util
471
40.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 471
40.2 RelativeDateFormat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 471
CONTENTS
11
41 Package: org.jfree.data
41.1 Introduction . . . . . . . . . .
41.2 ComparableObjectItem . . .
41.3 ComparableObjectSeries . . .
41.4 DataUtilities . . . . . . . . .
41.5 DefaultKeyedValue . . . . . .
41.6 DefaultKeyedValues . . . . .
41.7 DefaultKeyedValues2D . . . .
41.8 DomainInfo . . . . . . . . . .
41.9 DomainOrder . . . . . . . . .
41.10KeyedObject . . . . . . . . .
41.11KeyedObjects . . . . . . . . .
41.12KeyedObjects2D . . . . . . .
41.13KeyedValue . . . . . . . . . .
41.14KeyedValueComparator . . .
41.15KeyedValueComparatorType
41.16KeyedValues . . . . . . . . .
41.17KeyedValues2D . . . . . . . .
41.18KeyToGroupMap . . . . . . .
41.19Range . . . . . . . . . . . . .
41.20RangeInfo . . . . . . . . . . .
41.21RangeType . . . . . . . . . .
41.22UnknownKeyException . . .
41.23Value . . . . . . . . . . . . .
41.24Values . . . . . . . . . . . . .
41.25Values2D . . . . . . . . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
474
474
474
475
476
476
477
479
479
480
480
481
482
483
484
484
484
485
486
487
488
489
489
490
490
490
42 Package: org.jfree.data.category
42.1 Introduction . . . . . . . . . . .
42.2 CategoryDataset . . . . . . . .
42.3 CategoryToPieDataset . . . . .
42.4 DefaultCategoryDataset . . . .
42.5 DefaultIntervalCategoryDataset
42.6 IntervalCategoryDataset . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
492
492
492
492
494
494
496
43 Package: org.jfree.data.contour
43.1 Introduction . . . . . . . . . . .
43.2 ContourDataset . . . . . . . . .
43.3 DefaultContourDataset . . . .
43.4 NonGridContourDataset . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
497
497
497
498
498
44 Package: org.jfree.data.function
44.1 Introduction . . . . . . . . . . .
44.2 Function2D . . . . . . . . . . .
44.3 LineFunction2D . . . . . . . . .
44.4 NormalDistributionFunction2D
44.5 PowerFunction2D . . . . . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
499
499
499
499
500
501
45 Package: org.jfree.data.gantt
45.1 Introduction . . . . . . . . .
45.2 GanttCategoryDataset . . .
45.3 Task . . . . . . . . . . . . .
45.4 TaskSeries . . . . . . . . . .
45.5 TaskSeriesCollection . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
502
502
502
503
504
505
.
.
.
.
.
.
.
.
.
.
CONTENTS
12
46 Package: org.jfree.data.general
46.1 Introduction . . . . . . . . . . .
46.2 AbstractDataset . . . . . . . .
46.3 AbstractSeriesDataset . . . . .
46.4 CombinationDataset . . . . . .
46.5 CombinedDataset . . . . . . . .
46.6 Dataset . . . . . . . . . . . . .
46.7 DatasetChangeEvent . . . . . .
46.8 DatasetChangeListener . . . . .
46.9 DatasetGroup . . . . . . . . . .
46.10DatasetUtilities . . . . . . . . .
46.11DefaultKeyedValueDataset . .
46.12DefaultKeyedValuesDataset . .
46.13DefaultKeyedValues2DDataset
46.14DefaultPieDataset . . . . . . .
46.15DefaultValueDataset . . . . . .
46.16KeyedValueDataset . . . . . . .
46.17KeyedValuesDataset . . . . . .
46.18KeyedValues2DDataset . . . .
46.19PieDataset . . . . . . . . . . .
46.20Series . . . . . . . . . . . . . .
46.21SeriesChangeEvent . . . . . . .
46.22SeriesChangeListener . . . . . .
46.23SeriesDataset . . . . . . . . . .
46.24SeriesException . . . . . . . . .
46.25SubSeriesDataset . . . . . . . .
46.26ValueDataset . . . . . . . . . .
46.27WaferMapDataset . . . . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
508
508
508
509
510
510
510
511
511
511
512
515
515
516
516
517
518
518
519
519
519
521
521
522
522
523
523
523
47 Package: org.jfree.data.jdbc
47.1 Introduction . . . . . . . . .
47.2 JDBCCategoryDataset . . .
47.3 JDBCPieDataset . . . . . .
47.4 JDBCXYDataset . . . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
524
524
524
525
525
48 Package: org.jfree.data.statistics
48.1 Introduction . . . . . . . . . . . . . . . .
48.2 BoxAndWhiskerCalculator . . . . . . . .
48.3 BoxAndWhiskerCategoryDataset . . . .
48.4 BoxAndWhiskerItem . . . . . . . . . . .
48.5 BoxAndWhiskerXYDataset . . . . . . .
48.6 DefaultBoxAndWhiskerCategoryDataset
48.7 DefaultBoxAndWhiskerXYDataset . . .
48.8 DefaultStatisticalCategoryDataset . . .
48.9 HistogramBin . . . . . . . . . . . . . . .
48.10HistogramDataset . . . . . . . . . . . .
48.11HistogramType . . . . . . . . . . . . . .
48.12MeanAndStandardDeviation . . . . . . .
48.13Regression . . . . . . . . . . . . . . . . .
48.14SimpleHistogramBin . . . . . . . . . . .
48.15SimpleHistogramDataset . . . . . . . . .
48.16StatisticalCategoryDataset . . . . . . . .
48.17Statistics . . . . . . . . . . . . . . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
527
527
527
528
529
529
530
531
531
533
533
535
536
536
537
538
540
541
.
.
.
.
.
.
.
.
CONTENTS
13
49 Package: org.jfree.data.time
49.1 Introduction . . . . . . . . . .
49.2 DateRange . . . . . . . . . .
49.3 Day . . . . . . . . . . . . . .
49.4 DynamicTimeSeriesCollection
49.5 FixedMillisecond . . . . . . .
49.6 Hour . . . . . . . . . . . . . .
49.7 Millisecond . . . . . . . . . .
49.8 Minute . . . . . . . . . . . . .
49.9 Month . . . . . . . . . . . . .
49.10MovingAverage . . . . . . . .
49.11Quarter . . . . . . . . . . . .
49.12RegularTimePeriod . . . . . .
49.13Second . . . . . . . . . . . . .
49.14SimpleTimePeriod . . . . . .
49.15TimePeriod . . . . . . . . . .
49.16TimePeriodAnchor . . . . . .
49.17TimePeriodFormatException
49.18TimePeriodValue . . . . . . .
49.19TimePeriodValues . . . . . .
49.20TimePeriodValuesCollection .
49.21TimeSeries . . . . . . . . . .
49.22TimeSeriesCollection . . . . .
49.23TimeSeriesDataItem . . . . .
49.24TimeSeriesTableModel . . . .
49.25TimeTableXYDataset . . . .
49.26Week . . . . . . . . . . . . . .
49.27Year . . . . . . . . . . . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
543
543
543
543
545
547
547
548
549
550
551
552
553
555
556
556
557
557
557
558
560
562
567
570
570
571
573
574
50 Package: org.jfree.data.time.ohlc
50.1 Introduction . . . . . . . . . . . .
50.2 OHLC . . . . . . . . . . . . . . .
50.3 OHLCItem . . . . . . . . . . . .
50.4 OHLCSeries . . . . . . . . . . . .
50.5 OHLCSeriesCollection . . . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
576
576
576
577
578
578
51 Package: org.jfree.data.xml
51.1 Introduction . . . . . . . .
51.2 Usage . . . . . . . . . . .
51.3 CategoryDatasetHandler .
51.4 CategorySeriesHandler . .
51.5 DatasetReader . . . . . .
51.6 DatasetTags . . . . . . . .
51.7 ItemHandler . . . . . . . .
51.8 KeyHandler . . . . . . . .
51.9 PieDatasetHandler . . . .
51.10RootHandler . . . . . . .
51.11ValueHandler . . . . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
581
581
581
581
582
582
582
583
583
583
584
584
52 Package: org.jfree.data.xy
52.1 Introduction . . . . . . . . .
52.2 AbstractIntervalXYDataset
52.3 AbstractXYDataset . . . .
52.4 AbstractXYZDataset . . . .
52.5 CategoryTableXYDataset .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
585
585
585
585
586
586
CONTENTS
14
52.6 DefaultHighLowDataset .
52.7 DefaultIntervalXYDataset
52.8 DefaultOHLCDataset . .
52.9 DefaultTableXYDataset .
52.10DefaultWindDataset . . .
52.11DefaultXYDataset . . . .
52.12DefaultXYZDataset . . .
52.13IntervalXYDataset . . . .
52.14IntervalXYDelegate . . . .
52.15IntervalXYZDataset . . .
52.16MatrixSeries . . . . . . . .
52.17MatrixSeriesCollection . .
52.18NormalizedMatrixSeries .
52.19OHLCDataItem . . . . . .
52.20OHLCDataset . . . . . . .
52.21TableXYDataset . . . . .
52.22WindDataset . . . . . . .
52.23XisSymbolic . . . . . . . .
52.24XYBarDataset . . . . . .
52.25XYDataItem . . . . . . .
52.26XYDataset . . . . . . . .
52.27XYDatasetTableModel . .
52.28XYSeries . . . . . . . . .
52.29XYSeriesCollection . . . .
52.30XYZDataset . . . . . . . .
52.31YisSymbolic . . . . . . . .
A Migration
A.1 Introduction .
A.2 1.0.3 to 1.0.4
A.3 1.0.2 to 1.0.3
A.4 1.0.1 to 1.0.2
A.5 1.0.0 to 1.0.1
A.6 0.9.x to 1.0.0
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
588
589
591
592
594
596
598
600
600
602
602
603
604
605
606
607
607
608
608
610
611
612
614
617
619
619
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
620
620
620
621
622
623
623
B JCommon
B.1 Introduction . . .
B.2 Align . . . . . . .
B.3 PublicCloneable .
B.4 RectangleAnchor
B.5 RectangleEdge .
B.6 RectangleInsets .
B.7 TextAnchor . . .
B.8 UnitType . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
624
624
624
625
625
625
626
628
628
GNU Lesser General Public Licence
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
The Licence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Frequently Asked Questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
629
629
629
635
C The
C.1
C.2
C.3
.
.
.
.
.
.
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 C 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:
15
CHAPTER 1. INTRODUCTION
16
• 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, among other things);
• 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
17
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.
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:
Richard Atkinson, David Berry, Anthony Boulestreau, Jeremy Bowman, Daniel Bridenbecker, Nicolas Brodu, David Browning, Søren Caspersen, Chuanhao Chiu, Pascal Collet, Martin Cordova, Paolo Cova, Michael Duffy, Jonathan Gabbai, Serge V. Grachov,
Hans-Jurgen Greiner, Joao Guilherme Del Valle, Aiman Han, Jon Iles, Wolfgang Irler, Xun Kang, Bill Kelemen, Norbert Kiesel, Gideon Krause, Arnaud Lelievre, David
Li, Tin Luu, Craig MacFarlane, Achilleus Mantzios, Thomas Meier, Aaron Metzger,
Jim Moore, Jonathan Nash, Barak Naveh, David M. O’Donnell, Krzysztof Paz, Tomer
Peretz, Andrzej Porebski, Luke Quinane, Viktor Rajewski, Eduardo Ramalho, Michael
Rauch, Cameron Riley, Dan Rivett, Michel Santos, Thierry Saura, Andreas Schneider,
Jean-Luc Schwab, Bryan Scott, Roger Studner, Irv Thomae, Eric Thomas, Rich Unger,
Daniel van Enckevort, Laurence Vanhelsuwé, Sylvain Vieujot, Jelai Wang, Mark Watson,
Alex Weber, Matthew Wright, 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.4-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.
18
CHAPTER 2. SAMPLE CHARTS
19
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
20
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
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
21
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
22
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
23
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
24
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
25
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
26
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
27
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
28
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
29
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
30
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
31
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
32
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.4.tar.gz
jfreechart-1.0.4.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.8). 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.4) 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:
33
CHAPTER 3. DOWNLOADING AND INSTALLING JFREECHART
34
tar xvzf jfreechart-1.0.4.tar.gz
This will extract all the source, run-time and documentation files for JFreeChart into a new directory
called jfreechart-1.0.4.
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.4.zip
This will extract all the source, run-time and documentation files for JFreeChart into a new directory
called jfreechart-1.0.4.
3.3.3
The Files
The top-level directory (jfreechart-1.0.4) contains the files and directories listed in the following
table:
File/Directory:
Description:
ant
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 a script to generate the JFreeChart
API documentation using the gjdoc utility.
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 detailed log of changes made to JFreeChart.
An older change log.
A runnable jar file containing demo applications.
The JFreeChart licence (GNU LGPL).
Project news.
Important information - read this first!
checkstyle
experimental
gjdoc
lib
source
swt
tests
ChangeLog
CHANGELOG.txt
jfreechart-1.0.4-demo.jar
licence-LGPL.txt
NEWS
README.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.4-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.4-demos.zip on the download page for the JFreeChart Developer Guide.
CHAPTER 3. DOWNLOADING AND INSTALLING JFREECHART
3.5
35
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/
3.6
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.4
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:
36
CHAPTER 4. USING JFREECHART
37
// 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
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);
// 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.
Section colours are defined using a three layer attribute mechanism that is common throughout
JFreeChart. However, it is typical for the section fill colours to be defined on a per series basis, so
we’ll ignore the additional methods for now—for more information, refer to the reference section
for the PiePlot class (section 33.27).
1 Inside
the lookupSectionPaint(Comparable, boolean) method of the PiePlot class.
39
CHAPTER 5. PIE CHARTS
5.4
40
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
41
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
42
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
43
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.1
1 In section xxx, we’ll cover the special cases where the data table has just one row of data (a single series) or just
one column of data (a single category).
44
CHAPTER 6. BAR CHARTS
45
Figure 6.2: A bar chart (see BarExample1.java)
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.
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);
CHAPTER 6. BAR CHARTS
46
• 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;
• 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) {
CHAPTER 6. BAR CHARTS
47
BarExample1 demo = new BarExample1("Bar Demo 1");
demo.pack();
RefineryUtilities.centerFrameOnScreen(demo);
demo.setVisible(true);
}
}
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
ValueAxis valueAxis = new NumberAxis(valueAxisLabel);
3
BarRenderer renderer = new BarRenderer();
[snip...]
4
CategoryPlot plot = new CategoryPlot(dataset, categoryAxis, valueAxis,
5
renderer);
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.
CHAPTER 6. BAR CHARTS
6.4
48
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:
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);
CHAPTER 6. BAR CHARTS
49
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.
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.2 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)
2 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");
50
CHAPTER 7. LINE CHARTS
51
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
52
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());
53
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);
}
}
54
CHAPTER 7. LINE CHARTS
7.3
55
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
56
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
57
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}.
* <p>
* 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;
}
58
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);
}
}
59
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
60
CHAPTER 8. TIME SERIES CHARTS
61
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
62
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.
* <p>
* 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;
}
/**
63
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.
64
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);
}
}
65
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):
66
CHAPTER 9. CUSTOMISING CHARTS
67
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
68
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
69
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
70
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.
71
CHAPTER 10. DYNAMIC CHARTS
10.2.2
72
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
73
}
}
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.
* <p>
* 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.
74
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);
}
});
}
}
75
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):
76
CHAPTER 11. TOOLTIPS
77
å 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.
78
CHAPTER 12. ITEM LABELS
12.1.2
79
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
80
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
81
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
82
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
83
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 (<code>null</code> not permitted).
* @param series the series index (zero-based).
* @param category the category index (zero-based).
*
* @return the label (possibly <code>null</code>).
*/
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();
84
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);
}
}
85
CHAPTER 12. ITEM LABELS
12.7
Example 2 - Displaying Percentages
12.7.1
Overview
86
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 <code>null</code>,
* the total of all items in the series is used.
*
* @param category the category index (<code>null</code> 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 (<code>null</code> not permitted).
* @param series the series index (zero-based).
* @param category the category index (zero-based).
*
* @return the label (possibly <code>null</code>).
*/
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();
}
}
87
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;
88
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);
}
}
89
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.
90
CHAPTER 13. MULTIPLE AXES AND DATASETS
13.2.2
91
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
92
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.
93
CHAPTER 14. COMBINED CHARTS
14.2.2
94
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
95
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
96
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
97
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
98
CHAPTER 15. DATASETS AND JDBC
99
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
100
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
101
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 1.3.
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.
102
CHAPTER 16. EXPORTING CHARTS TO ACROBAT PDF
103
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.4.jar
jcommon-1.0.8.jar
itext-1.3.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
104
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
105
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.
* <P>
* 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 {
106
CHAPTER 16. EXPORTING CHARTS TO ACROBAT PDF
107
// 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
108
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
109
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
110
CHAPTER 17. EXPORTING CHARTS TO SVG FORMAT
17.3.2
111
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.8.jar
jfreechart-1.0.4.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
112
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.
113
CHAPTER 18. APPLETS
18.2.1
114
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
115
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:
<APPLET ARCHIVE="jfreechart-1.0.4-applet-demo.jar,
jfreechart-1.0.4.jar,jcommon-1.0.8.jar"
CODE="demo.applet.Applet1" width=640 height=260
ALT="You should see an applet, not this text.">
</APPLET>
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);
}
}
}
116
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.4-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.
117
CHAPTER 19. SERVLETS
118
• 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
119
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.4-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.4.jar:lib/jcommon-1.0.8.jar:lib/servlet.jar
source/demo/ServletDemo1.java
CHAPTER 19. SERVLETS
120
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.4.jar
.../jfreechart1/WEB-INF/lib/jcommon-1.0.8.jar
.../jfreechart1/WEB-INF/classes/demo/ServletDemo1.class
You need to create the web.xml file—it provides information about the servlet:
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
"http://java.sun.com/j2ee/dtds/web-app_2.2.dtd">
<web-app>
<servlet>
<servlet-name>
ServletDemo1
</servlet-name>
<servlet-class>
demo.ServletDemo1
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ServletDemo1</servlet-name>
<url-pattern>/servlet/ServletDemo1</url-pattern>
</servlet-mapping>
</web-app>
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.4-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
121
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.
* <P>
* This servlet uses another servlet (ServletDemo2ChartGenerator) to create a PNG image
* for the embedded chart.
* <P>
* 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.
* <P>
* 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
122
throws ServletException, IOException {
PrintWriter out = new PrintWriter(response.getWriter());
try {
String param = request.getParameter("chart");
response.setContentType("text/html");
out.println("<HTML>");
out.println("<HEAD>");
out.println("<TITLE>JFreeChart Servlet Demo 2</TITLE>");
out.println("</HEAD>");
out.println("<BODY>");
out.println("<H2>JFreeChart Servlet Demo</H2>");
out.println("<P>");
out.println("Please choose a chart type:");
out.println("<FORM ACTION=\"ServletDemo2\" METHOD=POST>");
String pieChecked = (param.equals("pie") ? " CHECKED" : "");
String barChecked = (param.equals("bar") ? " CHECKED" : "");
String timeChecked = (param.equals("time") ? " CHECKED" : "");
out.println("<INPUT TYPE=\"radio\" NAME=\"chart\" VALUE=\"pie\"" + pieChecked
+ "> Pie Chart");
out.println("<INPUT TYPE=\"radio\" NAME=\"chart\" VALUE=\"bar\"" + barChecked
+ "> Bar Chart");
out.println("<INPUT TYPE=\"radio\" NAME=\"chart\" VALUE=\"time\"" + timeChecked
+ "> Time Series Chart");
out.println("<P>");
out.println("<INPUT TYPE=\"submit\" VALUE=\"Generate Chart\">");
out.println("</FORM>");
out.println("<P>");
out.println("<IMG SRC=\"ServletDemo2ChartGenerator?type=" + param
+ "\" BORDER=1 WIDTH=400 HEIGHT=300/>");
out.println("</BODY>");
out.println("</HTML>");
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 <IMG> 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 <FORM> 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.
* <P>
* Three different charts can be generated, controlled by the ’type’ parameter. The possible
* values are ’pie’, ’bar’ and ’time’ (for time series).
* <P>
* 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();
123
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...
124
CHAPTER 19. SERVLETS
125
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.4.jar:lib/jcommon-1.0.8.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:
<HTML>
<HEADER>
<TITLE>JFreeChart : Basic Servlet Demo</TITLE>
</HEADER>
<BODY>
<H2>JFreeChart: Basic Servlet Demo</H2>
<P>
There are two sample servlets available:
<ul>
<li>a very basic servlet to generate a <a
href="servlet/ServletDemo1">bar chart</a>;</li>
<li>another servlet that allow you to select one of <a
href="chart.html">three sample charts</a>. The selected chart is
displayed in an HTML page.</li>
</ul>
</BODY>
</HTML>
There are two hyperlinks in this page, the first references the first demo servlet (ServletDemo1) and
the second references another HTML page, chart.html:
<HTML>
<HEADER>
<TITLE>JFreeChart Servlet Demo 2</TITLE>
</HEADER>
<BODY>
<H2>JFreeChart Servlet Demo</H2>
<P>
Please choose a chart type:
<FORM ACTION="servlet/ServletDemo2" METHOD=POST>
<INPUT TYPE="radio" NAME="chart" VALUE="pie" CHECKED> Pie Chart
<INPUT TYPE="radio" NAME="chart" VALUE="bar"> 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
126
<INPUT TYPE="radio" NAME="chart" VALUE="time"> Time Series Chart
<P>
<INPUT TYPE="submit" VALUE="Generate Chart">
</FORM>
</BODY>
</HTML>
This second HTML page contains a <FORM> 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 <IMG> 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:
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
"http://java.sun.com/j2ee/dtds/web-app_2.2.dtd">
<web-app>
<servlet>
<servlet-name>
ServletDemo1
</servlet-name>
<servlet-class>
demo.ServletDemo1
</servlet-class>
</servlet>
<servlet>
<servlet-name>
ServletDemo2
</servlet-name>
<servlet-class>
demo.ServletDemo2
</servlet-class>
</servlet>
<servlet>
<servlet-name>
ServletDemo2ChartGenerator
</servlet-name>
<servlet-class>
demo.ServletDemo2ChartGenerator
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ServletDemo1</servlet-name>
<url-pattern>/servlet/ServletDemo1</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>ServletDemo2</servlet-name>
<url-pattern>/servlet/ServletDemo2</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>ServletDemo2ChartGenerator</servlet-name>
<url-pattern>/servlet/ServletDemo2ChartGenerator</url-pattern>
</servlet-mapping>
</web-app>
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
127
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.8.jar
webapps/jfreechart2/WEB-INF/lib/jfreechart-1.0.4.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.
128
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.
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.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.
129
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:
å public static JFreeChart createPieChart(String title, PieDataset dataset,
boolean legend, boolean tooltips, boolean urls);
Creates a pie chart for the specified PieDataset (null permitted). The chart is constructed
using a PiePlot.
To create a pie chart with a “3D effect”:
130
CHAPTER 22. PACKAGE: ORG.JFREE.CHART
131
å 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.
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”:
å 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.
CHAPTER 22. PACKAGE: ORG.JFREE.CHART
22.3.4
132
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:
å 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:
CHAPTER 22. PACKAGE: ORG.JFREE.CHART
133
å 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 BoxAndWhiskerCategoryRenderer.
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.
22.4.2
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.
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.
CHAPTER 22. PACKAGE: ORG.JFREE.CHART
22.5.2
134
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.
å public ChartEntity getEntity();
Returns the chart entity underneath the mouse pointer (this may be null).
22.5.4
Notes
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).
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.
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.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;
CHAPTER 22. PACKAGE: ORG.JFREE.CHART
135
• printing – print a chart via the standard Java printing facilities;
• saving – write the chart to a PNG format file;
• 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).
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.
å 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.
CHAPTER 22. PACKAGE: ORG.JFREE.CHART
136
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.
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.
22.7.7
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.
CHAPTER 22. PACKAGE: ORG.JFREE.CHART
137
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.
å 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.
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:
å 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.
CHAPTER 22. PACKAGE: ORG.JFREE.CHART
22.7.9
138
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):
å public Rectangle2D getScreenDataArea();
Returns the area within which the data is plotted on the screen. This takes into account any
scaling applied by the panel.
å public Rectangle2D getScreenDataArea(int x, int y);
Returns the area within which the data is plotted on the screen, for the subplot at (x, y). This
takes into account any scaling applied by the panel.
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.
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.
CHAPTER 22. PACKAGE: ORG.JFREE.CHART
22.8.2
139
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.
22.8.4
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.
CHAPTER 22. PACKAGE: ORG.JFREE.CHART
22.9
ChartUtilities
22.9.1
Overview
140
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:
å 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.
CHAPTER 22. PACKAGE: ORG.JFREE.CHART
22.9.3
141
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);
Saves a chart to a JPEG format image file.
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. If an info object is supplied, it will be populated
with information about the structure of the chart.
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.
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 <MAP> 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.
CHAPTER 22. PACKAGE: ORG.JFREE.CHART
22.11
DrawableLegendItem
22.11.1
Overview
142
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.
22.13
JFreeChart
22.13.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).
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:
22.13.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:
CHAPTER 22. PACKAGE: ORG.JFREE.CHART
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
or
an
IntervalXYBarRenderer.
CompassPlot, MeterPlot and ThermometerPlot.
XYPlot
with
a
HighLowRenderer
or
a
CandlestickRenderer.
PiePlot.
CategoryPlot with a classfStatisticalBarRenderer.
XYPlot with various renderers.
XYPlot with an XYBubbleRenderer.
WaferMapPlot.
XYPlot with a WindItemRenderer.
ContourDataset
GanttCategoryDataset
IntervalCategoryDataset
IntervalXYDataset
MeterDataset
OHLCDataset
PieDataset
StatisticalCategoryDataset
XYDataset
XYZDataset
WaferMapDataset
WindDataset
143
Table 22.1: Compatible plot and dataset types
å 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.13.3
Attributes
The attributes maintained by the JFreeChart class are listed in Table 22.2.
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
Table 22.2: Attributes for the JFreeChart class
CHAPTER 22. PACKAGE: ORG.JFREE.CHART
22.13.4
144
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:
å 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.
You can control whether or not the chart is drawn with anti-aliasing (switching anti-aliasing on can
improve the on-screen appearance of charts):
å public void setAntiAlias(boolean flag);
Sets a flag controlling whether or not anti-aliasing is used when drawing the chart.
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.13.5
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:
CHAPTER 22. PACKAGE: ORG.JFREE.CHART
145
å 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.
22.13.6
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.
å 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.13.7
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.
CHAPTER 22. PACKAGE: ORG.JFREE.CHART
146
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);
22.13.8
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.13.9
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.14
LegendItem
22.14.1
Overview
A class that records the attributes of an item that should appear in a legend. 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.
CHAPTER 22. PACKAGE: ORG.JFREE.CHART
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.
147
Table 22.3: Attributes for the LegendItem class
22.14.2
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.14.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.
CHAPTER 22. PACKAGE: ORG.JFREE.CHART
148
å 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.
å 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.14.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.
CHAPTER 22. PACKAGE: ORG.JFREE.CHART
149
See Also
LegendItemCollection, LegendTitle.
22.15
LegendItemCollection
22.15.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.
22.15.2
Constructors
There is a single constructor:
å public LegendItemCollection();
Creates a new empty collection.
22.15.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.15.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.
CHAPTER 22. PACKAGE: ORG.JFREE.CHART
ID:
Description:
LegendRenderingOrder.STANDARD
LegendRenderingOrder.REVERSE
Items are rendered in order.
Items are rendered in reverse order.
150
Table 22.4: Tokens defined by LegendRenderingOrder
22.16
LegendItemSource
22.16.1
Overview
An interface for obtaining a collection of legend items. This interface is implemented (or extended)
by:
• CategoryPlot;
• CategoryItemRenderer;
• XYPlot;
• 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.
22.16.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.17
LegendRenderingOrder
22.17.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.17.2
Notes
This class is a left-over from older versions of JFreeChart, and is not currently used. It should
probably be deprecated.
22.18
PolarChartPanel
22.18.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;
• XYDrawableAnnotation;
• XYImageAnnotation;
• XYLineAnnotation;
• XYPolygonAnnotation;
• XYShapeAnnotation;
• XYTextAnnotation.
23.2.2
Constructors
This class defines a single (protected) constructor:
å protected AbstractXYAnnotation();
Initialises the tool tip text and URL to null.
151
CHAPTER 23. PACKAGE: ORG.JFREE.CHART.ANNOTATIONS
23.2.3
152
Methods
To access the tool tip text for the annotation:
å public String getToolTipText();
Returns the tool tip text for this annotation. This may be null.
å public void setToolTipText(String text);
Sets the tool tip text for this annotation (null is permitted).
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. This may be
null.
å public void setURL(String url);
Sets the URL that will be used for this annotation in an HTML image map (null is permitted).
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.
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.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. 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.5
Notes
There is no event notification mechanism for annotations, so when you update an annotation, the
chart display will not automatically be refreshed.
23.3
CategoryAnnotation
23.3.1
Overview
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).
CHAPTER 23. PACKAGE: ORG.JFREE.CHART.ANNOTATIONS
23.3.2
153
Methods
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.
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).
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.
23.4.3
Methods
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).
CHAPTER 23. PACKAGE: ORG.JFREE.CHART.ANNOTATIONS
154
å 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).
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.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. 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.
To get a hash code for this annotation:
å public int hashCode();
Returns a hash code for this annotation.
Instances of this class are cloneable and serializable.
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. This class was introduced in JFreeChart 1.0.3.
23.5.2
Constructors
To create a new instance:
å public CategoryPointerAnnotation(String label, Comparable key, double value, double angle);
Creates a new pointer annotation.
23.5.3
Methods
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 point on the chart.
CHAPTER 23. PACKAGE: ORG.JFREE.CHART.ANNOTATIONS
155
å 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.
å 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.
å 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.
å 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.
å 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.
å 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.
å 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.
å 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.
To draw the annotation:
å 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.
23.5.4
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.
To clone the annotation:
å public Object clone() throws CloneNotSupportedException; [1.0.3]
Returns a clone of this annotation.
CHAPTER 23. PACKAGE: ORG.JFREE.CHART.ANNOTATIONS
23.5.5
156
Notes
Some points to note:
• this class is a subclass of CategoryTextAnnotation.
23.6
CategoryTextAnnotation
23.6.1
Overview
An annotation that can be used to display an item of text at some location (defined by a (category,
value) pair) on a CategoryPlot.
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
Methods
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.
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.
å public void setCategoryAnchor(CategoryAnchor anchor);
Sets the category anchor point, which is used to determine the position of the alignment point
for the annotation.
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.
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.
CHAPTER 23. PACKAGE: ORG.JFREE.CHART.ANNOTATIONS
23.6.4
157
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:
å public Object clone() throws CloneNotSupportedException;
Returns a clone of this annotation.
23.6.5
Notes
Some points to note:
• there is no event notification for annotations, so automatic chart redrawing does not occur
when an annotation is updated;
• this class is a subclass of TextAnnotation.
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:
• font = new Font("SansSerif", Font.PLAIN, 10);
• paint = Color.black;
• textAnchor = TextAnchor.CENTER;
• rotationAnchor = TextAnchor.CENTER;
• rotationAngle = 0.0;
23.7.3
Methods
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.
CHAPTER 23. PACKAGE: ORG.JFREE.CHART.ANNOTATIONS
158
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.
To get a hash code:
å public int hashCode();
Returns a hash code for this annotation.
23.7.5
Notes
The XYTextAnnotation class is NOT a subclass of this class.
23.8
XYAnnotation
23.8.1
Overview
The interface that must be supported by annotations that are to be added to an XYPlot.
This interface is implemented by:
• XYBoxAnnotation;
CHAPTER 23. PACKAGE: ORG.JFREE.CHART.ANNOTATIONS
159
• XYDrawableAnnotation;
• XYImageAnnotation;
• XYLineAnnotation;
• XYPointerAnnotation;
• XYPolygonAnnotation;
• XYShapeAnnotation;
• XYTextAnnotation;
You can, of course, provide your own implementations of the interface.
23.8.2
Methods
This class 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.
See Also
AbstractXYAnnotation.
23.9
XYBoxAnnotation
23.9.1
Overview
An annotation that highlights a rectangular region within the data area of an XYPlot. XYBoxAnnotation is a subclass of AbstractXYAnnotation.
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.
CHAPTER 23. PACKAGE: ORG.JFREE.CHART.ANNOTATIONS
23.9.3
160
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:
• obj is not null;
• obj is an instance of XYBoxAnnotation;
• both annotations have the same attributes.
å public int hashCode();
Returns a hash code for this annotation.
Instances of this class are cloneable (this class implements 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.
23.10
XYDrawableAnnotation
23.10.1
Overview
An annotation 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).
23.10.2
Notes
See the MarkerDemo1.java source file in the JFreeChart demo collection for an example.
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:
CHAPTER 23. PACKAGE: ORG.JFREE.CHART.ANNOTATIONS
161
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.
23.11.5
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).
CHAPTER 23. PACKAGE: ORG.JFREE.CHART.ANNOTATIONS
23.11.6
162
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.
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.
23.12.4
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.
CHAPTER 23. PACKAGE: ORG.JFREE.CHART.ANNOTATIONS
23.12.5
163
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”.
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.1). The arrow can have a label at one end.
Figure 23.1: 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);
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
Methods
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.
CHAPTER 23. PACKAGE: ORG.JFREE.CHART.ANNOTATIONS
164
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).
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.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).
CHAPTER 23. PACKAGE: ORG.JFREE.CHART.ANNOTATIONS
23.14.2
165
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.
å 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.
CHAPTER 23. PACKAGE: ORG.JFREE.CHART.ANNOTATIONS
23.14.6
166
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.
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 Cloneable1 and Serializable.
1 Technically,
this probably isn’t necessary since instances of this class are immutable.
CHAPTER 23. PACKAGE: ORG.JFREE.CHART.ANNOTATIONS
23.15.5
167
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.
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.
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
Methods
This class defines methods to get and set the x and y values (defining the location of the annotation
against the domain and range axes):
å 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.
å 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.
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);
23.16.5
Notes
Some points to note:
• this class is cloneable and serializable;
• the AnnotationDemo1.java application (included in the JFreeChart demo collection) provides
an example;
CHAPTER 23. PACKAGE: ORG.JFREE.CHART.ANNOTATIONS
168
• the XYPointerAnnotation subclass can be used to display a label with an arrow pointing to
some (x, y) value.
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.
169
CHAPTER 24. PACKAGE: ORG.JFREE.CHART.AXIS
170
Axis
ValueAxis
CategoryAxis
DateAxis
NumberAxis
SubCategoryAxis
CategoryAxis3D
NumberAxis3D
SymbolAxis
LogarithmicAxis
Figure 24.1: Axis classes
Attribute:
Description:
plot
visible
label
labelFont
labelPaint
labelInsets
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 color for the axis label.
The space to leave around the outside of 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
171
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.
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:
å 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.
CHAPTER 24. PACKAGE: ORG.JFREE.CHART.AXIS
24.2.7
172
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.
å 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).
å 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).
å 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:
å public boolean isTickLabelsVisible();
Returns the flag that controls whether or not the tick labels are visible.
å 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.
å public void setTickLabelFont(Font font);
Sets the tick label font and sends an AxisChangeEvent to all registered listeners.
CHAPTER 24. PACKAGE: ORG.JFREE.CHART.AXIS
173
To control the paint used to draw the tick labels:
å public Paint getTickLabelPaint();
Returns the tick label paint.
å public void setTickLabelPaint(Paint paint);
Sets the tick label paint and sends an AxisChangeEvent to all registered listeners.
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.
24.2.10
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.
CHAPTER 24. PACKAGE: ORG.JFREE.CHART.AXIS
24.3
AxisCollection
24.3.1
Overview
174
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.
24.5
AxisSpace
24.5.1
Overview
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.
CHAPTER 24. PACKAGE: ORG.JFREE.CHART.AXIS
24.5.2
175
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.
24.6.2
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).
CHAPTER 24. PACKAGE: ORG.JFREE.CHART.AXIS
24.8
CategoryAxis
24.8.1
Overview
176
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.5.
24.8.2
Constructor
There is a single 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.
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).
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
Table 24.3: Attributes for the CategoryAxis class
The following default values are used:
Default:
Value:
DEFAULT AXIS MARGIN
DEFAULT CATEGORY MARGIN
0.05 (5 percent).
0.20 (20 percent).
CHAPTER 24. PACKAGE: ORG.JFREE.CHART.AXIS
24.8.4
177
Setting Axis Margins
To set the lower margin for the axis:
å 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 set the upper margin for the axis:
å 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 set the margin 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.
24.8.5
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.
å 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.
å 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 set the position of the category labels:
å public void setCategoryLabelPositions(CategoryLabelPositions positions);
Sets the attribute that controls the position, alignment and rotation of the category labels
along the axis.
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.
CHAPTER 24. PACKAGE: ORG.JFREE.CHART.AXIS
178
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.6
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:
å 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.7
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.
24.8.8
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:
CHAPTER 24. PACKAGE: ORG.JFREE.CHART.AXIS
179
å 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:
å 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.
24.8.9
Cloning and Serialization
This class is Cloneable and Serializable.
24.8.10
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.
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).
24.9.3
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.
CHAPTER 24. PACKAGE: ORG.JFREE.CHART.AXIS
180
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.
24.11
CategoryLabelPositions
24.11.1
Overview
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:
CHAPTER 24. PACKAGE: ORG.JFREE.CHART.AXIS
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
181
Table 24.4: Static instances of the CategoryLabelPositions class
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
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.
24.12.3
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.
CHAPTER 24. PACKAGE: ORG.JFREE.CHART.AXIS
24.13
CategoryTick
24.13.1
Overview
182
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.
24.15.3
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.
CHAPTER 24. PACKAGE: ORG.JFREE.CHART.AXIS
183
å 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).
å 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.
CHAPTER 24. PACKAGE: ORG.JFREE.CHART.AXIS
24.17
DateAxis
24.17.1
Overview
184
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.42.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.
24.17.4
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.42.3 for information about the attributes inherited by this class.
CHAPTER 24. PACKAGE: ORG.JFREE.CHART.AXIS
24.17.5
185
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:1
å 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.
24.17.7
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);
1 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
186
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.
24.17.10
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.
CHAPTER 24. PACKAGE: ORG.JFREE.CHART.AXIS
187
å 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.
å 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.
CHAPTER 24. PACKAGE: ORG.JFREE.CHART.AXIS
24.17.11
188
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.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.
CHAPTER 24. PACKAGE: ORG.JFREE.CHART.AXIS
24.20.2
189
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).
24.20.4
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.
CHAPTER 24. PACKAGE: ORG.JFREE.CHART.AXIS
24.21.2
190
Notes
Some points to note:
• a couple of demos (SurveyResultsDemo2.java and SurveyResultsDemo3.java) are included in
the JFreeChart demo collection.
24.22
LogarithmicAxis
24.22.1
Overview
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.
24.22.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.22.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.
CHAPTER 24. PACKAGE: ORG.JFREE.CHART.AXIS
24.22.4
191
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.
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.22.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.22.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.
CHAPTER 24. PACKAGE: ORG.JFREE.CHART.AXIS
24.23
MarkerAxisBand
24.23.1
Overview
192
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.
24.24
ModuloAxis
24.24.1
Overview
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.24.2
Constructor
There is a single constructor:
å public ModuloAxis(String label, Range fixedRange);
Creates a new axis with the specified label and fixedRange.
24.24.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).
CHAPTER 24. PACKAGE: ORG.JFREE.CHART.AXIS
193
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.
24.24.4
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.25
MonthDateFormat
24.25.1
Overview
A custom date formatter that displays the month and, optionally, the year. This formatter is
typically used with the PeriodAxis class. An examples 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.25.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:
CHAPTER 24. PACKAGE: ORG.JFREE.CHART.AXIS
194
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:
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.25.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.26
NumberAxis
24.26.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.
CHAPTER 24. PACKAGE: ORG.JFREE.CHART.AXIS
24.26.2
195
Usage
A NumberAxis can be used for:
• the range axis in a CategoryPlot.
• the domain and/or range axes in an XYPlot;
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.2
24.26.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.26.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
2 If
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"));
you are sure of what you are doing, you can drop the instanceof check.
CHAPTER 24. PACKAGE: ORG.JFREE.CHART.AXIS
24.26.5
196
The Axis Range
You can control most aspects of the axis range using methods inherited from the ValueAxis class—
see section 24.42.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).
å 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.26.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.
CHAPTER 24. PACKAGE: ORG.JFREE.CHART.AXIS
24.26.7
197
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%¨
));
24.26.8
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.26.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.
CHAPTER 24. PACKAGE: ORG.JFREE.CHART.AXIS
24.26.10
198
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.
24.26.11
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.26.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.26.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.27
NumberAxis3D
24.27.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.
CHAPTER 24. PACKAGE: ORG.JFREE.CHART.AXIS
24.27.2
199
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).
24.27.3
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.27.4
Notes
Ideally, this class will be combined with the NumberAxis class.
See Also
CategoryAxis3D.
24.28
NumberTick
24.28.1
Overview
A class used to represent a single tick on a NumberAxis.
24.28.2
Usage
This class is used internally and it is unlikely that you should ever need to use it directly.
24.29
NumberTickUnit
24.29.1
Overview
A number tick unit for use by subclasses of NumberAxis (extends the TickUnit class).
24.29.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).
CHAPTER 24. PACKAGE: ORG.JFREE.CHART.AXIS
24.29.3
200
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.
24.29.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.29.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.29.6
Notes
This class is immutable, a requirement for all subclasses of TickUnit.
See Also
DateTickUnit.
24.30
PeriodAxis
24.30.1
Overview
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.
24.30.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.
CHAPTER 24. PACKAGE: ORG.JFREE.CHART.AXIS
201
Figure 24.7: A chart that uses a PeriodAxis
24.30.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):
å 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.30.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.
CHAPTER 24. PACKAGE: ORG.JFREE.CHART.AXIS
202
å 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.30.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.30.6
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.30.7
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.
å 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.
CHAPTER 24. PACKAGE: ORG.JFREE.CHART.AXIS
24.30.8
203
Notes
Some points to note:
• two demos (PeriodAxisDemo1.java and PeriodAxisDemo2.java) are included in the JFreeChart
demo collection.
See Also
DateAxis, PeriodAxisLabelInfo.
24.31
PeriodAxisLabelInfo
24.31.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.
24.31.2
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.31.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.
CHAPTER 24. PACKAGE: ORG.JFREE.CHART.AXIS
204
å 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.31.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.
24.32
QuarterDateFormat
24.32.1
Overview
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).
24.32.2
Constructors
The following constructors are available:
å public QuarterDateFormat();
Creates a new instance using the default time zone and the quarter symbols defined in REGULAR QUARTERS
(that is, “1”, “2”, “3” and “4”).
å public QuarterDateFormat(TimeZone zone);
Creates a new instance using the given time zone and the quarter symbols defined in REGULAR QUARTERS
(that is, “1”, “2”, “3” and “4”).
å public QuarterDateFormat(TimeZone zone, String[] quarterSymbols);
Creates a new instance using the given time zone and quarter symbols (the array should have
four entries).
24.32.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).
CHAPTER 24. PACKAGE: ORG.JFREE.CHART.AXIS
205
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.32.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.33
SegmentedTimeline
24.33.1
Overview
A segmented timeline for use with a DateAxis.
24.33.2
Usage
Please refer to the Javadocs.
24.34
StandardTickUnitSource
24.34.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.34.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.34.3
Constructor
This class has a single constructor:
å public StandardTickUnitSource();
Creates a new instance. There are no customisable attributes for this class.
24.34.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.
CHAPTER 24. PACKAGE: ORG.JFREE.CHART.AXIS
24.34.5
206
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.
24.35
SubCategoryAxis
24.35.1
Overview
An extension of the CategoryAxis class that allows subcategories to be displayed.
24.35.2
Notes
See the StackedBarChartDemo4.java file for an example.
24.36
SymbolAxis
24.36.1
Overview
A value axis that maps integer values 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 (y-axis).
24.36.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.36.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.
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.
å 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.
å 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.
CHAPTER 24. PACKAGE: ORG.JFREE.CHART.AXIS
24.36.4
207
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.36.5
Equals, Cloning and Serialization
To test this axis for equality with another axis:
å 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.
This class is Cloneable and Serializable.
24.36.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.37
Tick
24.37.1
Overview
208
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.38
TickUnit
24.38.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.38.2
Constructors
The standard constructor:
å public TickUnit(double size);
Creates a new tick unit with the specified size.
24.38.3
Notes
Implements the Comparable interface, so that a collection of tick units can be sorted easily using
standard Java methods.
See Also
TickUnits.
24.39
TickUnits
24.39.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.39.2
Constructors
The default constructor:
å public TickUnits();
Creates a new collection of tick units, initially empty.
CHAPTER 24. PACKAGE: ORG.JFREE.CHART.AXIS
24.39.3
209
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.39.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.
24.40
TickUnitSource
24.40.1
Overview
The interface through which a ValueAxis finds a suitable tick unit. Classes that implement this
interface include:
• TickUnits;
• StandardTickUnitSource;
24.40.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.41
Timeline
24.41.1
Overview
The interface that defines the methods for a timeline that can be used with a DateAxis.
24.41.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.
CHAPTER 24. PACKAGE: ORG.JFREE.CHART.AXIS
210
å 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.41.3
Notes
The SegmentedTimeline class implements this interface.
24.42
ValueAxis
24.42.1
Overview
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.42.2
Constructors
The constructors for this class are protected, you cannot create a ValueAxis directly—you must use
a subclass.
24.42.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.
24.42.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:
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...
CHAPTER 24. PACKAGE: ORG.JFREE.CHART.AXIS
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.
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 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.
fixedAutoRange
autoRangeMinimumSize
lowerMargin
upperMargin
autoTickUnitSelection
standardTickUnits
positiveArrowVisible
negativeArrowVisible
upArrow
downArrow
leftArrow
rightArrow
211
Table 24.6: Attributes for the ValueAxis class
Name:
DEFAULT
DEFAULT
DEFAULT
DEFAULT
DEFAULT
Value:
AUTO RANGE
MINIMUM AXIS VALUE
MAXIMUM AXISVALUE
UPPER MARGIN
LOWER MARGIN
true;
0.0;
1.0;
0.05 (5 percent)
0.05 (5 percent)
Table 24.7: ValueAxis class default attribute values
Having obtained an axis reference, you can:
• control the axis range, see section 24.42.5;
• invert the axis scale, see section 24.42.6;
24.42.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:
CHAPTER 24. PACKAGE: ORG.JFREE.CHART.AXIS
212
å 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.
å 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.
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.
CHAPTER 24. PACKAGE: ORG.JFREE.CHART.AXIS
24.42.6
213
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.
24.42.7
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.42.8
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.43
ValueTick
24.43.1
Overview
The base class for the NumberTick and DateTick classes.
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).
25.2.2
Constructor
To create a new block:
å protected AbstractBlock();
Creates a new block.
25.2.3
Methods
The following accessor methods are defined:
å public String getID();
Returns the block id.
å public void setID(String id);
Sets the block id.
å 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.
å public double getHeight();
Returns the block height.
å 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 RectangleInsets getMargin();
Returns the margin around the outside of the block’s border.
214
CHAPTER 25. PACKAGE: ORG.JFREE.CHART.BLOCK
å public void setMargin(RectangleInsets margin);
Sets the margin around the outside of the block’s border.
å public BlockBorder getBorder();
Returns the border that will be drawn around the block.
å public void setBorder(BlockBorder border);
Sets the border that will be drawn around the block.
å public RectangleInsets getPadding();
Returns the padding between the block’s content and its border.
å public void setPadding(RectangleInsets padding);
Sets the padding between the block’s content and its border.
å public Size2D arrange(Graphics2D g2);
Arranges the block 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 and returns its size. Keep in mind that the block may be a BlockContainer
that contains other blocks.
å 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.
å 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.
å 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.
å protected void drawBorder(Graphics2D g2, Rectangle2D area);
Draws the border for the block.
25.2.4
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.
25.3
Arrangement
25.3.1
Overview
A layout manager that can arrange blocks.
215
CHAPTER 25. PACKAGE: ORG.JFREE.CHART.BLOCK
25.3.2
216
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.
25.3.3
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.
CHAPTER 25. PACKAGE: ORG.JFREE.CHART.BLOCK
25.5
BlockBorder
25.5.1
Overview
217
A simple border that can be assigned to any subclass of AbstractBlock.
25.5.2
Constructors
There are two constructors:
å public BlockBorder();
Creates a new block border, using insets of 1.0 on all four sides of the border.
å public BlockBorder(RectangleInsets insets);
Creates a new block border using the specified insets.
25.5.3
Methods
å public RectangleInsets getInsets();
Returns the insets that define the available drawing space for the border.
å public void draw(Graphics2D g2, Rectangle2D area);
Draws the border around the edges of the specified area, always staying within the area.
å public boolean equals(Object obj);
Tests this border for equality with an arbitrary object.
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.
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.
CHAPTER 25. PACKAGE: ORG.JFREE.CHART.BLOCK
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.
25.7
BlockParams
25.7.1
Overview
A carrier for the (optional) parameters passed to a Block in its draw() method.
25.7.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.
218
CHAPTER 25. PACKAGE: ORG.JFREE.CHART.BLOCK
25.8
BlockResult
25.8.1
Overview
219
A carrier for the result from the draw() method in the BlockContainer class.
25.8.2
Methods
å public EntityCollection getEntityCollection();
Returns the entity collection from the block drawing.
å public void setEntityCollection(EntityCollection entities);
Sets the entity collection.
25.9
BorderArrangement
25.9.1
Overview
A layout manager (Arrangement) that is similar to the BorderLayout class in AWT.
25.9.2
Constructor
To create a new instance:
å public BorderArrangement();
Creates a new layout manager.
25.9.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.10
CenterArrangement
25.10.1
Overview
An Arrangement that places a single block at the center of its container.
25.11
ColorBlock
25.11.1
Overview
A simple block that is filled with a color. This is a useful class for visual testing of layout classes.
CHAPTER 25. PACKAGE: ORG.JFREE.CHART.BLOCK
25.11.2
220
Constructor
To create a new block:
å public ColorBlock(Paint paint, double width, double height);
Creates a new block with the specified “preferred” dimensions.
25.11.3
Methods
To draw the block:
å public void draw(Graphics2D g2, Rectangle2D area);
Draws the block inside the given area.
25.12
ColumnArrangement
25.12.1
Overview
An Arrangement that lays out the blocks in a container into columns. This is the “vertical” equivalent
of the FlowArrangement class.
25.12.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.12.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.12.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.
25.13
EmptyBlock
25.13.1
Overview
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.
CHAPTER 25. PACKAGE: ORG.JFREE.CHART.BLOCK
25.13.2
221
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.14
EntityBlockParams
25.14.1
Overview
To be documented.
25.15
EntityBlockResult
25.15.1
Overview
To be documented.
25.16
FlowArrangement
25.16.1
Overview
An Arrangement that lays out blocks horizontally from left to right (with wrapping if necessary).
25.16.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.16.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.
25.16.4
Equals, Cloning and Serialization
å public boolean equals(Object obj);
Tests this arrangement for equality with an arbitrary object.
CHAPTER 25. PACKAGE: ORG.JFREE.CHART.BLOCK
25.17
GridArrangement
25.17.1
Overview
222
A layout manager (Arrangement) that places blocks within a fixed size grid.
25.17.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.17.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.18
LabelBlock
25.18.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.18.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).
25.18.3
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:
CHAPTER 25. PACKAGE: ORG.JFREE.CHART.BLOCK
223
å 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.18.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.18.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.18.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.19
LengthConstraintType
25.19.1
Overview
224
This class defines three constraint types:
• LengthConstraintType.NONE;
• LengthConstraintType.FIXED;
• LengthConstraintType.RANGE;
These types are used when creating RectangleConstraint instances.
25.19.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.20
RectangleConstraint
25.20.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 (indicated by the LengthConstraintType
class). These constraints are used by the layout code implemented by JFreeChart.
25.20.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.20.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).
CHAPTER 25. PACKAGE: ORG.JFREE.CHART.BLOCK
å 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).
25.20.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.
225
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.
226
CHAPTER 26. PACKAGE: ORG.JFREE.CHART.EDITOR
26.3.3
227
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
228
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.
CHAPTER 26. PACKAGE: ORG.JFREE.CHART.EDITOR
26.9
DefaultNumberAxisEditor
26.9.1
Overview
229
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.
230
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).
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:
231
CHAPTER 27. PACKAGE: ORG.JFREE.CHART.ENCODERS
232
å 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.
27.3
ImageEncoderFactory
27.3.1
Overview
A factory class for image encoders.
27.3.2
Methods
å 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”).
å 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.
å 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.
27.4
ImageEncoder
27.4.1
Overview
An interface that provides an abstract view of the image encoders supported by this package.
27.4.2
Methods
å 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.
å public float getQuality();
Returns the image quality setting.
å public void setQuality(float quality);
Sets the quality.
CHAPTER 27. PACKAGE: ORG.JFREE.CHART.ENCODERS
233
å 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.
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).
27.6.2
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.
CHAPTER 27. PACKAGE: ORG.JFREE.CHART.ENCODERS
234
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.
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.
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.
CHAPTER 27. PACKAGE: ORG.JFREE.CHART.ENCODERS
235
å 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.
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, int series, Object category, int categoryIndex);
Creates a new entity instance.
236
CHAPTER 28. PACKAGE: ORG.JFREE.CHART.ENTITY
28.3.3
237
Methods
In addition to the methods inherited from the ChartEntity class:
å public CategoryDataset getDataset();
Returns a reference to the dataset. This may be null.
å public void setDataset(CategoryDataset dataset);
Sets the dataset reference for this entity (null is permitted).
å public int getSeries();
Returns the index of the series containing the item that this entity represents.
å public void setSeries(int series);
Sets the index of the series containing the item that this entity represents.
å public Object getCategory();
Returns the category containing the item that this entity represents. This may be null.
å public void setCategory(Object category);
Sets the category containing the item that this entity represents.
å public int getCategoryIndex();
Returns the index of the category containing the item that this entity represents.
å public void setCategoryIndex(int index);
Sets the index of the category containing the item that this entity represents.
å 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.
28.4
ChartEntity
28.4.1
Overview
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.
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.
CHAPTER 28. PACKAGE: ORG.JFREE.CHART.ENTITY
238
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.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.
28.6
EntityCollection
28.6.1
Overview
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:
CHAPTER 28. PACKAGE: ORG.JFREE.CHART.ENTITY
239
å 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
To access the index of the series that the legend item relates to:
å public int getSeriesIndex();
Returns the index of the series that the legend item entity relates to.
å public void setSeriesIndex(int index);
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.
CHAPTER 28. PACKAGE: ORG.JFREE.CHART.ENTITY
28.8.2
240
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.
28.9.2
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.
CHAPTER 28. PACKAGE: ORG.JFREE.CHART.ENTITY
28.9.4
241
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.
28.11
XYAnnotationEntity
28.11.1
Overview
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.
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.12
XYItemEntity
28.12.1
Overview
242
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.
243
CHAPTER 29. PACKAGE: ORG.JFREE.CHART.EVENT
29.3.3
244
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
245
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
246
å 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.
å 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
247
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
248
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
249
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.
250
CHAPTER 30. PACKAGE: ORG.JFREE.CHART.IMAGEMAP
251
å 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.
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.
30.6
StandardURLTagFragmentGenerator
30.6.1
Overview
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.
CHAPTER 30. PACKAGE: ORG.JFREE.CHART.IMAGEMAP
30.6.2
252
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.
30.8
URLTagFragmentGenerator
30.8.1
Overview
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:
<area shape="rect" coords="553,259,564,288" title="(Series 3, Type 8) = 12"
alt="" href="bar chart detail.jsp?series=Series+3&amp;category=Type+8"/>
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.
CHAPTER 30. PACKAGE: ORG.JFREE.CHART.IMAGEMAP
30.8.2
253
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
254
CHAPTER 31. PACKAGE: ORG.JFREE.CHART.LABELS
255
å 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.
256
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
257
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
258
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
259
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
260
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
261
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
262
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
263
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
264
å 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
To be documented.
31.18
PieSectionLabelGenerator
31.18.1
Overview
An interface that defines the methods used by a @link 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.
CHAPTER 31. PACKAGE: ORG.JFREE.CHART.LABELS
31.18.2
265
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.
31.18.4
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.
CHAPTER 31. PACKAGE: ORG.JFREE.CHART.LABELS
31.20
StandardCategoryItemLabelGenerator
31.20.1
Overview
266
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.
31.20.3
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.
CHAPTER 31. PACKAGE: ORG.JFREE.CHART.LABELS
31.21
StandardCategorySeriesLabelGenerator
31.21.1
Overview
267
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.
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.
CHAPTER 31. PACKAGE: ORG.JFREE.CHART.LABELS
Code:
Description:
{0}
{1}
{2}
The series key (or name).
The category.
The item value.
268
Table 31.3: MessageFormat substitutions for StandardCategoryToolTipGenerator
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.
31.22.3
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.
CHAPTER 31. PACKAGE: ORG.JFREE.CHART.LABELS
Code:
Description:
{0}
{1}
{2}
{3}
The
The
The
The
269
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.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.
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);
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 current locale. This
constructor throws an IllegalArgumentException if labelFormat is null.
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.
2 This
is defined in the DEFAULT SECTION LABEL FORMAT constant field.
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.
270
Table 31.5: MessageFormat substitutions
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.
31.24.5
Attributed Labels
An option is provided to use AttributedString instances as the section labels.
å 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 for the given section.
31.24.6
Equals, Cloning and Serialization
The equals() method is overridden:
å public boolean equals(Object obj);
Tests this label generator for equality with an arbitrary object.
This class is both Cloneable and Serializable.
31.25
StandardPieToolTipGenerator
31.25.1
Overview
A label generator that can be used to generate tool tips for a PiePlot (implements PieToolTipGenerator).
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);
CHAPTER 31. PACKAGE: ORG.JFREE.CHART.LABELS
31.25.3
271
Constructors
The default constructor uses number and percentage formatters appropriate for the default locale:
å public StandardPieToolTipGenerator();
Creates a default tool tip generator.
You can create a generator with a specific format string:
å public StandardPieToolTipGenerator(String labelFormat);
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 current 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
Notes
Some points to note:
• instances of this class are cloneable and serializable;
• section 11 contains information about using tool tips with JFreeChart.
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.
31.26.3
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:
CHAPTER 31. PACKAGE: ORG.JFREE.CHART.LABELS
272
å 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.
31.27.2
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.
CHAPTER 31. PACKAGE: ORG.JFREE.CHART.LABELS
31.27.3
273
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);
31.28.3
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.
CHAPTER 31. PACKAGE: ORG.JFREE.CHART.LABELS
274
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 XYZItemLabelGenerator interface. This generator is used with the
XYBubbleRenderer class.
31.30
SymbolicXYItemLabelGenerator
31.30.1
Overview
An item label generator for use with symbolic plots.
31.31
XYItemLabelGenerator
31.31.1
Overview
An xy item label generator is an object that assumes responsibility for generating the text strings
that will be used for the item labels in a chart. A generator is assigned to a renderer using the
setItemLabelGenerator() method in the XYItemRenderer interface.
31.31.2
Usage
Chapter 12 contains information about using item labels.
CHAPTER 31. PACKAGE: ORG.JFREE.CHART.LABELS
31.31.3
275
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 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.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.
31.32.2
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.
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.
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
276
• 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.
31.34.3
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
277
CHAPTER 32. PACKAGE: ORG.JFREE.CHART.NEEDLE
32.3
LineNeedle
32.3.1
Overview
278
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
279
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).
280
CHAPTER 32. PACKAGE: ORG.JFREE.CHART.NEEDLE
Figure 32.8: A wind needle
281
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
282
CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT
283
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
284
• 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
285
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);
The axis classes have many attributes that can be customised to control the appearance of your
charts.
The axes can be offset slightly from the edges of the plot area, if required. Use the following
methods:
å public RectangleInsets getAxisOffset();
Returns the object that controls the offset between the plot area and the axes.
å 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. A null value causes an exception.
CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT
33.3.5
286
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.6
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.7
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):
å 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.
CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT
287
å 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.8
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.9
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.10
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.
33.3.11
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).
CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT
288
å 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.12
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.13
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.14
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
33.5
CombinedDomainCategoryPlot
33.5.1
Overview
289
A category plot that allows multiple subplots to be displayed together using a shared domain axis—
see figure 33.3 for an example.
Figure 33.3: A CombinedDomainCategoryPlot
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
290
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
291
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
292
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
293
å 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
294
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 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).
295
CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT
33.9.5
296
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
297
å 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
298
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
299
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 colors, 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 outline paint sequence contains just one color (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
33.15.4
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 outline paint in the sequence:
1 This
is not currently enforced.
CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT
300
å 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.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.
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);
CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT
301
Figure 33.8: DialShape examples
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).
33.17.2
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 Stroke getNextStroke();
Returns the next Stroke object in the sequence (never null). These are usually used as the
default series line style in charts.
å 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.
CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT
33.18
FastScatterPlot
33.18.1
Overview
302
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.
33.18.4
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.
CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT
303
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.
å 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.
CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT
304
å 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.
33.18.8
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.
CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT
33.18.9
305
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.
33.20.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 (DifferenceChartDemo2.java) included in the JFreeChart demo collection that illustrates the use of this class.
33.20.3
Constructors
This class defines two 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, Stroke stroke, Paint outlinePaint,
Stroke outlineStroke, float alpha);
Creates a new instance for the specified range (in data space) and with the given attributes.
CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT
33.20.4
306
Methods
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.
The marker supports the use of GradientPaint via a transformer that can dynamically update the
coordinates of the gradient:
å public GradientPaintTransformer getGradientPaintTransformer();
Returns the transformer applied to any GradientPaint instances used by the marker. This
method never returns null.
å 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. This method throws an IllegalArgumentException
if transformer is null.
33.20.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 (which may be null.
Instances of this class are cloneable and serializable.
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
CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT
33.21.2
307
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:
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;
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.
CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT
308
å 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.
33.21.5
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.
CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT
309
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
å 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).
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.
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
310
Figure 33.10: Marker insets and the label anchor
å 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;
• 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”.
CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT
33.22.2
311
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.
33.22.4
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.
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.
CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT
312
Figure 33.11: A meter chart
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.
33.23.3
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:
CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT
313
å 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.
å 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).
CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT
314
å 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.
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”.
CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT
33.23.8
315
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.
å 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.
CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT
33.23.12
316
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.
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.
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:
CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT
317
å 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.
å 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.
CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT
33.24.4
318
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.
33.24.6
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.
CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT
33.27
PiePlot
33.27.1
Overview
319
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.
33.27.2
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.
The following default values are used where necessary:
Name:
DEFAULT
DEFAULT
DEFAULT
DEFAULT
DEFAULT
DEFAULT
Value:
INTERIOR GAP
START ANGLE
LABEL FONT
LABEL PAINT
LABEL BACKGROUND PAINT
LABEL GAP
0.25 (25 percent)
90.0
new Font("SansSerif", Font.PLAIN, 10);
Color.black;
new Color(255, 255, 192);
0.10 (10 percent)
CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT
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).
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).
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).
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 color for the section labels.
The background color 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
320
CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT
33.27.4
321
Methods
To replace the dataset being used by the plot:
å public void setDataset(PieDataset dataset);
Replaces the dataset being used by the plot (this triggers a DatasetChangeEvent).
To control whether the pie chart is circular or elliptical:
å public void setCircular(boolean flag);
Sets a flag that controls whether the pie chart is circular or elliptical in shape.
To control the position of the first section in the chart:
å public void setStartAngle(double angle);
Defines the angle (in degrees) at which the first 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.
To control the direction (clockwise or anticlockwise) of the sections in the pie chart:
å 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.25.
å public void setInteriorGapPercent(double percent);
Sets the amount of space inside the plot area and sends a PlotChangeEvent to all registered
listeners.
If you are displaying your pie chart in a ChartPanel and you want to customise the tooltip text, you
can register your own tool tip generator with the plot:
å public void setToolTipGenerator(PieToolTipGenerator generator);
Registers a tool tip generator with the pie plot. You can set this to null if you do not require
tooltips.
33.27.5
Utility Methods
å protected Comparable getSectionKey(int section); [1.0.3]
Returns the key for the specified section.
33.27.6
Section Paint
The paint associated with each section in a pie chart is completely configurable 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.
CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT
322
å public void setBaseSectionPaint(Paint paint);
Sets the base section paint (null is not permitted) and sends a PlotChangeEvent to all registered
listeners.
Similarly, you can specify an override section paint that takes precedence over the other settings
(this defaults to null and is rarely used):
å public Paint getSectionPaint();
Returns the paint that should be used for ALL sections in the PiePlot. The default value is
null.
å public void setSectionPaint(Paint paint);
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.7
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();
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);
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.
å 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:
CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT
å public Stroke getSectionOutlineStroke();
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);
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.8
Shadow Effect
The pie plot will draw a “shadow” effect. To set the paint used to draw the shadow:
å 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.
33.27.9
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.
323
CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT
33.27.10
324
Section Labels
Section labels are now generated by a plugin object that is an instance of any class that implements
the PieSectionLabelGenerator interface:
å public PieSectionLabelGenerator getLabelGenerator();
Returns the section label generator for the plot (possibly null).
å 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 color of the section labels:
å public Paint getLabelPaint();
Returns the color used to display the section labels (never null).
å public void setLabelPaint(Paint paint);
Sets the color used to display the section labels and sends a PlotChangeEvent to all registered
listeners. This method throws an IllegalArgumentException if paint is null.
To control the background color of the section labels:
å public Paint getLabelBackgroundPaint();
Returns the color used to fill the section label boxes—if this is null, the boxes are transparent
(the plot background color will show through).
å public void setLabelBackgroundPaint(Paint paint);
Sets the color 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 color
will show through).
To control the outline color of the section label boxes:
å public Paint getLabelOutlinePaint();
Returns the color used to draw the outline around the section labels. If this is null, no outline
is drawn.
å public void setLabelOutlinePaint(Paint paint);
Sets the color 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 set the color of the lines connecting the pie sections to their corresponding labels:
å 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.
To set the line style for the linking lines:
å 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.
At the current time, there is no facility to hide the linking lines.
CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT
33.27.11
325
Legend Items
The following methods allow for customisation of the legend items generated by the plot:
å public Shape getLegendItemShape();
Returns the shape displayed with each legend item.
å public void setLegendItemShape(Shape shape);
Sets the shape to be displayed with each legend item and sends a PlotChangeEvent to all registered listeners.
å public PieSectionLabelGenerator getLegendLabelGenerator();
Returns the generator that derives the labels for the items in the legend.
å 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.
å public PieSectionLabelGenerator getLegendLabelToolTipGenerator();
Returns the generator that creates the tool tips for each item in the legend.
å 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.
å 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.
å 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.
33.27.12
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.13
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).
See Also
PieDataset, PieSectionLabelGenerator, PieToolTipGenerator, Plot.
CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT
326
Figure 33.14: A 3D pie chart
33.28
PiePlot3D
33.28.1
Overview
An extension of the PiePlot class that draws pie charts with a 3D effect—see figure 33.14 for an
example.
33.28.2
Notes
Some points to note:
• this class does not yet support the “exploded” sections that can be displayed by the regular
pie charts;
• additional information is provided in section 5.8;
• some demos (PieChart3DDemo1-3.java) are included in the JFreeChart demo collection.
33.29
PiePlotState
33.29.1
Overview
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;
CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT
327
• 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.15 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.15: 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.
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:
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
328
Table 33.7: Attributes for the Plot class
å 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 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.
CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT
329
å public void setBackgroundImage(Image image);
Sets the background image for the plot3 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).
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.7
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.8
The Plot Outline
An outline is drawn for most plot types, and can be controlled with the following methods:
å 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.
å public Paint getOutlinePaint();
Returns the paint used to draw the plot outline. The default value is Color.GRAY.
å 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.
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.
3 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
33.30.9
330
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.
33.30.11
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:
CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT
331
å 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.
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.
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.
CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT
Class:
Description:
PlotOrientation.HORIZONTAL
PlotOrientation.VERTICAL
A “horizontal” orientation.
A “vertical” orientation.
332
Table 33.8: Plot orientation values
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.
33.32.2
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).
CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT
33.32.4
333
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.
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.
33.33
PlotState
33.33.1
Overview
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
PolarPlot
33.34.1
Overview
A plot that is used to display data from an XYDataset using polar coordinates—see figure 33.16 for
an example.
The items in the plot are drawn by a PolarItemRenderer.
33.34.2
Usage
A demo application (PolarChartDemo1.java) is included in the JFreeChart demo collection.
33.34.3
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.
CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT
334
Figure 33.16: A polar chart
Note that a convenience method (createPolarChart()) for creating charts based on this plot is
provided in the ChartFactory class.
33.34.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.34.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.
CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT
335
å 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).
å 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.34.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.
CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT
336
å 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.
33.34.7
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.34.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.34.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.
CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT
337
å 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.
å 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.34.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.34.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.
CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT
33.34.12
338
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.
33.35
RainbowPalette
33.35.1
Overview
A rainbow palette (extends ColorPalette) used by the ContourPlot class. This class is deprecated
as of version 1.0.4.
33.36
RingPlot
33.36.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.17 for an example.
Figure 33.17: A ring chart
33.36.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.36.3
Separators
The plot can draw lines to highlight the separation between sections:
å public boolean getSeparatorsVisible();
Returns true if the separators between sections are visible, and false otherwise.
CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT
339
å public void setSeparatorsVisible(boolean visible);
Sets the flag that controls whether or not the separators between sections are visible.
å public Stroke getSeparatorStroke();
Returns the stroke used to draw the separator lines, if they are visible. This method never
returns null.
å public void setSeparatorStroke(Stroke stroke);
Sets the stroke used to draw the separator lines (null not permitted).
å public Paint getSeparatorPaint();
Returns the paint used to draw the separator lines, if they are visible. This method never
returns null.
å public void setSeparatorPaint(Paint paint);
Sets the paint used to draw the separator lines (null not permitted).
å 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.
å public void setInnerSeparatorExtension(double percent);
Sets the length of the inner separator line as a percentage of the ring depth.
å public double getOuterSeparatorExtension();
Returns the length of the outer separator line for each section, as a percentage of the ring
depth.
å public void setOuterSeparatorExtension(double percent);
Sets the length of the outer separator line as a percentage of the ring depth.
33.36.4
Equals, Cloning and Serialization
This class overrides the equals() method:
å public boolean equals(Object obj);
Tests this plot for equality with an arbitrary object.
This class is Cloneable and Serializable.
33.36.5
Notes
The section depth is fixed at 10 percent of the plot bounds, methods should be added to make this
user configurable.
33.37
SeriesRenderingOrder
33.37.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.37.2
Notes
See the setSeriesRenderingOrder() method in the XYPlot class.
CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT
33.38
SpiderWebPlot
33.38.1
Overview
340
A plot that displays data from a CategoryDataset in a format that resembles a spider web—see
figure 33.18 for an example.
Figure 33.18: A spider web chart (see SpiderWebChartDemo1.java)
33.38.2
Constructors
There are three constructors for this class:
å 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.38.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.
CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT
341
å 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.
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.
CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT
342
å 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.38.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).
å 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:4
å 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:
4 These
methods could be (much) better named.
CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT
343
å 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:5
å 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).
å 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:6
å 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.38.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.
5 These
6 These
methods could be (much) better named.
methods could be (much) better named.
CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT
344
å 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.38.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.38.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.
33.38.8
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.39
ThermometerPlot
33.39.1
Overview
A plot that displays a single value in a thermometer-style representation.
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 color 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.
CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT
345
Figure 33.19: A thermometer chart
33.39.2
Constructors
To create a new ThermometerPlot:
å public ThermometerPlot(ValueDataset dataset);
Creates a thermometer with default settings, using the supplied dataset.
33.39.3
Methods
The current value can be displayed as text in the thermometer bulb or to the right of the thermometer. To set the position:
å public void setValueLocation(int location);
Sets the position of the value label. Use one of the constants: NONE, RIGHT or BULB.
The font for the value label can be set as follows:
å public void setValueFont(Font font);
Sets the font used to display the current value.
Similarly, the paint for the value label can be set as follows:
å public void setValuePaint(Paint paint);
Sets the paint used to display the current value.
You can set a formatter for the value label:
å public void setValueFormatter(NumberFormat formatter);
Sets the formatter for the value label.
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”.
You can specify the bounds for any of the three sub-ranges:
å 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:
CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT
346
å 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. You can set a flag that controls whether or not this automatic adjustment
happens:
å 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.
To set the default color of the “mercury” in the thermometer:
å public void setMercuryPaint(Paint paint);
Sets the default color of the mercury in the thermometer.
To set the color of the mercury for each sub-range:
å public void setSubrangePaint(int range, Paint paint);
Sets the paint used for the mercury when the data value is within the specified sub-range. Use
one of the constants NORMAL, WARNING or CRITICAL to indicate the sub-range.
The sub-range mercury colors are only used if the useSubrangePaint flag is set to true (the default):
å public void setUseSubrangePaint(boolean flag);
Sets the flag that controls whether or not the sub-range colors are used for the mercury in the
thermometer.
To show grid lines within the thermometer stem:
å public void setShowValueLines(boolean flag);
Sets a flag that controls whether or not grid lines are displayed inside the thermometer stem.
To control the color of the thermometer outline:
å public void setThermometerPaint(Paint paint);
Sets the paint used to draw the outline of the thermometer.
To control the pen used to draw the thermometer outline:
å public void setThermometerStroke(Stroke stroke);
Sets the stroke used to draw the outline of the thermometer.
You can control the amount of white space at the top and bottom of the thermometer:
å public void setPadding(RectangleInsets padding);
Sets the padding around the thermometer.
33.39.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.
CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT
33.39.5
347
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.
• various dimensions for the thermometer (for example, the bulb radius) are hard-coded constants in the current implementation. A useful enhancement would be to replace these constants with attributes that could be modified via methods in the ThermometerPlot class.
• the ThermometerDemo class in the org.jfree.chart.demo package provides a working example
of this class.
33.40
ValueAxisPlot
33.40.1
Overview
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.40.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
ValueMarker
33.41.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.41.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.41.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.
CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT
33.41.4
348
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.
33.41.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 (which may be null.
Instances of this class are cloneable and serializable.
33.41.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.42
WaferMapPlot
33.42.1
Overview
A plot for generating wafer map charts.
33.42.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.
33.43
XYPlot
33.43.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.
CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT
349
Figure 33.20: The plot regions
33.43.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).
33.43.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.43.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.
CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT
350
å 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.
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.43.10.
33.43.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.43.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.
CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT
33.43.7
351
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.
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.43.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.
CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT
352
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.
33.43.9
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.43.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.43.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).7 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);
7 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
353
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.
å 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.43.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).
CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT
354
å 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.
33.43.13
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.43.14
Crosshairs
The XYPlot class supports the display of crosshairs for the primary domain and range axes.8 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.
8 Unfortunately,
it is not possible to display crosshairs for other axes at this time.
CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT
355
å 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).
å 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).
CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT
356
å 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.
33.43.15
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.43.16
Annotations
You can add annotations to a chart 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);
To clear all annotations:
plot.clearAnnotations();
33.43.17
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.
CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT
357
å 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.43.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.43.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.
33.43.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.
CHAPTER 33. PACKAGE: ORG.JFREE.CHART.PLOT
33.44
Zoomable
33.44.1
Overview
358
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.
33.44.2
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.
Chapter 34
Package: org.jfree.chart.renderer
34.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.
34.2
AbstractRenderer
34.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 34.2.3);
–
–
–
–
–
–
paint (section 34.2.5);
fill paint (section 34.2.6);
outline paint (section 34.2.7);
stroke (section 34.2.8);
outline stroke (section 34.2.9);
shape (section 34.2.11);
• series visibility (section 34.2.12);
• series in legend visibility (section 34.2.13);
• item labels (section 34.2.14);
–
–
–
–
–
item labels visible (section 34.2.15);
item label font (section 34.2.16);
item label paint (section 34.2.17);
positive item label positions (section 34.2.18);
negative item label positions (section 34.2.19);
• chart entity generation (section 34.2.21);
This base class is extended by:
• AbstractCategoryItemRenderer;
• AbstractXYItemRenderer.
359
CHAPTER 34. PACKAGE: ORG.JFREE.CHART.RENDERER
34.2.2
360
Three Level Attribute Mechanism
Many renderer attributes need to have a value defined for each series in the dataset that is assigned
to the renderer. JFreeChart uses a mechanism with three levels:
• the override level – provides a single override value that has priority over all other values. If
this is null (the default, usually), the series level value is used instead;
• the series level – provides a value for each series. If the value for a series is null, the base level
value is used instead;
• the base level – provides a single default value to be used when both the override value and
the series value are null.
34.2.3
Common Attributes
All renderers use a common set of attributes as listed in Table 34.1.
Attribute:
Description:
paint
paintList
The paint override (null permitted).
A list of paints that apply to individual series (only referenced if paint is
null).
The paint that is used if there is no other setting.
basePaint
fillPaint
fillPaintList
The fill paint override (null permitted).
A list of fill paints that apply to individual series (only referenced if paint is
null).
The fill paint that is used if there is no other setting.
baseFillPaint
outlinePaint
outlinePaintList
baseOutlinePaint
stroke
strokeList
The stroke override (null permitted).
A list of stroke objects that apply to individual series (only referenced if stroke
is null).
The stroke that is used if there is no other setting.
baseStroke
outlineStroke
outlineStrokeList
baseOutlineStroke
shape
shapeList
baseShape
The outline paint override (null permitted).
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.
The outline stroke override (null permitted).
A list of outline strokes that apply to individual series (only referenced if
outlineStroke is null).
The outline stroke override.
The shape override (null permitted).
A list of shapes that apply to individual series (only referenced if shape is
null).
The shape that is used if there is no other setting.
Table 34.1: Attributes for the AbstractRenderer class
34.2.4
Setting Series Colors
Renderers are responsible for drawing the data items within a plot, so this class provides attributes
for controlling the colors that will be used. Colors 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 colors (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:
CHAPTER 34. PACKAGE: ORG.JFREE.CHART.RENDERER
361
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);
34.2.5
Paint
The paint attribute defines the main color used to identify a series in a chart:
Attribute:
Description:
paint
paintList
The paint override (null permitted).
A list of paints that apply to individual series (only referenced if paint is
null).
The paint that is used if there is no other setting.
basePaint
Table 34.2: Paint attributes for the AbstractRenderer class
å public Paint getItemPaint(int row, int column);
This method is called to obtain the paint for each item that the renderer draws. By default,
it simply returns the series paint obtained by calling getSeriesPaint(row). However, you can
override this method to return an arbitrary color 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);
Equivalent to setPaint(paint, true), see the next method for details.
å public void setPaint(Paint paint, boolean notify);
Sets the override paint attribute and, if requested, sends a RendererChangeEvent to all registered
listeners.
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.
CHAPTER 34. PACKAGE: ORG.JFREE.CHART.RENDERER
362
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.
34.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).
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 34.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.
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);
Equivalent to setFillPaint(paint, true), see the next method for details.
å public void setFillPaint(Paint paint, boolean notify);
Sets the override fill paint attribute and, if requested, sends a RendererChangeEvent to all registered 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.
CHAPTER 34. PACKAGE: ORG.JFREE.CHART.RENDERER
363
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.
34.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).
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 34.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.
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);
Equivalent to setOutlinePaint(paint, true), see the next method for details.
å public void setOutlinePaint(Paint paint, boolean notify);
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.
CHAPTER 34. PACKAGE: ORG.JFREE.CHART.RENDERER
364
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.
34.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);
Equivalent to setStroke(stroke, true), see the next method for details.
å public void setStroke(Stroke stroke, boolean notify);
Sets the override stroke and, if requested, sends a RendererChangeEvent to all registered listeners.
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.
CHAPTER 34. PACKAGE: ORG.JFREE.CHART.RENDERER
34.2.9
365
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);
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);
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.
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.
34.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.
CHAPTER 34. PACKAGE: ORG.JFREE.CHART.RENDERER
366
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);
}
34.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):
å 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);
Equivalent to setShape(shape, true), see the next method for details.
å public void setShape(Shape shape, boolean notify);
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:
CHAPTER 34. PACKAGE: ORG.JFREE.CHART.RENDERER
367
å 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.
34.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 34.13.1
Attribute:
Description:
seriesVisible
seriesVisibleList
The override flag (null permitted).
A list of flags that apply to individual series (these are only referenced
if seriesVisible is null).
The default visibility for all series.
baseSeriesVisible
Table 34.5: Series visibility attributes for the AbstractRenderer class
To determine the current visibility of an item or series:
å 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).
å public Boolean getSeriesVisible();
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);
Equivalent to setSeriesVisible(visible, true), see the method below.
å public void setSeriesVisible(Boolean visible, boolean notify);
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.
1 Note
that not all renderers respect these flags yet, but eventually they all will.
CHAPTER 34. PACKAGE: ORG.JFREE.CHART.RENDERER
368
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.
34.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 34.6.
Attribute:
Description:
seriesVisibleInLegend
seriesVisibleInLegendList
The override flag (null permitted).
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
Table 34.6: Legend visibility attributes for the AbstractRenderer class
To determine the current visibility of a series in the legend:
å 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();
Returns the override flag for series visibility in the legend. This may be null.
å public void setSeriesVisibleInLegend(Boolean visible);
Equivalent to setSeriesVisibleInLegend(visible, true), see the next method for details.
CHAPTER 34. PACKAGE: ORG.JFREE.CHART.RENDERER
369
å public void setSeriesVisibleInLegend(Boolean visible, boolean notify);
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.
34.2.14
Item Label Attributes
All renderers use a common set of item label attributes (some renderers may ignore these settings):
34.2.15
Item Label Visibility
The item label visibility attributes control the visibility of individual item labels:
å public boolean isItemLabelVisible(int row, int column);
Returns true if the item label is visible for the specified item, and false otherwise. Note that
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.
CHAPTER 34. PACKAGE: ORG.JFREE.CHART.RENDERER
Attribute:
Description:
itemLabelsVisible
itemLabelsVisibleList
The itemLabelsVisible override flag (null permitted).
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.
baseItemLabelsVisible
itemLabelFont
itemLabelFontList
370
The itemLabelFont override (null permitted).
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.
baseItemLabelFont
itemLabelPaint
itemLabelPaintList
The itemLabelPaint override (null permitted).
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.
baseItemLabelPaint
itemLabelAnchor
itemLabelAnchorList
The itemLabelAnchor override (null permitted).
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.
baseItemLabelAnchor
itemLabelTextAnchor
itemLabelTextAnchorList
baseItemLabelTextAnchor
itemLabelRotationAnchor
itemLabelRotationAnchorList
baseItemLabelRotationAnchor
itemLabelAngle
itemLabelAngleList
The itemLabelTextAnchor override (null permitted).
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).
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).
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.
baseItemLabelAngle
Table 34.7: Attributes for the AbstractRenderer class
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);
Equivalent to setItemLabelsVisible(Boolean.valueOf(visible), see the next method for details.
å public void setItemLabelsVisible(Boolean visible);
Equivalent to setItemLabelsVisible(visible, true), see the next method for details.
å public void setItemLabelsVisible(Boolean visible, boolean notify);
Sets the override item labels visible flag and, if requested, sends a RendererChangeEvent to all
registered listeners.
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 34.8: Item label visibility attributes for the AbstractRenderer class
CHAPTER 34. PACKAGE: ORG.JFREE.CHART.RENDERER
371
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.2
å 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.
34.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.
Attribute:
Description:
itemLabelFont
itemLabelFontList
The override font (null permitted).
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
Table 34.9: Item label font attributes for the AbstractRenderer class
To determine the item label font:
å public Font getItemLabelFont(int row, int column);
Returns the item label font for the specified item.
2 This
field should have been defined as a boolean, but is now part of the published API so we have to support it.
CHAPTER 34. PACKAGE: ORG.JFREE.CHART.RENDERER
372
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();
Returns the override item label font. The default value is null.
å public void setItemLabelFont(Font font);
Equivalent to setItemLabelFont(font, true)—see the next method.
å public void setItemLabelFont(Font font, boolean notify);
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.
34.2.17
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).
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 34.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.
CHAPTER 34. PACKAGE: ORG.JFREE.CHART.RENDERER
373
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();
Returns the override item label font. The default value is null.
å public void setItemLabelPaint(Paint paint);
Equivalent to setItemLabelPaint(paint, true)—see the next method.
å public void setItemLabelPaint(Paint paint, boolean notify);
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
å public Paint getBaseItemLabelPaint();
å public void setBaseItemLabelPaint(Paint paint);
å public void setBaseItemLabelPaint(Paint paint, boolean notify);
34.2.18
Positive Item Label Position
The positive item label position attributes (see table 34.11) control the position of item labels for
those items that have a data value that is positive.
Attribute:
Description:
positiveItemLabelPosition
seriesPositiveItemLabelPositionList
The positiveItemLabelPosition override flag (null permitted).
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)
basePositiveItemLabelPosition
Table 34.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.
CHAPTER 34. PACKAGE: ORG.JFREE.CHART.RENDERER
374
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();
Returns the positive item label position override. The default value is null.
å public void setPositiveItemLabelPosition(ItemLabelPosition position);
Equivalent to setPositiveItemLabelPosition(position, true)—see the next method.
å public void setPositiveItemLabelPosition(ItemLabelPosition position, boolean notify);
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).
å 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.
34.2.19
Negative Item Label Position
The negative item label position attributes (see table 34.12) control the position of item labels for
those items that have a data value that is negative.
Attribute:
Description:
negativeItemLabelPosition
seriesNegativeItemLabelPositionList
The negativeItemLabelPosition override flag (null permitted).
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))
baseNegativeItemLabelPosition
Table 34.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.
CHAPTER 34. PACKAGE: ORG.JFREE.CHART.RENDERER
375
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();
Returns the negative item label position override. The default value is null.
å public void setNegativeItemLabelPosition(ItemLabelPosition position);
Equivalent to setNegativeItemLabelPosition(position, true)—see the next method.
å public void setNegativeItemLabelPosition(ItemLabelPosition position, boolean notify);
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.
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.
34.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).
CHAPTER 34. PACKAGE: ORG.JFREE.CHART.RENDERER
34.2.21
376
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
seriesCreateEntitiesList
The createEntities override flag (null permitted).
A list of flags that apply to individual series (only referenced
if createEntities is null).
The default flag for all series.
baseCreateEntities
Table 34.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.
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();
Returns the override flag. This is null by default.
å public void setCreateEntities(Boolean create);
Equivalent to setCreateEntities(create, true)—see the next method.
å public void setCreateEntities(Boolean create, boolean notify);
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.
CHAPTER 34. PACKAGE: ORG.JFREE.CHART.RENDERER
34.2.22
377
Equals, Cloning and Serialization
An equals() method is provided for use by subclasses:
å 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.
34.2.23
Notes
Some points to note:
• subclasses include AbstractCategoryItemRenderer and AbstractXYItemRenderer.
34.3
AreaRendererEndType
34.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 34.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 34.14: AreaRendererEndType tokens
34.3.2
Usage
The AreaRenderer class has a method named setEndType() that accepts the tokens defined by this
class.
34.4
DefaultPolarItemRenderer
34.4.1
Overview
A default renderer for use by the PolarPlot class (implements the PolarItemRenderer interface).
34.4.2
Constructor
To create a new renderer:
å public DefaultPolarItemRenderer();
Creates a new renderer instance.
CHAPTER 34. PACKAGE: ORG.JFREE.CHART.RENDERER
34.4.3
Methods
å public DrawingSupplier getDrawingSupplier();
A convenience method that returns the drawing supplier from 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 void drawSeries(Graphics2D g2, Rectangle2D dataArea, PlotRenderingInfo info,
PolarPlot plot, XYDataset dataset, int seriesIndex);
Draws a series within the specified dataArea.
å 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.
å 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 LegendItem getLegendItem(int series);
Returns a legend item for the specified series.
34.5
GrayPaintScale
34.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.
34.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.
34.5.3
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.
378
CHAPTER 34. PACKAGE: ORG.JFREE.CHART.RENDERER
34.5.4
379
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.
34.5.5
Notes
This class can be used with the XYBlockRenderer class.
See Also
PaintScale, PaintScaleLegend.
34.6
LookupPaintScale
34.6.1
Overview
A PaintScale implementation that uses a lookup table to convert values to corresponding Paint
instances.
This class was first introduced in JFreeChart version 1.0.4.
34.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.
34.6.3
Methods
The following methods are defined:
å public Paint getDefaultPaint(); [1.0.4]
Returns the default paint, as specified in the constructor.
å 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 void add(Number n, Paint p); [1.0.4]
Adds a new entry to the lookup table.
å public Paint getPaint(double value); [1.0.4]
Returns the color for the specified value.
34.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.
34.6.5
Notes
This class can be used with the XYBlockRenderer class.
CHAPTER 34. PACKAGE: ORG.JFREE.CHART.RENDERER
380
See Also
PaintScale, PaintScaleLegend.
34.7
NotOutlierException
34.7.1
Overview
An exception that is, in fact, never used in JFreeChart.
34.8
Outlier
34.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.
34.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).
34.8.3
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.
34.9
OutlierList
34.9.1
Overview
Represents a collection of outliers for a single item in a box-and-whisker plot.
CHAPTER 34. PACKAGE: ORG.JFREE.CHART.RENDERER
381
See Also
Outlier, OutlierListCollection.
34.10
OutlierListCollection
34.10.1
Overview
Represents a collection of outlier lists for a box-and-whisker plot.
See Also
OutlierList.
34.11
PaintScale
34.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.
34.11.2
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.
See Also
PaintScaleLegend.
34.12
PolarItemRenderer
34.12.1
Overview
A renderer that is used by the PolarPlot class. The DefaultPolarItemRenderer class provides an
implementation of this interface.
34.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).
CHAPTER 34. PACKAGE: ORG.JFREE.CHART.RENDERER
34.12.3
382
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).
å 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.
34.13
RendererState
34.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.
34.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).
34.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.
CHAPTER 34. PACKAGE: ORG.JFREE.CHART.RENDERER
34.13.4
383
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.
34.14
WaferMapRenderer
34.14.1
Overview
A renderer used by the WaferMapPlot class.
Chapter 35
Package:
org.jfree.chart.renderer.category
35.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.
35.2
AbstractCategoryItemRenderer
35.2.1
Overview
A base class (extending AbstractRenderer) that can be used to implement a new CategoryItemRenderer.
35.2.2
Constructors
The default constructor creates a renderer with no tooltip generator and no URL generator. The
constructor is protected.
35.2.3
Attributes
The attributes maintained by this class are listed in Table 35.1.
35.2.4
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 get the renderer type:
å public RangeType getRangeType();
Returns the range type for the renderer (STANDARD or STACKED).
To draw the plot background:
384
CHAPTER 35. 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
Table 35.1: Attributes for the AbstractCategoryItemRenderer class
å 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.
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.
385
CHAPTER 35. PACKAGE: ORG.JFREE.CHART.RENDERER.CATEGORY
386
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.
35.2.5
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.
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.
CHAPTER 35. PACKAGE: ORG.JFREE.CHART.RENDERER.CATEGORY
35.2.6
387
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.
35.2.7
Notes
If you are implementing your own renderer, you do not have to use this base class, but it does save
you some work.
35.3
AreaRenderer
35.3.1
Overview
A category item renderer that represents each item in a CategoryDataset using a polygon that fills
the area between the x-axis and the data point—an example is shown in figure 35.1.
Figure 35.1: A chart that uses AreaRenderer
This renderer is designed for use with the CategoryPlot class.
35.3.2
Methods
To control how the end points of the area chart are represented:
å public void setEndType(AreaRendererEndType type);
Sets the attribute that controls how the end points are drawn on the area chart.
35.3.3
Notes
Some notes:
• the createAreaChart() method in the ChartFactory class will create a default chart that uses
this renderer.
• this class extends AbstractCategoryItemRenderer.
See Also
XYAreaRenderer.
CHAPTER 35. PACKAGE: ORG.JFREE.CHART.RENDERER.CATEGORY
35.4
BarRenderer
35.4.1
Overview
388
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 35.2) or a
horizontal orientation (see figure 35.3).
Figure 35.2: A vertical bar chart
Figure 35.3: A horizontal bar chart
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 implements the CategoryItemRenderer interface, and is an extension of the AbstractCategoryItemRenderer
base class.
35.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 35. PACKAGE: ORG.JFREE.CHART.RENDERER.CATEGORY
35.4.3
389
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:
å 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.
35.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.
35.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 true.
CHAPTER 35. PACKAGE: ORG.JFREE.CHART.RENDERER.CATEGORY
390
å 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.
35.4.6
Gradient Paint Support
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.
35.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 35.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 35.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
CHAPTER 35. PACKAGE: ORG.JFREE.CHART.RENDERER.CATEGORY
391
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.
å 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.
35.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.
35.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.
35.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:
CHAPTER 35. PACKAGE: ORG.JFREE.CHART.RENDERER.CATEGORY
392
• 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.
35.4.11
Notes
Some points to note:
• 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.
35.5
BarRenderer3D
35.5.1
Overview
A renderer that draws items from a CategoryDataset using bars with a 3D effect—see figure 35.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 35.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.
35.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 35. PACKAGE: ORG.JFREE.CHART.RENDERER.CATEGORY
35.5.3
393
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.
35.5.4
Other Methods
Several methods are overridden to add support for the 3D effect:
å 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.
35.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 and Serializable.
CHAPTER 35. PACKAGE: ORG.JFREE.CHART.RENDERER.CATEGORY
35.5.6
394
Notes
Some points to note:
• this class is a subclass of BarRenderer and implements the CategoryItemRenderer interface.
• demos (BarChart3DDemo1 and BarChart3DDemo2) are included in the JFreeChart demo collection.
See Also
StackedBarRenderer3D, CategoryAxis3D.
35.6
BoxAndWhiskerRenderer
35.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 35.6.
Figure 35.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.
35.6.2
Constructors
To create a new renderer:
å public BoxAndWhiskerRenderer();
Creates a new renderer.
CHAPTER 35. PACKAGE: ORG.JFREE.CHART.RENDERER.CATEGORY
35.6.3
395
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:1
å 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.
35.6.4
Notes
Some points to note:
• a demo application (BoxAndWhiskerDemo1.java) is included in the JFreeChart demo collection.
See Also
XYBoxAndWhiskerRenderer.
35.7
CategoryItemRenderer
35.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:
1 The
spacing between categories is controlled by the CategoryAxis.
CHAPTER 35. PACKAGE: ORG.JFREE.CHART.RENDERER.CATEGORY
AbstractCategoryItemRenderer
396
CategoryItemRenderer
AreaRenderer
LineAndShapeRenderer
StackedAreaRenderer
DefaultCategoryItemRenderer
MinMaxCategoryRenderer
BarRenderer
BarRenderer3D
StackedBarRenderer
IntervalBarRenderer
StackedBarRenderer3D
Figure 35.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.
35.7.2
Methods
The interface defines an initialisation method:
å 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 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.
35.7.3
Item Labels
An item label is a short text string that can be displayed near each data item in a chart. Whenever
the renderer requires an item label, it obtains a label generator via the following method:
CHAPTER 35. PACKAGE: ORG.JFREE.CHART.RENDERER.CATEGORY
397
å public CategoryItemLabelGenerator getLabelGenerator(int series, int item);
Returns the label generator for the specified data item. In theory, this method could return
a different generator for each item but, in practice, it will often return the same generator for
every item (or one generator per series). The method can return null if no generator has been
set for the renderer—in this case, no item labels will be displayed.
To set a generator that will be used for all data items in the chart:
å public void setItemLabelGenerator(CategoryItemLabelGenerator generator);
Sets the item label generator that will be used for ALL data items in the chart, and sends a
RendererChangeEvent to all registered listeners. Set this to null if you prefer to set the generator
on a “per series” basis.
To set a generator for a particular series:
å public void setSeriesItemLabelGenerator(int series, CategoryItemLabelGenerator generator);
Sets the item label generator for the specified series. If null, the baseItemLabelGenerator will
be used.
To make item labels visible for ALL series:
å public void setItemLabelsVisible(boolean visible);
Sets the flag that controls whether or not item labels are visible for all series drawn by this
renderer. If you prefer to set the visibility on a per series basis, you need to set this flag to
null (see the next method).
å public void setItemLabelsVisible(Boolean visible);
Sets the flag that controls whether or not item labels are visible for all series drawn by this
renderer. Set this to null if you prefer to set the visibility on a per series basis.
To control the visibility of item labels for a particular series:
å public void setSeriesItemLabelsVisible(int series, boolean visible);
Sets a flag that controls whether or not item labels are visible for the specified series.
å public void setSeriesItemLabelsVisible(int series, Boolean visible);
Sets a flag that controls whether or not item labels are visible for the specified series. If this is
set to null, the baseItemLabelsVisible flag determines the visibility.
The position of the item labels is set using the following methods (one applies to positive data items
and the other applies to negative data items):
å public void setPositiveItemLabelPosition(ItemLabelPosition position);
Sets the position for labels for data items where the y-value is positive.
å public void setNegativeItemLabelPosition(ItemLabelPosition position);
Sets the position for labels for data items where the y-value is negative.
35.7.4
Tooltips
A tool tip is a short text string that is displayed temporarily in a GUI while the mouse pointer
hovers over a particular item in a chart. Whenever the renderer requires a text string for a tool tip,
it calls the following method:
å public CategoryToolTipGenerator getToolTipGenerator(int series, int item);
Returns the tool tip generator for the specified data item (possibly null).
You can register a generator with the renderer using:
å public void setToolTipGenerator(CategoryToolTipGenerator generator);
Sets the tool tip generator that will be used for ALL data items in the chart, and sends a
RendererChangeEvent to all registered listeners.
CHAPTER 35. PACKAGE: ORG.JFREE.CHART.RENDERER.CATEGORY
35.7.5
398
URL Generation
The ChartEntity objects created by the renderer for each data item can have a URL associated
with them. To provide flexibility, URLs are generated using a mechanism that is very similar to
the tooltips mechanism.
URLs are only used in HTML image maps at present. If you are not generating HTML
image maps, then you should leave the URL generators set to null.
You can associate a CategoryURLGenerator with the renderer using this method:
å public void setItemURLGenerator(CategoryURLGenerator generator);
Sets the generator that will be used to generate URLs for items in ALL series.
It is possible to specify a different URL generator for each series by first setting the generator in
the previous method to null then using the following method to assign a generator to each series
independently:
å public void setSeriesItemURLGenerator(int series, CategoryURLGenerator generator);
Sets the generator for the items in a particular series.
In most cases, a single generator for all series will suffice.
35.7.6
Notes
Some points to note:
• classes that implement the CategoryItemRenderer interface are used by the CategoryPlot class.
They cannot be used by the XYPlot class (which uses implementations of the XYItemRenderer
interface).
See Also
CategoryPlot, AbstractCategoryItemRenderer.
35.8
CategoryItemRendererState
35.8.1
Overview
This class records state information for a CategoryItemRenderer during the process of drawing a
chart. Recall that the plot uses a renderer to draw the individual data items in a chart. In the
plot’s render() method, a call is made to the renderer’s initialise() method, which returns a state
object. Subsequently, for every call the plot makes to the renderer’s drawItem() method, it passes
in the same state object (which can be updated with new state information during the rendering).
This scheme is designed to allow two or more different threads to use a single renderer to draw a
chart to different output targets simultaneously.
35.8.2
Constructors
To create a new state instance:
å public CategoryItemRendererState(PlotRenderingInfo info);
Creates a new state object with a reference to the specified info for plot rendering (which may
be null.
In general, this class is instantiated in the renderer’s initialize() method.
CHAPTER 35. PACKAGE: ORG.JFREE.CHART.RENDERER.CATEGORY
35.8.3
399
Methods
To access the bar width (only used by some renderers):
å public double getBarWidth();
Returns the bar width, in Java2D units.
å public void setBarWidth(double width);
Sets the bar width. This method is intended for internal use (by the renderer), you shouldn’t
call this method directly.
To access the running total for the current series:
å public double getSeriesRunningTotal();
Returns the running total for the current series.
å void setSeriesRunningTotal(double total);
Sets the running total for teh current series. This method is intended for internal use (by the
renderer), you shouldn’t call this method directly (actually, it is package private so you can’t
in any case).
35.8.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
RendererState.
35.9
CategoryStepRenderer
35.9.1
Overview
A renderer that draws “steps” between each data value in a CategoryPlot—see figure 35.8 for an
example.
Figure 35.8: A chart using CategoryStepRenderer
35.9.2
Constructor
To create a new renderer:
å public CategoryStepRenderer();
Creates a new renderer with stagger set to false.
å public CategoryStepRenderer(boolean stagger);
Creates a new renderer. If stagger is true, the vertical steps for each series are offset slightly
from one another.
CHAPTER 35. PACKAGE: ORG.JFREE.CHART.RENDERER.CATEGORY
35.9.3
400
Methods
To get/set the “stagger” flag:
å public boolean getStagger();
Returns the flag that controls whether or not the “step” for each series is offset from the other
series (to avoid the vertical lines overlapping). In the sample chart (see figure 35.8) this flag is
set to true.
å public void setStagger(boolean shouldStagger);
Sets the flag that controls whether or not the series are “staggered” and sends a RendererChangeEvent
to all registered listeners.
35.9.4
Notes
Some points to notes:
• a demo application (CategoryStepChartDemo1.java) is included in the JFreeChart demo collection.
35.10
DefaultCategoryItemRenderer
35.10.1
Overview
This class is an alias for the LineAndShapeRenderer class.
35.11
GanttRenderer
35.11.1
Overview
A renderer that is used to draw simple Gantt charts—an example is shown in figure 35.9.
Figure 35.9: A Gantt chart
The renderer is used with the CategoryPlot class and accesses data via the GanttCategoryDataset
interface. The createGanttChart() method in the ChartFactory class will create a JFreeChart instance
that uses this rendeerer.
35.11.2
Methods
The renderer can highlight the “percentage complete” for a task, provided that this information is
specified in the dataset. The colors used for this indicator are set with the following methods:
CHAPTER 35. PACKAGE: ORG.JFREE.CHART.RENDERER.CATEGORY
401
å public void setCompletePaint(Paint paint);
Sets the Paint used to draw the portion of the task that is completed and sends a RendererChangeEvent
to all registered listeners.
å public void setIncompletePaint(Paint paint);
Sets the Paint used to draw the portion of the task that is not yet completed and sends a
RendererChangeEvent to all registered listeners.
The width of the “percentage complete” indicator can be controlled by specifying the start and end
percentage values relative to the width (not length!) of the task bars:
å public void setStartPercent(double percent);
Sets the start position for the indicator as a percentage of the width of the task bar (for example,
0.30 is thirty percent)
å public void setEndPercent(double percent);
Sets the end position for the indicator as a percentage of the width of the task bar (for example,
0.70 is seventy percent)
As an example, by setting the start and end percentages in the above methods to 0.30 and 0.70
(say), the middle forty percent of the task bar is occupied by the “percentage complete” indicator.
35.11.3
Notes
Some points to note:
• this class extends IntervalBarRenderer;
• you can enable or disable bar outlines using the setDrawBarOutline() method inherited from
the BarRenderer class;
• two demo applications (GanttDemo1.java and GanttDemo2.java) are included in the JFreeChart
demo distribution.
35.12
GroupedStackedBarRenderer
35.12.1
Overview
This renderer is used to draw grouped and stacked bar charts using data from a CategoryDataset
(see figure 35.10).
Figure 35.10: A grouped and stacked bar chart
This class extends the StackedBarRenderer class.
CHAPTER 35. PACKAGE: ORG.JFREE.CHART.RENDERER.CATEGORY
35.12.2
402
Constructor
To create a new renderer:
å public GroupedStackedBarRenderer();
Creates a new renderer with default settings. By default, all series are mapped to a single
group—you can change this using the setSeriesToGroupMap() method.
35.12.3
Mapping Series To Groups
This renderer requires you to specify the mapping between series and groups using the following
method:
å public void setSeriesToGroupMap(KeyToGroupMap map);
Sets the map that controls which series are grouped together.
Refer to the source code for StackedBarChartDemo4 for an example of this.
35.12.4
Other Methods
The following method is called by JFreeChart when determining the axis range that will display
ALL the data in the dataset. Due to the stacking performed by this renderer, the range will depend
on the way that the series are grouped together:
å public Range getRangeExtent(CategoryDataset dataset);
Returns the range of data values in the dataset, after taking into account the stacking that is
performed by this renderer.
35.12.5
Notes
Some points to note:
• there is a demo (StackedBarChartDemo4.java) included in the JFreeChart demo collection.
35.13
IntervalBarRenderer
35.13.1
Overview
A renderer that draws bars to represent items from an IntervalCategoryDataset—see figure 35.11.
Figure 35.11: A chart that uses an IntervalBarRenderer
This renderer is used with the CategoryPlot class, and is an extension of BarRenderer.
CHAPTER 35. PACKAGE: ORG.JFREE.CHART.RENDERER.CATEGORY
35.13.2
403
Constructors
This class has a single constructor:
å public IntervalBarRenderer();
Creates a new renderer instance. After the renderer is created, you can customise it using the
methods inherited from its ancestor classes.
35.13.3
Methods
The following methods are called by the CategoryPlot class during chart rendering, you won’t
normally call them directly:
å public void drawItem(Graphics2D g2, CategoryItemRendererState state,
Rectangle2D dataArea, CategoryPlot plot, CategoryAxis domainAxis, ValueAxis rangeAxis,
CategoryDataset dataset, int row, int column, int pass);
Handles the drawing of a single item. If dataset is an instanceof
IntervalCategoryDataset, the bars are rendered for the interval defined by the dataset. Other-
wise, the method passes control back to the super class to draw a regular bar.
å protected void drawInterval(Graphics2D g2, CategoryItemRendererState state,
Rectangle2D dataArea, CategoryPlot plot, CategoryAxis domainAxis,
ValueAxis rangeAxis, IntervalCategoryDataset dataset, int row, int column);
Handles the drawing of a single interval (called from the drawItem() method).
Many other methods are inherited from BarRenderer.
35.13.4
Notes
Some points to note:
• the IntervalCategoryToolTipGenerator interface can be used to generate tooltips with this
renderer;
• a demo (IntervalBarChartDemo1) is included in the JFreeChart demo collection.
See Also
DefaultIntervalCategoryDataset, GanttRenderer.
35.14
LayeredBarRenderer
35.14.1
Overview
A renderer that draws layered bars to represent items from an CategoryDataset—see figure 35.12
for an example.
35.14.2
Constructors
To create a new renderer:
å public LayeredBarRenderer();
Creates a new renderer with default settings.
CHAPTER 35. PACKAGE: ORG.JFREE.CHART.RENDERER.CATEGORY
404
Figure 35.12: A chart that uses a LayeredBarRenderer
35.14.3
Methods
With this renderer, the bar width varies by series. Most of the time, the default widths are
acceptable, but you can specify a custom width if necessary:
å public double getSeriesBarWidth(int series);
Returns the bar width as a percentage of the default bar width.
å public void setSeriesBarWidth(int series, double width);
Sets the bar width as a percentage of the default bar width. Bear in mind that the default bar
width decreases as the series index increases.
å protected void calculateBarWidth(CategoryPlot plot, Rectangle2D dataArea, int rendererIndex,
CategoryItemRendererState state);
Updates the state with the bar width calculated for the current series/renderer.
å public void drawItem(Graphics2D g2, CategoryItemRendererState state, Rectangle2D dataArea,
CategoryPlot plot, CategoryAxis domainAxis, ValueAxis rangeAxis, CategoryDataset data, int
row, int column, int pass);
Draws a bar to represent one data item.
å protected void drawHorizontalItem(Graphics2D g2, CategoryItemRendererState state, Rectangle2D
dataArea, CategoryPlot plot, CategoryAxis domainAxis, ValueAxis rangeAxis, CategoryDataset
data, int row, int column);
Draws a horizontal bar to represent a data item.
å protected void drawVerticalItem(Graphics2D g2, CategoryItemRendererState state, Rectangle2D
dataArea, CategoryPlot plot, CategoryAxis domainAxis, ValueAxis rangeAxis, CategoryDataset
data, int row, int column);
Draws a vertical bar to represent a data item.
35.14.4
Notes
Some points to note:
• a demo (LayeredBarChartDemo1.java) is included in the JFreeChart demo distribution.
35.15
LevelRenderer
35.15.1
Overview
A renderer that draws horizontal lines to represent items from an CategoryDataset. The lines
occupy the same width along the axis that a bar drawn by the BarRenderer class would occupy—for
example, see figure 35.13.
CHAPTER 35. PACKAGE: ORG.JFREE.CHART.RENDERER.CATEGORY
405
Figure 35.13: A chart that uses a LevelRenderer
35.15.2
Methods
To control the gap between items:
å 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 percent);
Sets the item margin and sends a RendererChangeEvent to all registered listeners.
To set a cap for the maximum width of each item:
å public double getMaximumItemWidth();
Returns the maximum item width allowed, as a percentage of the length of the category axis.
The default is 1.00 (100 percent) which means that the item widths are never capped.
å public void setMaximumItemWidth(double percent);
Sets the maximum item 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 items 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 items will be displayed.
35.15.3
Equals, Cloning and Serialization
This class overrides the equals() method:
å public boolean equals(Object obj);
Tests this renderer for equality with an arbitrary object. Returns true if and only if:
• obj is not null;
• obj is an instanceof LevelRenderer;
• both renderers have equal field values.
This renderer is Cloneable and Serializable.
35.15.4
Notes
Some points to note:
• the item widths for this renderer are intended to match those calculated by the BarRenderer
class;
• a demo for this renderer (OverlaidBarChartDemo2.java) is included in the JFreeChart demo
collection.
CHAPTER 35. PACKAGE: ORG.JFREE.CHART.RENDERER.CATEGORY
35.16
LineAndShapeRenderer
35.16.1
Overview
406
A renderer that displays data items by drawing a shape at each data point and/or connecting data
points with straight lines—see figure 35.14 for an example. The renderer works with a CategoryPlot
and obtains data from a CategoryDataset.
Figure 35.14: A chart that uses a LineAndShapeRenderer
35.16.2
Constructors
The default constructor creates a renderer that draws both shapes and lines:
å public LineAndShapeRenderer();
Creates a new renderer that draws both shapes and lines.
A second constructor allows you to select shapes and/or lines:
å public LineAndShapeRenderer(boolean lines, boolean shapes);
Creates a new renderer that draws shapes and/or lines.
35.16.3
Line Visibility
To determine if a line should be drawn between the current item and the previous item, the following
method is called by the renderer’s drawing code:
å public boolean getItemLineVisible(int series, int item);
Returns true if a line should be drawn between the current item and the previous item, and
false otherwise.
This method is called for every data item, even though the default implementation can access only
the “per series” settings provided by the renderer. You can override this method if you need to
vary the line visibility on a “per item” basis.
The line visibility settings are arranged into the standard three-layer mechanism for renderer attributes (see 34.2.2). To get the top level (override) setting for the visibility of lines:
å public Boolean getLinesVisible();
Returns Boolean.TRUE if lines are visible for all series, Boolean.FALSE if lines are invisible for all
series, and null (the default) if the lower level settings should be referenced instead.
å public void setLinesVisible(Boolean visible);
Sets the override flag for the visibility of lines for all series and sends a RendererChangeEvent to
all registered listeners. You should set this value to null (the default) if you don’t require an
override setting.
CHAPTER 35. PACKAGE: ORG.JFREE.CHART.RENDERER.CATEGORY
407
å public void setLinesVisible(boolean visible);
As above.
If the override setting is null, the “per series” settings apply:
å public Boolean getSeriesLinesVisible(int series);
Returns Boolean.TRUE if lines are visible for the specified series, Boolean.FALSE if lines are invisible
for the specified series, and null (the default) if the lower level settings should be referenced
instead.
å public void setSeriesLinesVisible(int series, Boolean flag);
Sets the line visibility flag for the specified series and sends a RendererChangeEvent to all registered listeners. If you set the value for a series to null, the base value will be used instead.
å public void setSeriesLinesVisible(int series, boolean visible);
As above.
If neither the override nor the per series settings are set, the base level flag is used:
å public boolean getBaseLinesVisible();
Returns true if lines are visible, by default, for all series, and false otherwise.
å public void setBaseLinesVisible(boolean flag);
Sets the default value for line visibility and sends a RendererChangeEvent to all registered listeners.
The line color (Paint) and style (Stroke) settings are inherited from the AbstractRenderer class.
35.16.4
Shape Visibility
Methods that set the shapes displayed by the renderer are inherited from the AbstractRenderer
class.
35.16.5
Controlling Shape Outlines
If the renderer is configured to draw shapes, then the shapes can be drawn with or without outlines,
according to the setting of the drawOutlines flag:
å public boolean getDrawOutlines();
Returns true if the renderer draws outlines around each shape, and false otherwise.
å public void setDrawOutlines(boolean flag);
Sets the flag that controls whether or not outlines are drawn around shapes, and sends a
RendererChangeEvent to all registered listeners.
The renderer uses one of two possible colors (inherited from AbstractRenderer) for the shape outlines:
(a) the outline paint for the current series, or (b) the (regular) paint for the current series. The
selection is determined by the useOutlinePaint flag:
å public boolean getUseOutlinePaint();
Returns true if the renderer draws shape outlines using the outline paint, and false if the
regular series paint is used (the default).
å public void setUseOutlinePaint(boolean use);
Sets the flag that controls which paint is used for the shape outlines and sends a RendererChangeEvent
to all registered listeners.
35.16.6
Controlling Shape Filling
The renderer can fill each shape (with either the regular series paint or the series fill paint) or leave
the shapes empty (usually only when shape outlines are drawn). The flags that control this are set
using the “three layer, per series” approach common to many other renderer attributes.
CHAPTER 35. PACKAGE: ORG.JFREE.CHART.RENDERER.CATEGORY
408
å public boolean getItemShapeFilled(int series, int item);
Returns true if the shape for the specified item should be filled, and false if it should remain
unfilled. This method simply calls the getSeriesShapeFilled(int) method—override it if you
need to control the shape filling on a per item basis.
å public boolean getSeriesShapesFilled(int series);
Returns true if all shapes for the specified series should be filled, and false if they should
remain unfilled.
An override flag can control shape filling for all series:
å public Boolean getShapesFilled();
Returns Boolean.TRUE if all shapes are filled, Boolean.FALSE if all shapes are unfilled, and null
if the override setting does not apply.
å public void setShapesFilled(boolean filled);
Sets the override flag for filling all shapes, and sends a RendererChangeEvent to all registered
listeners.
å public void setShapesFilled(Boolean filled);
Sets the override flag for filling all shapes, and sends a RendererChangeEvent to all registered
listeners. If you set this to null, the override setting does not apply.
å public void setSeriesShapesFilled(int series, boolean filled);
Sets the flag that controls whether or not the shapes are filled for the specified series.
å public void setSeriesShapesFilled(int series, Boolean filled);
Sets the flag that controls whether or not the shapes are filled for the specified series (if null,
the default setting applies).
å public boolean getDefaultShapesFilled();
Returns the renderer’s default setting for filling shapes. This will be used only when the override
setting is null and the per-series setting is null.
å public void setDefaultShapesFilled(boolean flag);
Sets the default setting for filling shapes and sends a RendererChangeEvent to all registered
listeners.
The renderer can use either the regular series paint to fill shapes or the series fill paint, according
to the setting of the useFillPaint attribute:
å public boolean getUseFillPaint();
Returns true of the renderer should use the series fill paint to fill shapes, and false if it should
use the regular series paint.
å public void setUseFillPaint(boolean flag);
Sets the flag that controls whether the series fill paint or the regular series paint is used to fill
shapes.
Both the series fill paint and regular series paint settings are inherited from the AbstractRenderer
class.
35.16.7
Rendering Methods
The following methods are used during the chart drawing process, most applications won’t call
them directly:
å public int getPassCount();
Returns 2, to indicate that this renderer requires two passes through the dataset. Lines are
drawn in the first pass, and shapes are drawn in the second pass.
å public LegendItem getLegendItem(int datasetIndex, int series);
Returns a legend item for the specified series. The legend item will reflect the line and shape
visibility settings for the specified series.
å 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 item from the dataset. This method is called by the CategoryPlot class, you
don’t normally need to call it directly.
CHAPTER 35. PACKAGE: ORG.JFREE.CHART.RENDERER.CATEGORY
35.16.8
409
Equals, Cloning and Serialization
This renderer overrides the equals() method, and is Cloneable and Serializable
å public boolean equals(Object obj);
Returns true if this renderer is equal to the specified object, and false otherwise.
å public Object clone() throws CloneNotSupportedException;
Returns a clone of the renderer.
For general issues about these methods, refer to section 34.2.22.
35.17
LineRenderer3D
35.17.1
Overview
A line renderer that uses a pseudo 3D effect.
35.17.2
Constructor
To create a new renderer:
å public LineRenderer3D();
Creates a new default renderer.
35.17.3
General Attributes
The 3D effect is controlled by offsets that can be configured with the following methods:
å public double getXOffset();
Returns the x-offset for the 3D effect. The offset is measured in Java2D units. The default
value is 12.0.
å public void setXOffset(double xOffset);
Sets the x-offset (in Java2D units) for the 3D effect, and sends a RendererChangeEvent to all
registered listeners.
å public double getYOffset();
Returns the y-offset for the 3D effect. The offset is measured in Java2D units. The default
value is 8.0.
å public void setYOffset(double yOffset);
Sets the y-offset (in Java2D untis) for the 3D effect, and sends a RendererChangeEvent to all
registered listeners.
å public Paint getWallPaint();
Returns the paint used to color the offset part of the data area.
å public void setWallPaint(Paint paint);
Sets the paint used to color the offset part of the data area, and sends a RendererChangeEvent
to all registered listeners.
35.17.4
Drawing Methods
Various drawing methods are overridden to incorporate the 3D effect:
å public void drawBackground(Graphics2D g2, CategoryPlot plot, Rectangle2D dataArea);
Draws the plot background, taking into account the 3D offset defined by the renderer.
å public void drawOutline(Graphics2D g2, CategoryPlot plot, Rectangle2D dataArea);
Draws the plot outline, taking into account the 3D offset defined by the renderer.
å public void drawDomainGridline(Graphics2D g2, CategoryPlot plot, Rectangle2D dataArea, double
value);
Draws a domain gridline, adjusted for the 3D offset.
CHAPTER 35. PACKAGE: ORG.JFREE.CHART.RENDERER.CATEGORY
410
å public void drawRangeGridline(Graphics2D g2, CategoryPlot plot, ValueAxis axis, Rectangle2D
dataArea, double value);
Draws a range gridline, adjusted for the 3D offset.
å public void drawRangeMarker(Graphics2D g2, CategoryPlot plot, ValueAxis axis, Marker marker,
Rectangle2D dataArea);
Draws a range marker, adjusted for the 3D offset.
å public void drawItem(Graphics2D g2, CategoryItemRendererState state, Rectangle2D dataArea,
CategoryPlot plot, CategoryAxis domainAxis, ValueAxis rangeAxis, CategoryDataset dataset, int
row, int column, int pass);
Draws the visual representation of one data item on the chart.
35.17.5
Equals, Cloning and Serialization
This renderer overrides the equals() method:2
å public boolean equals(Object obj);
Tests this renderer for equality with an arbitrary object.
Instances of this class are cloneable and serializable.
35.18
MinMaxCategoryRenderer
35.18.1
Overview
A renderer that plots data from a CategoryDataset with:
• an icon for each data item;
• special icons for the minimum and maximum value items within each category;
• a line connecting the minimum and maximum value items within each category.
An example is shown in figure 35.15.
Figure 35.15: A chart that uses a MinMaxCategoryRenderer
35.18.2
Constructor
To create a new renderer:
å public MinMaxCategoryRenderer();
Creates a new renderer with default settings.
2 As
of JFreeChart 1.0.4.
CHAPTER 35. PACKAGE: ORG.JFREE.CHART.RENDERER.CATEGORY
35.18.3
411
Methods
The following methods are defined by this class:
å public boolean isDrawLines();
Returns true if lines are drawn to connect the items within a series, and false otherwise. The
default value is false.
å public void setDrawLines(boolean draw);
Sets the flag that controls whether or not lines are drawn to connect the items within a series.
If the new value of the flag is different to the old, a RendererChangeEvent is sent to all registered
listeners.
The renderer draws a line between the minimum and maximum value items within each category.
The Paint and Stroke for this line are controlled via the following methods:
å public Paint getGroupPaint();
Returns the paint used to draw the line between the minimum and maximum value items within
each category. The default value is Color.black. This method never returns null.
å public void setGroupPaint(Paint paint);
Sets the paint used to draw the line between the minimum and maximum value items within
each category, and sends a RendererChangeEvent to all registered listeners. An IllegalArgumentException
is thrown if paint is null.
å public void setGroupStroke(Stroke groupStroke);
Returns the stroke used to draw the line between the minimum and maximum value items
within each category. The default value is BasicStroke(1.0f). This method never returns null.
å public Stroke getGroupStroke();
Sets the stroke used to draw the line between the minimum and maximum value items within
each category, and sends a RendererChangeEvent to all registered listeners. An IllegalArgumentException
is thrown if stroke is null.
This renderer highlights data items by drawing an icon for each data value. There is a special icon
for the maximum and minimum value items within each category, and a regular icon for all other
data items.
å public Icon getObjectIcon();
Returns the Icon that is displayed for each data item (note that a special icon is displayed for
the data items with the minimum and maximum values in each category). The default icon is
a horizontal line. This method never returns null.
å public void setObjectIcon(Icon icon);
Sets the Icon that is displayed for each data item and sends a RendererChangeEvent to all
registered listeners. An IllegalArgumentException is thrown if icon is null.
å public Icon getMaxIcon();
Returns the Icon that is displayed for the maximum value data item within each category. The
default icon is a hollow circle. This method never returns null.
å public void setMaxIcon(Icon icon);
Sets the Icon that is displayed for the maximum value data item and sends a RendererChangeEvent
to all registered listeners. An IllegalArgumentException is thrown if icon is null.
å public Icon getMinIcon();
Returns the Icon that is displayed for the minimum value data item within each category. The
default icon is a hollow circle. This method never returns null.
å public void setMinIcon(Icon minIcon);
Sets the Icon that is displayed for the minimum value data item and sends a RendererChangeEvent
to all registered listeners. An IllegalArgumentException is thrown if icon is null.
CHAPTER 35. PACKAGE: ORG.JFREE.CHART.RENDERER.CATEGORY
35.18.4
412
Drawing Methods
Each item is drawn using the following method:
å public void drawItem(Graphics2D g2, CategoryItemRendererState state, Rectangle2D dataArea,
CategoryPlot plot, CategoryAxis domainAxis, ValueAxis rangeAxis, CategoryDataset dataset, int
row, int column, int pass);
Draws the specified item. This method is called by the CategoryPlot instance during chart
rendering, you won’t normally call it yourself.
35.19
StackedAreaRenderer
35.19.1
Overview
A renderer that draws a “stacked” form of area chart from the data in a CategoryDataset. An
example is shown in figure 35.16.
Figure 35.16: A chart that uses a StackedAreaRenderer
35.19.2
Constructors
This renderer has only the default constructor:
å public StackedAreaRenderer();
Creates a new renderer instance.
35.19.3
Methods
The super class (AreaRenderer) has methods that can be used to customise this renderer. The
methods added by this class are intended to be called by other JFreeChart classes, you won’t
normally need to call these methods yourself.
å public Range findRangeBounds(CategoryDataset dataset);
Returns the range of values that this renderer requires to display all the items from the dataset.
å 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.
CHAPTER 35. PACKAGE: ORG.JFREE.CHART.RENDERER.CATEGORY
35.19.4
413
Notes
Some points to note:
• a demo (StackedAreaChartDemo.java) is included in the JFreeChart demo distribution.
35.20
StackedBarRenderer
35.20.1
Overview
A renderer that draws stacked bar charts (this class extends the BarRenderer class). An example is
shown in figure 35.17. This renderer works with a CategoryPlot and any dataset that implements
the CategoryDataset interface.
Figure 35.17: A chart that uses a StackedBarRenderer
35.20.2
Constructors
This renderer has two constructors:
å public StackedBarRenderer();
Creates a new renderer instance with default settings.
å public StackedBarRenderer(boolean renderAsPercentages);
Creates a new renderer instance. If renderAsPercentages is true, each bar will represent a
percentage, and all the bars within a category will sum to 100%.
35.20.3
Displaying Bars as Percentage Values
The renderAsPercentages flag controls the style of chart drawn. If it is set to true, the bars all add
to 100 % within each category.
å public boolean getRenderAsPercentages();
Returns the flag that controls whether each bar represents the data value or its percentage of
the category total.
å public void setRenderAsPercentages(boolean asPercentages);
Sets the flag that controls whether each bar represents the data value or its percentage of the
category total. A RendererChangeEvent is sent to all registered listeners.
CHAPTER 35. PACKAGE: ORG.JFREE.CHART.RENDERER.CATEGORY
35.20.4
414
Other Methods
These methods are used internally by JFreeChart, you won’t normally need to call them directly.
å public int getPassCount();
Returns 2, the number of times the renderer needs to pass through the dataset for rendering.
The second pass is used to draw item labels, if they are visible.
å public Range findRangeBounds(CategoryDataset dataset);
Returns the range of values required by the renderer to ensure that all items in the dataset are
visible. This is used to set the default axis range.
å public void drawItem(Graphics2D g2, CategoryItemRendererState state,
Rectangle2D dataArea, CategoryPlot plot, CategoryAxis domainAxis,
ValueAxis rangeAxis, CategoryDataset data, int row, int column, int pass);
Draws one item from the dataset.
35.20.5
Equals, Cloning and Serialization
To test the renderer for equality with another object:
å public boolean equals(Object obj);
Tests this renderer for equality with an arbitrary object.
This renderer is Cloneable and Serializable.
35.20.6
Notes
Some points to note:
• to control the space between the bars, see the setCategoryMargin() method in the CategoryAxis
class.
• a demo (StackedBarChartDemo1.java) is included in the JFreeChart demo distribution.
35.21
StackedBarRenderer3D
35.21.1
Overview
A renderer that draws stacked bars with a 3D effect. An example is shown in figure 35.18. This
renderer works with a CategoryPlot class and uses data from any CategoryDataset.
Figure 35.18: A chart that uses a StackedBarRenderer3D
CHAPTER 35. PACKAGE: ORG.JFREE.CHART.RENDERER.CATEGORY
35.21.2
415
Constructors
To create a new renderer:
å public StackedBarRenderer3D();
Creates a new renderer with the renderAsPercentages flag set to false. All other defaults are
set by the super class (BarRenderer3D).
å public StackedBarRenderer3D(double xOffset, double yOffset);
Creates a new renderer with the specified offsets for the 3D effect.
å public StackedBarRenderer3D(boolean renderAsPercentages);
Creates a new renderer with the specified value for the renderAsPercentages flag. All other
defaults are set by the super class (BarRenderer3D). [Since 1.0.2]
å public StackedBarRenderer3D(double xOffset, double yOffset, boolean renderAsPercentages);
Creates a new renderer with the specified offsets for the 3D effect and the specified value for
the renderAsPercentages flag. [Since 1.0.2]
35.21.3
Methods
The renderAsPercentages flag controls whether the values are displayed as percentages that stack
up to 100%—see figure 35.19 for an example:
Figure 35.19: A StackedBarRenderer3D with renderAsPercentages set
å public boolean getRenderAsPercentages();
Returns true if the renderer displays values in percentage terms, and false if the actual values
are displayed. [Since 1.0.2]
å public void setRenderAsPercentages(boolean asPercentages);
Sets the flag that controls whether the renderer displays values in percentage terms or as
outright values and sends a RendererChangeEvent to all registered listeners. [Since 1.0.2]
The remaining methods are called by JFreeChart, you won’t normally need to call them yourself:
å public int getPassCount();
Returns 2, the number of passes through the dataset required by the renderer. The second pass
is used to draw the item labels, if they are visible.
å public Range findRangeBounds(CategoryDataset dataset);
Returns the range of values required by the renderer to display all the items in the dataset.
This is used to set the default axis range. If the renderAsPercentages flag is true, the range is
0.0 to 1.0, otherwise it is the range that covers the sum of the stacked values.
å public void drawItem(Graphics2D g2, CategoryItemRendererState state,
Rectangle2D dataArea, CategoryPlot plot, CategoryAxis domainAxis,
ValueAxis rangeAxis, CategoryDataset data, int row, int column, int pass);
Draws one item from the dataset.
CHAPTER 35. PACKAGE: ORG.JFREE.CHART.RENDERER.CATEGORY
35.21.4
416
Equals, Cloning and Serialization
To test this renderer for equality with an arbitrary object:
å public boolean equals(Object obj);
Returns true if and only if:
• obj is not null;
• obj is an instance of StackedBarRenderer3D;
• all the fields in this renderer match those in obj.
Instances of this class are Cloneable and Serializable.
35.21.5
Notes
Some points to note:
• when using this renderer, you need to ensure that the plot is using axes that support the
3D effect—see CategoryAxis3D and NumberAxis3D. This is because the size of the data area is
slightly reduced to make space for the 3D effect, and the axes need to take this into account;
• a demo (StackedBarRenderer3DDemo1.java) is included in the JFreeChart demo distribution.
See Also
BarRenderer3D, StackedBarRenderer.
35.22
StatisticalBarRenderer
35.22.1
Overview
A renderer that draws bars for each data value and then overlays a standard deviation indicator.
An example is shown in figure 35.20. This renderer works with a CategoryPlot and requires a
StatisticalCategoryDataset.
Figure 35.20: A chart that uses a StatisticalBarRenderer
35.22.2
Constructors
This renderer has only the default constructor:
å public StatisticalBarRenderer();
Creates a new renderer instance. The errorIndicatorPaint defaults to Color.gray. Other defaults are inherited from BarRenderer.
CHAPTER 35. PACKAGE: ORG.JFREE.CHART.RENDERER.CATEGORY
35.22.3
417
Attributes
In addition to the attributes inherited from BarRenderer, this class defines an errorIndicatorPaint
attribute:
å public Paint getErrorIndicatorPaint();
Returns the paint used to display the error indicator for each bar. If this is null then the item
outline paint is used instead.
å public void setErrorIndicatorPaint(Paint paint);
Sets the paint used to display the error indicator for each bar, then sends a RendererChangeEvent
to registered listeners. You can set this to null, in which case the item outline paint will be
used for the error indicators instead.
35.22.4
Other Methods
The renderer overrides the drawItem() method, which is called by JFreeChart when a chart is being
drawn (normally you won’t need to call this method yourself):
å public void drawItem(Graphics2D g2, CategoryItemRendererState state,
Rectangle2D dataArea, CategoryPlot plot, CategoryAxis domainAxis,
ValueAxis rangeAxis, CategoryDataset data, int row, int column, int pass);
Draws one item from the dataset.
35.22.5
Equals, Cloning and Serialization
To test the renderer for equality with another object:
å public boolean equals(Object obj);
Tests this renderer for equality with an arbitrary object.
This class is Cloneable and Serializable.
35.22.6
Notes
Some points to note:
• a demo (StatisticalBarChartDemo1.java) is included in the JFreeChart demo distribution.
35.23
StatisticalLineAndShapeRenderer
35.23.1
Overview
A renderer that draws lines and/or shapes for each data value and then overlays a standard deviation
indicator. An example is shown in figure 35.21. This renderer works with a CategoryPlot and
requires a StatisticalCategoryDataset.
35.23.2
Constructors
This renderer has two constructors:
å public StatisticalLineAndShapeRenderer();
Creates a new renderer instance. By default, both lines and shapes are visible. The errorIndicatorPaint
defaults to null, which means the series paint will be used. Other defaults are inherited from
LineAndShapeRenderer.
å public StatisticalLineAndShapeRenderer(boolean linesVisible,
boolean shapesVisible);
Creates a new renderer instance with lines and/or shapes visible as requested. The errorIndicatorPaint
defaults to null, which means the series paint will be used. Other defaults are inherited from
LineAndShapeRenderer.
CHAPTER 35. PACKAGE: ORG.JFREE.CHART.RENDERER.CATEGORY
418
Figure 35.21: A chart that uses a StatisticalLineAndShapeRenderer
35.23.3
Attributes
In addition to the attributes inherited from LineAndShapeRenderer, this class defines an errorIndicatorPaint attribute:
å public Paint getErrorIndicatorPaint();
Returns the paint used to display the error indicator for each item. If this is null then the
item paint is used instead (that is, the error indicator will use the same color as the line/shape
for the item).
å public void setErrorIndicatorPaint(Paint paint);
Sets the paint used to display the error indicator for each item, then sends a RendererChangeEvent
to registered listeners. You can set this to null, in which case the item paint will be used for
the error indicators instead.
35.23.4
Other Methods
The renderer overrides the drawItem() method, which is called by JFreeChart when a chart is being
drawn (normally you won’t need to call this method yourself):
å public void drawItem(Graphics2D g2, CategoryItemRendererState state,
Rectangle2D dataArea, CategoryPlot plot, CategoryAxis domainAxis,
ValueAxis rangeAxis, CategoryDataset data, int row, int column, int pass);
Draws one item from the dataset.
35.23.5
Equals, Cloning and Serialization
To test the renderer for equality with another object:
å public boolean equals(Object obj);
Tests this renderer for equality with an arbitrary object.
This class is Cloneable and Serializable.
35.23.6
Notes
Some points to note:
• a demo (StatisticalLineChartDemo1.java) is included in the JFreeChart demo distribution.
CHAPTER 35. PACKAGE: ORG.JFREE.CHART.RENDERER.CATEGORY
35.24
WaterfallBarRenderer
35.24.1
Overview
419
A renderer for drawing “waterfall” charts on a CategoryPlot using data from a CategoryDataset. A
waterfall chart highlights the difference between two values and the components that make up that
difference. An example is shown in figure 35.22.
Figure 35.22: A chart that uses a WaterfallBarRenderer
35.24.2
Constructors
This renderer has two constructors:
å public WaterfallBarRenderer();
Creates a new renderer with default colors. The defaults are blue for the first value/bar, yellow
for the last value/bar, green for intermediate values that are positive and red for intermediate
values that are negative.
å public WaterfallBarRenderer(Paint firstBarPaint,
Paint positiveBarPaint, Paint negativeBarPaint, Paint lastBarPaint);
Creates a new renderer with the specified colors. An IllegalArgumentException is thrown if any
of these is null.
35.24.3
Methods
This renderer defines the following methods to control the color of the bars it draws:
å public Paint getFirstBarPaint();
Returns the paint used for the first bar drawn—this will never be null.
å public void setFirstBarPaint(Paint paint);
Sets the paint used for the first bar, and sends a RendererChangeEvent to all registered listeners.
An IllegalArgumentException is thrown if the supplied argument is null.
å public Paint getLastBarPaint();
Returns the paint used for the last bar drawn—this will never be null.
å public void setLastBarPaint(Paint paint);
Sets the paint used for the last bar drawn by the renderer, and sends a RendererChangeEvent
to all registered listeners. An IllegalArgumentException is thrown if the supplied argument is
null.
å public Paint getPositiveBarPaint();
Returns the paint used for intermediate bars that have a positive value—this will never be null.
CHAPTER 35. PACKAGE: ORG.JFREE.CHART.RENDERER.CATEGORY
420
å public void setPositiveBarPaint(Paint paint);
Sets the paint used for the intermediate bars representing positive values, and sends a RendererChangeEvent
to all registered listeners.
An IllegalArgumentException is thrown if the supplied argument is null.
å public Paint getNegativeBarPaint();
Returns the paint used for intermediate bars that have a negative value—this will never be
null.
å public void setNegativeBarPaint(Paint paint);
Sets the paint used for the intermediate bars representing negative values, and sends a RendererChangeEvent
to all registered listeners.
An IllegalArgumentException is thrown if the supplied argument is null.
Further methods for customising the renderer are inherited from the BarRenderer class.
35.24.4
Other Methods
The renderer has a couple of other methods that will be called by the CategoryPlot class when it is
drawing the chart—you won’t typically call these methods directly.
å public Range findRangeBounds(CategoryDataset dataset);
Returns the range of values that this renderer needs to display all the data in the specified
dataset.
å 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.
35.24.5
Equals, Cloning and Serialization
To test an object for equality with this renderer:
å public boolean equals(Object obj);
Tests this renderer for equality with an arbitrary object.
This renderer can be Cloneable and Serializable.
35.24.6
Notes
Some points to note:
• a “shortcut” has been taken in the implementation of this renderer: the value for the last
bar could be derived from the values of the other bars, but instead the renderer expects the
final value to be part of the dataset. This means that you need to ensure that the final value
corresponds to the sum of the preceding values (although this is not enforced).
• the createWaterfallChart() method in the ChartFactory class can be used to create a “ready
made” chart;
• a demo (WaterfallChartDemo1.java) is included in the JFreeChart demo distribution.
Chapter 36
Package:
org.jfree.chart.renderer.xy
36.1
Overview
This package contains interfaces and classes that are used to implement renderers for the XYPlot
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
AbstractXYItemRenderer
36.2.1
Overview
A base class (extending AbstractRenderer) that can be used for creating new XYItemRenderer implementations.
36.2.2
Constructors
This class provides a default constructor which allocates storage for the label generator(s), the tool
tip generator(s) and the URL generator.
å protected AbstractXYItemRenderer();
Creates a new renderer.
36.2.3
Initialisation
Each time a chart is drawn, the plot will initialise the renderer by calling the following method:
å public XYItemRendererState initialise()
Initialises the renderer and returns a state object that the plot will pass to all subsequent calls
to the drawItem() method. The state object is discarded once the chart is fully drawn.
36.2.4
The Pass Count
The pass count refers to the number of times the XYPlot scans through the dataset passing individual
data items to the renderer for drawing. Most renderers require only a single pass through the
dataset, but some will use a second pass to overlay shapes (for example) over previously drawn
items.
The plot will call the following method to determine how many passes the renderer requires:
421
CHAPTER 36. PACKAGE: ORG.JFREE.CHART.RENDERER.XY
422
å public int getPassCount();
Returns 1 to indicate that the renderer requires only a single pass through the dataset.
Renderers that require more than one pass through the dataset should override this method.
36.2.5
Domain and Range Markers
A default method is supplied for displaying a domain marker as a line on the plot:
å public void drawDomainMarker(...);
Draws a line perpendicular to the domain axis to represent a Marker.
A default method is supplied for displaying a range marker as a line on the plot:
å public void drawRangeMarker(...);
Draws a line perpendicular to the range axis to represent a Marker.
Most renderers will use these methods by default, but some may override them.
36.2.6
Grid Bands
It is possible to fill the space between alternate grid lines with a different color to create a “band”
effect.
36.2.7
Methods
To create a legend item for a series (this method is called by the plot):
å public LegendItem getLegendItem(int index, int series);
Returns a legend item that represents the specified series. The index argument tells the renderer
which dataset it is rendering (only the plot tracks this)—0 for the primary dataset, or n+1 for
a secondary dataset (where n is the index of the secondary dataset).
36.2.8
Notes
Some points to note:
• this class provides a property change mechanism to support the requirements of the XYItemRenderer
interface;
See Also
XYItemRenderer, XYPlot.
36.3
CandlestickRenderer
36.3.1
Overview
A candlestick renderer draws each item from an OHLCDataset as a box with lines extending from the
top and bottom. Candlestick charts are typically used to display financial data—the box represents
the open and closing prices, while the lines indicate the high and low prices for a trading period
(often one day).
This renderer is designed for use with the XYPlot class.
This renderer also has the ability to represent volume information in the background of the chart.
36.3.2
Constructors
To create a new renderer:
å public CandlestickRenderer(double candleWidth);
Creates a new renderer.
CHAPTER 36. PACKAGE: ORG.JFREE.CHART.RENDERER.XY
423
Figure 36.1: A sample chart using CandlestickRenderer
36.3.3
Methods
To set the width of the candles (in points):
å public void setCandleWidth(double width);
Sets the width of each candle. If the value is negative, then the renderer will automatically
determine a width each time the chart is redrawn.
To set the color used to fill candles when the closing price is higher than the opening price (the
price has moved up):
å public void setUpPaint(Paint paint);
Sets the fill color for candles where the closing price is higher than the opening price.
To set the color used to fill candles when the closing price is lower than the opening price (the price
has moved down):
å public void setDownPaint(Paint paint);
Sets the fill color for candles where the closing price is lower than the opening price.
To control whether or not volume bars are drawn in the background of the chart:
å public void setDrawVolume(boolean flag);
Controls whether or not volume bars are drawn in the background of the chart.
These methods will fire a property change event that will be picked up by the XYPlot class, triggering
a chart redraw.
36.3.4
Notes
This renderer requires an OHLCDataset.
36.4
ClusteredXYBarRenderer
36.4.1
Overview
A renderer that draws bars from the items in an IntervalXYDataset—see figure 36.2.
This renderer is designed to work with an XYPlot. It differs slightly from the XYBarRenderer class,
in that it adjusts the position and width of each of the bars, making the assumption that the bars
for all the series should be clustered within the same x-interval.
CHAPTER 36. PACKAGE: ORG.JFREE.CHART.RENDERER.XY
424
Figure 36.2: A sample chart using ClusteredXYBarRenderer
36.4.2
Constructors
Two constructors are defined:
å public ClusteredXYBarRenderer();
Equivalent to ClusteredXYBarRenderer(0.0, false)—see next constructor.
å public ClusteredXYBarRenderer(double margin, boolean centerBarAtStartValue);
Creates a new renderer. The margin (a percentage) indicates how much (if any) of each bar
should be trimmed off. The centerBarAtStartValue flag controls whether or not the cluster of
bars is shifted so that it centers around the starting x-value returned by the dataset.
36.4.3
Methods
The drawItem() method handles the rendering of a single item for the plot.
36.4.4
Equals, Cloning and Serialization
This class overrides the equals() method:
å public boolean equals(Object obj);
Tests this renderer for equality with an arbitrary object. Returns true if and only if:
• obj is not null;
• obj is an instance of ClusteredXYBarRenderer;
• obj has the same values for the margin and centerBarAtStartValue attributes;
• super.equals(obj) returns true.
Instances of this class are Cloneable and Serializable.
36.4.5
Notes
Some points to note:
• this renderer casts the dataset to IntervalXYDataset, so you should ensure that the plot is
supplied with the correct type of data;
• it would probably be a good idea to merge this class with the XYBarRenderer class, but this
hasn’t been done yet.
See Also
XYBarRenderer.
CHAPTER 36. PACKAGE: ORG.JFREE.CHART.RENDERER.XY
36.5
CyclicXYItemRenderer
36.5.1
Overview
425
A renderer for drawing “cyclic” charts.
See Also
CyclicNumberAxis.
36.6
DefaultXYItemRenderer
36.6.1
Overview
This class is an alias for the XYLineAndShapeRenderer class.
36.7
HighLowRenderer
36.7.1
Overview
A high-low renderer draws each item in an OHLCDataset using lines to mark the “high-low” range
for a trading period, plus small marks to indicate the “open” and “close” values.
Figure 36.3: A chart that uses a HighLowRenderer
This renderer is designed for use with the XYPlot class. It requires an OHLCDataset.
36.7.2
Constructors
To create a new renderer:
å public HighLowRenderer();
Creates a new renderer.
36.7.3
Methods
The renderer has flags that control whether or not the open and close ticks are drawn for each data
value:
å public boolean getDrawOpenTicks();
Returns the flag that controls whether or not the open tick is drawn for each data value.
CHAPTER 36. PACKAGE: ORG.JFREE.CHART.RENDERER.XY
426
å public void setDrawOpenTicks(boolean draw);
Sets the flag that controls whether or not an open tick is drawn for each data value (the default
value is true). A RendererChangeEvent is sent to all registered listeners.
å public boolean getDrawCloseTicks();
Returns the flag that controls whether or not the close tick is drawn for each data value.
å public void setDrawCloseTicks(boolean draw);
Sets the flag that controls whether or not a close tick is drawn for each data value (the default
value is true). A RendererChangeEvent is sent to all registered listeners.
The paint used for the open and close ticks is the same as the series paint, but it can be overridden
with the following methods:
å public Paint getOpenTickPaint();
Returns the paint (possibly null) used for the open tick mark.
å public void setOpenTickPaint(Paint paint);
Sets the paint used to draw the open tick mark for each data value. If this is null (the default)
then the renderer’s series paint is used instead.
å public Paint getCloseTickPaint();
Returns the paint (possibly null) used for the close tick mark.
å public void setCloseTickPaint(Paint paint);
Sets the paint used to draw the open tick mark for each data value. If this is null (the default)
then the renderer’s series paint is used instead.
Finally, this class implements the drawItem() method defined in the XYItemRenderer interface:
å public void drawItem(Graphics2D g2, XYItemRendererState state, Rectangle2D dataArea,
PlotRenderingInfo info, XYPlot plot, ValueAxis domainAxis, ValueAxis rangeAxis,
XYDataset dataset, int series, int item, CrosshairState crosshairState, int pass);
Draws a single item in the dataset. This method is called by the XYPlot class during chart
rendering—you won’t normally call this method yourself.
36.7.4
Equals, Cloning and Serialization
This class overrides the equals method:
å public boolean equals(Object obj);
Tests this renderer for equality with an arbitary object. This method returns true if and only
if:
• obj is not null,
• obj is an instance of HighLowRenderer,
• obj and this renderer have the same field values.
Instances of this class are Cloneable and Serializable.
36.7.5
Notes
Some points to note:
• this renderer requires the dataset to be an instance of OHLCDataset;
• the createHighLowChart() method in the ChartFactory class makes use of this renderer.
36.8
StackedXYAreaRenderer
36.8.1
Overview
A stacked area renderer that draws items from a TableXYDataset. An example is shown in figure
36.4.
CHAPTER 36. PACKAGE: ORG.JFREE.CHART.RENDERER.XY
427
Figure 36.4: A chart created using StackedXYAreaRenderer
36.9
StackedXYBarRenderer
36.9.1
Overview
A renderer for drawing stacked bar charts using data from a TableXYDataset—see figure 36.5 for an
example.
Figure 36.5: A chart generated with a StackedXYBarRenderer.
This class extends XYBarRenderer.
36.9.2
Constructors
There are two constructors:
å public StackedXYBarRenderer();
Creates a new instance with default settings.
å public StackedXYBarRenderer(double margin);
Creates a new instance with the specified margin. The margin is a percentage amount to trim
off the width of each bar drawn by the renderer—for example, 0.10 is ten percent.
36.9.3
Methods
This renderer extends XYBarRenderer. The following methods are overridden:
CHAPTER 36. PACKAGE: ORG.JFREE.CHART.RENDERER.XY
428
å public Range getRangeExtent(XYDataset dataset);
Calculates the range of values represented by the dataset, taking into account the fact that the
renderer “stacks” values and that the base value may be non-zero (see the getBase() method
in the XYBarRenderer class).
å public XYItemRendererState initialise(Graphics2D g2, Rectangle2D dataArea, XYPlot plot,
XYDataset data, PlotRenderingInfo info);
Initialises the renderer. This method is called by the XYPlot class, you won’t normally need to
call it yourself.
å public void drawItem(Graphics2D g2, XYItemRendererState state, Rectangle2D dataArea,
PlotRenderingInfo info, XYPlot plot, ValueAxis domainAxis, ValueAxis rangeAxis,
XYDataset dataset, int series, int item, CrosshairState crosshairState, int pass);
Draws one item from the dataset. This method is called by the XYPlot class, you won’t normally
need to call it yourself.
36.9.4
Notes
Some points to note:
• this renderer requires a dataset that implements the TableXYDataset interface (which guarantees that all series share the same set of x-values, a requirement to allow values to be
“stacked”).
• a demo (StackedXYBarChartDemo1.java) is included in the JFreeChart Demo distribution.
36.10
StandardXYItemRenderer
36.10.1
Overview
A standard renderer for the XYPlot class. This renderer represents data by drawing lines between
(x, y) data points. There is also a mechanism for drawing shapes or images at each at each (x, y)
data point (with or without the lines).
36.10.2
Constructors
To create a StandardXYItemRenderer:
å public StandardXYItemRenderer(int type);
Creates a new renderer. The type argument should be one of: LINES, SHAPES or SHAPES AND LINES.
36.10.3
Methods
To control whether or not the renderer draws lines between data points:
å public void setPlotLines(boolean flag);
Sets the flag that controls whether or not lines are plotted between data points. The stroke
and paint used for the lines is determined by the plot, per series.
To control whether or not the renderer draws shapes at each data point:
å public void setPlotShapes(boolean flag);
Sets the flag that controls whether or not shapes are plotted at each data point.
For each item, the shape to be plotted is obtained from the getShape() method which, unless
overridden, delegates to the plot’s getShape() method (which will return a different shape for
each series).
When the renderer draws each shape, it can draw an outline of the shape, or it can fill the shape
with a solid color. This is controlled by a protected method:
CHAPTER 36. PACKAGE: ORG.JFREE.CHART.RENDERER.XY
429
å protected boolean isShapeFilled();
Returns a flag that controls whether or not the shape is filled.
By default, this method returns the value from the getDefaultShapeFilled() method, but you
can override the method in a subclass to customise the behaviour.
36.10.4
Notes
This class implements the XYItemRenderer interface.
The XYPlot class will use an instance of this class as its default renderer.
36.11
WindItemRenderer
36.11.1
Overview
A renderer that XYPlot uses to draw wind plots.
Figure 36.6: A sample chart using WindItemRenderer
36.11.2
Notes
Some points to note:
• this renderer requires a WindDataset for the data;
• a demo (WindChartDemo1.java) is included in the JFreeChart demo collection.
36.12
XYAreaRenderer
36.12.1
Overview
A renderer draws each item in an XYDataset using a polygon that fills the area between the x-axis
and the data point—see figure 36.7 for an example.
This renderer is designed to be used with the XYPlot class.
36.12.2
Constructors
The default constructor sets up the renderer to draw area charts:
CHAPTER 36. PACKAGE: ORG.JFREE.CHART.RENDERER.XY
430
Figure 36.7: A chart using XYAreaRenderer
å public XYAreaRenderer();
Creates a new renderer.
You can change the appearance of the chart by specifying the type:
å public XYAreaRenderer(int type);
Creates a new XYAreaRenderer using one of the following types: SHAPES, LINES, SHAPES AND LINES,
AREA, AREA AND SHAPES.
A further constructor allows you to specify the tool tip and URL generators:
å public XYAreaRenderer(int type, XYToolTipGenerator labelGenerator,
XYURLGenerator urlGenerator);
Creates a new renderer with the specified tool tip generator and URL generator.
36.12.3
Methods
A flag controls whether or not outlines are drawn for the area representing each series:
å public boolean isOutline();
Returns the flag that controls whether or not outlines are drawn.
å public void setOutline(boolean show);
Sets the flag that controls whether or not outlines are drawn.
Several flags control the rendering process. These flags are initialised in the constructor, and cannot
be updated without creating a new renderer:
å public boolean getPlotShapes();
Returns the flag that controls whether or not shapes are drawn at each data point.
å public boolean getPlotLines();
Returns the flag that controls whether or not lines are drawn between each data point.
å public boolean getPlotArea();
Returns a flag that controls whether or not the area is being filled for each series.
To initialise the renderer (this method is called by the plot, you won’t normally need to call it
yourself):
å public XYItemRendererState initialise(Graphics2D g2,
Rectangle2D dataArea, XYPlot plot, XYDataset data, PlotRenderingInfo info);
Initialises the renderer. The plot will call this method at the start of the drawing process, each
time a chart is drawn.
å public void drawItem(Graphics2D g2, XYItemRendererState state,
Rectangle2D dataArea, PlotRenderingInfo info, XYPlot plot,
ValueAxis domainAxis, ValueAxis rangeAxis, XYDataset dataset,
int series, int item, CrosshairState crosshairState, int pass);
Draws a single item (this method is called by the plot).
CHAPTER 36. PACKAGE: ORG.JFREE.CHART.RENDERER.XY
36.12.4
431
Notes
Some points to note:
• this class extends AbstractXYItemRenderer;
• instances of this class are cloneable and serializable;
• this class uses code copied from the StandardXYItemRenderer class, and that some additional
work is required to eliminate the duplication. One option (still under consideration) for a
future version of JFreeChart is to merge the two classes.
See Also
AreaRenderer.
36.13
XYBarRenderer
36.13.1
Overview
This renderer can be used within an XYPlot to draw bar charts with data from an IntervalXYDataset—
see figure 36.8 for an example.
Figure 36.8: A chart generated with an XYBarRenderer.
Related to this class is ClusteredXYBarRenderer.
36.13.2
Constructors
To create a new instance:
å public XYBarRenderer();
Creates a new renderer. The margin defaults to 0.0 (see the next constructor).
å public XYBarRenderer(double margin);
Creates a new renderer with the specified margin (which is expressed as a percentage, for
example 0.10 is ten percent).
CHAPTER 36. PACKAGE: ORG.JFREE.CHART.RENDERER.XY
36.13.3
432
Methods
To control the “margin” for the renderer:
å public double getMargin();
Returns the margin used by the renderer, as a percentage of the bar width (for example, 0.10
is ten percent).
å public void setMargin(double margin);
Sets the margin for the renderer and sends a RendererChangeEvent to all registered listeners.
The margin is specified as a percentage of the bar width (for example, 0.10 is ten percent) and
is the amount that is trimmed from the bar width before the bar is displayed.
To control whether or not outlines are drawn for each bar:
å public boolean isDrawBarOutline();
Returns a flag that controls whether or not bar outlines are drawn.
å public void setDrawBarOutline(boolean draw);
Sets a flag that controls whether or not bar outlines are drawn, and sends a RendererChangeEvent
to all registered listeners.
To control the way that the length of the bars is determined:
å public double getBase();
Returns the base value for the bars (usually 0.0, but you can set it to any value).
å public void setBase(double base);
Sets the base value for the bars (defaults to 0.0). This setting is ignored if the getUseYInterval()
method returns true.
å public boolean getUseYInterval();
Returns a flag that controls how the length of the bars is determined.
å public void setUseYInterval(boolean use);
Sets a flag that controls how the length of the bars is determined. If true, the y-interval from
the dataset is used. If false, the y-value from the dataset determines one end of the bar, and
the getBase() method determines the other end of the bar.
This renderer supports the use of GradientPaint for any series color by using a transformer:
å public GradientPaintTransformer getGradientPaintTransformer();
Returns the transformer used for GradientPaint instances.
å public void setGradientPaintTransformer(GradientPaintTransformer transformer);
Sets the transformer used for GradientPaint instances.
The following two methods are usually called by the XYPlot, you shouldn’t need to call them directly:
å public XYItemRendererState initialise(Graphics2D g2, Rectangle2D dataArea, XYPlot plot,
XYDataset dataset, PlotRenderingInfo info);
Initialises the renderer for drawing a chart.
å public void drawItem(Graphics2D g2, XYItemRendererState state, Rectangle2D dataArea,
PlotRenderingInfo info, XYPlot plot, ValueAxis domainAxis, ValueAxis rangeAxis,
XYDataset dataset, int series, int item, CrosshairState crosshairState, int pass);
Draws one item from the dataset.
36.13.4
Equals, Cloning and Serialization
This class overrides the equals(Object) method:
å public boolean equals(Object obj);
Tests this renderer for equality with an arbitrary object (null is permitted). This method
returns true if and only if:
• obj is not null;
• obj is an instance of XYBarRenderer;
• both renderers have the same attributes (excluding the registered listeners).
Instances of this class are cloneable and serializable.
CHAPTER 36. PACKAGE: ORG.JFREE.CHART.RENDERER.XY
36.13.5
433
Notes
Some points to note:
• this renderer casts the dataset to IntervalXYDataset, so you should ensure that the plot is
supplied with the correct type of data.
36.14
XYBlockRenderer
36.14.1
Overview
A renderer that draws coloured (or gray-scale) blocks to represent the z-values from an XYZDataset.
For example see figure 36.9.
XYBlockChartDemo1
1.00
45
0.95
40
0.90
30
0.85
25
0.80
20
0.75
15
0.70
10
0.65
5
0.60
0
0.55
Scale
Y
35
-5
-10
-15
0.50
0.45
0.40
-20
0.35
-25
0.30
-30
0.25
-35
0.20
-40
0.15
-45
0.10
-50
-50
-40
-30
-20
-10
0
10
20
30
40
X
0.05
0.00
Figure 36.9: A sample chart (see XYBlockChartDemo1.java)
This renderer was first introduced in JFreeChart version 1.0.4.
36.14.2
Constructors
To create a new renderer:
å public XYBlockRenderer(); [1.0.4]
Creates a new renderer with the following defaults:
• blockWidth = 1.0;
• blockHeight = 1.0;
• blockAnchor = RectangleAnchor.CENTER;
• paintScale = new LookupPaintScale();.
36.14.3
Attributes
To control the width and height of the blocks drawn by this renderer:
å public double getBlockWidth(); [1.0.4]
Returns the block width in data units (that is, measured against the domain axis). The default
value is 1.0.
CHAPTER 36. PACKAGE: ORG.JFREE.CHART.RENDERER.XY
434
å public void setBlockWidth(double width); [1.0.4]
Sets the block width and sends a RendererChangeEvent to all registered listeners. If width is less
than or equal to zero, this method throws an IllegalArgumentException.
å public double getBlockHeight(); [1.0.4]
Returns the block height in data units (that is, measured against the range axis). The default
value is 1.0.
å public void setBlockHeight(double height); [1.0.4]
Sets the block height and sends a RendererChangeEvent to all registered listeners. If height is
less than or equal to zero, this method throws an IllegalArgumentException.
Each block drawn by the renderer is aligned to its (x, y) location using an anchor point:
å public RectangleAnchor getBlockAnchor(); [1.0.4]
Returns the anchor point on the block that will be aligned to the (x, y) location on the plot.
The default value is RectangleAnchor.CENTER.
å public void setBlockAnchor(RectangleAnchor anchor); [1.0.4]
Sets the anchor point and sends a RendererChangeEvent to all registered listeners. If anchor is
null, this method throws an IllegalArgumentException.
To access the paint scale used by the renderer:
å public PaintScale getPaintScale(); [1.0.4]
Returns the paint scale used by this renderer (never null).
å public void setPaintScale(PaintScale scale); [1.0.4]
Sets the paint scale used by this renderer and sends a RendererChangeEvent to all registered
listeners. If scale is null, this method throws an IllegalArgumentException.
36.14.4
Other Methods
The axis ranges required by this renderer are slightly greater than the default ranges calculated on
the basis of the x-values and y-value alone, because the renderer draws blocks at each data point.
The following method overrides take this into account:
å public Range findDomainBounds(XYDataset dataset); [1.0.4]
Returns the domain axis range required to display all the data in the specified dataset.
å public Range findRangeBounds(XYDataset dataset); [1.0.4]
Returns the range axis range required to display all the data in the specified dataset.
Each item is drawn with a call to the following method (JFreeChart calls this method, you don’t
have to):
å public void drawItem(Graphics2D g2, XYItemRendererState state, Rectangle2D dataArea,
PlotRenderingInfo info, XYPlot plot, ValueAxis domainAxis, ValueAxis rangeAxis,
XYDataset dataset, int series, int item, CrosshairState crosshairState,
int pass); [1.0.4]
Draws the block for one item in the dataset.
36.14.5
Equals, Cloning and Serialization
This class overrides the equals() method:
å public boolean equals(Object obj); [1.0.4]
Tests this renderer for equality with an arbitrary object.
Instances of this class are Cloneable and Serializable.
CHAPTER 36. PACKAGE: ORG.JFREE.CHART.RENDERER.XY
36.14.6
435
Notes
Some points to note:
• this renderer works with an XYPlot;
• the dataset must be an instance of XYZDataset, because the block colours are determined by
the z-value in the dataset;
• several demos (XYBlockChartDemo1-3.java) are included in the JFreeChart demo collection.
See Also
XYZDataset.
36.15
XYBoxAndWhiskerRenderer
36.15.1
Overview
A renderer that is used to create a box-and-whisker chart using data from an XYBoxAndWhiskerDataset.
A sample chart is shown in Figure 36.10.
Figure 36.10: A chart generated with an XYBoxAndWhiskerRenderer.
36.15.2
Constructors
To create a new renderer:
å public XYBoxAndWhiskerRenderer();
Creates a new renderer where the box width is calculated automatically.
å public XYBoxAndWhiskerRenderer(double boxWidth);
Creates a new renderer with the specified box width.
36.15.3
Notes
Some points to note:
• for tool tips, you can use the BoxAndWhiskerXYToolTipGenerator class;
• there is a demo (XYBoxAndWhiskerDemo1.java) included in the JFreeChart demo collection.
See Also
BoxAndWhiskerRenderer.
CHAPTER 36. PACKAGE: ORG.JFREE.CHART.RENDERER.XY
36.16
XYBubbleRenderer
36.16.1
Overview
436
An XYBubbleRenderer displays items from an XYZDataset by drawing a bubble at each (x, y) point.
The size (diameter) of the bubble is determined by the z-value from the dataset.
36.16.2
Constructors
The following constructors are defined:
å public XYBubbleRenderer();
Equivalent to XYBubbleRenderer(SCALE ON BOTH AXES)—see the next constructor.
å public XYBubbleRenderer(int scaleType);
Creates a new renderer with the specified scaleType, which must be one of the following integer
constants defined by this class:
• SCALE ON BOTH AXES;
• SCALE ON DOMAIN AXIS;
• SCALE ON RANGE AXIS.
The width and height of the bubble is calculated from the dataset’s z-value scaled against the
specified axis.
36.16.3
Attributes
The scaleType attribute determines how the bubble is scaled relative to the domain and range axes:
å public int getScaleType();
Returns the method used to determine the size of the bubbles drawn by this renderer:
• SCALE ON BOTH AXES – bubbles are drawn as ellipses where the width and height of the
ellipse is determined by the z-value scaled against both axes;
• SCALE ON DOMAIN AXIS – bubbles are drawn as circles where the diameter of the circle is
determined by the z-value scaled against the domain axis;
• SCALE ON RANGE AXIS – bubbles are drawn as circles where the diameter of the circle is
determined by the z-value scaled against the range axis.
36.16.4
Other Methods
The following methods are called by JFreeChart—you won’t normally call them directly.
å public LegendItem getLegendItem(int datasetIndex, int series);
Returns a legend item for the specified series. This method is overridden so that the legend
item has a circle for the legend graphic.
å public void drawItem(Graphics2D g2, XYItemRendererState state, Rectangle2D dataArea,
PlotRenderingInfo info, XYPlot plot, ValueAxis domainAxis, ValueAxis rangeAxis,
XYDataset dataset, int series, int item, CrosshairState crosshairState, int pass);
Draws a bubble representing one item from the dataset.
CHAPTER 36. PACKAGE: ORG.JFREE.CHART.RENDERER.XY
36.16.5
437
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 XYBubbleRenderer;
• obj has the same attributes as this renderer.
Instances of this class are Cloneable and Serializable.
36.16.6
Notes
Some notes:
• this class implements the XYItemRenderer interface and extends the AbstractXYItemRenderer
class.
• a demo application (BubbleChartDemo1.java) is included in the JFreeChart demo collection.
See Also
XYZDataset.
36.17
XYDifferenceRenderer
36.17.1
Overview
A renderer that highlights the difference between the items in two series by filling in the area
between the lines for each series. The fill color alternates between a “positive” color (used when
series 1 is greater than series 2) and a “negative” color (used when series 1 is less than series 2).
Figure 36.11 shows an example.
Figure 36.11: A chart generated with an XYDifferenceRenderer.
CHAPTER 36. PACKAGE: ORG.JFREE.CHART.RENDERER.XY
36.17.2
438
Usage
This renderer is designed for use with the XYPlot class. It expects an XYDataset that has exactly
two series, with both series having the same set of x-values. The renderer does not handle null
values.
There are two demos available: DifferenceChartDemo1.java and
DifferenceChartDemo2.java.
36.17.3
Constructors
To create a new renderer:
å public XYDifferenceRenderer();
Creates a new renderer instance that uses Color.green for the positive paint, Color.red for the
negative paint, and does not display shapes at each data point.
å public XYDifferenceRenderer(Paint positivePaint, Paint negativePaint,
boolean shapes);
Creates a new renderer instance with the given (non-null) colors. The shapes argument controls
whether or not the renderer displays shapes at each data point.
36.17.4
Accessor Methods
The following methods for accessing the attributes defined by this renderer (in addition to those
inherited from AbstractXYItemRenderer):
å public Paint getPositivePaint();
Returns the paint used to fill the area between series 1 and series 2 when the difference is
positive (that is, the y-value in series 1 is greater than the corresponding y-value in series 2).
å public void setPositivePaint(Paint paint);
Sets the paint used to fill the area between series 1 and series 2 when the difference is positive,
and sends a RendererChangeEvent to all registered listeners.
å public Paint getNegativePaint();
Returns the paint used to fill the area between series 1 and series 2 when the difference is
negative (that is, the y-value in series 1 is less than the corresponding y-value in series 2).
å public void setNegativePaint(Paint paint);
Sets the paint used to fill the area between series 1 and series 2 when the difference is negative,
and sends a RendererChangeEvent to all registered listeners.
å public boolean getShapesVisible();
Returns the flag that controls whether or not the renderer displays shapes at each data point.
å public void setShapesVisible(boolean flag);
Sets the flag that controls whether or not the renderer displays shapes at each data point, and
sends a RendererChangeEvent to all registered listeners.
å public int getPassCount();
Returns 2, the number of passes required by this renderer to draw the data items. In the first
pass, the “difference” area between the two series is filled with the specified colors. In the
second pass, the series lines and item shapes are drawn.
A flag can be set to perform rounding on the x-coordinates to improve on-screen rendering:
å public boolean getRoundXCoordinates(); [1.0.4]
Returns a flag that controls whether or not the x-coordinates are rounded to integers, which
can prevent “striping” for charts displayed on-screen. The default value is false.
å public void setRoundXCoordinates(boolean round); [1.0.4]
Sets the flag that controls whether or not the x-coordinates are rounded to integers and sends
a RendererChangeEvent to all registered listeners.
As mentioned, the methods that set an attribute will send a RendererChangeEvent to all registered
listeners. This will usually trigger a chain of events that will lead to the chart itself being repainted,
if necessary.
CHAPTER 36. PACKAGE: ORG.JFREE.CHART.RENDERER.XY
36.17.5
439
Rendering Methods
The following methods are called by the XYPlot, you shouldn’t need to call them directly:
å public XYItemRendererState initialise(Graphics2D g2,
Rectangle2D dataArea, XYPlot plot, XYDataset data, PlotRenderingInfo info);
Initialises the renderer.
å public void drawItem(Graphics2D g2, XYItemRendererState state,
Rectangle2D dataArea, PlotRenderingInfo info, XYPlot plot,
ValueAxis domainAxis, ValueAxis rangeAxis, XYDataset dataset,
int series, int item, CrosshairState crosshairState, int pass);
Draws an item—this method will be called for each item in the dataset.
36.17.6
Equals, Cloning and Serialization
This renderer overrides the equals() method:
å public boolean equals(Object obj);
Tests the renderer for equality with obj (which may be null).
This renderer can be cloned:
å public Object clone() throws CloneNotSupportedException;
Returns a clone of the renderer. In typical usage, the specified exception will not be thrown,
however it is possible to trigger the exception if some attribute of the renderer is not cloneable.
This renderer is serializable.
36.18
XYDotRenderer
36.18.1
Overview
A renderer that can be used by an XYPlot to display items from an XYDataset. The renderer fills a
rectangle (a single pixel by default) at each (x, y) point—see figure 36.12 for an example.
Figure 36.12: A chart generated with an XYDotRenderer.
This renderer offers better performance (but less flexibility) than the XYLineAndShapeRenderer class,
because it simply fills a rectangle for each data item, rather than filling and drawing a shape.
36.18.2
Constructor
The default constructor is the only constructor available:
å public XYDotRenderer();
Creates a new renderer with the default dot size of 1 unit by 1 unit.
CHAPTER 36. PACKAGE: ORG.JFREE.CHART.RENDERER.XY
36.18.3
440
Methods
Accessor methods are provided for the “dot” (actually a rectangle) width and height:
å public int getDotWidth(); [1.0.2]
Returns the current dot width. The default value is 1.
å public void setDotWidth(int w); [1.0.2]
Sets the dot width and sends a RendererChangeEvent to all registered listeners.
å public int getDotHeight(); [1.0.2]
Returns the current dot height. The default value is 1.
å public void setDotHeight(int h); [1.0.2]
Sets the dot height and sends a RendererChangeEvent to all registered listeners.
This class implements the drawItem() method defined in the XYItemRenderer interface. This method
is usually called by the plot, you don’t need to call it yourself. Many other methods are inherited
from the AbstractXYItemRenderer base class.
36.18.4
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, so that chart’s using this type of renderer
are cloneable and serializable. This renderer also implements the PublicCloneable interface.
36.18.5
Notes
Some points to note:
• tooltips, item labels and URLs are NOT generated by this renderer (these features may be
added in a future release);
• a demo application (ScatterPlotDemo4.java) is included in the JFreeChart demo collection.
36.19
XYErrorRenderer
36.19.1
Overview
A renderer that extends XYLineAndShapeRenderer to display error bars about each data item. This
renderer is designed to be used with an XYPlot to display items from an IntervalXYDataset—see
figure 36.13 for an example.
Figure 36.13: A chart generated with an XYErrorRenderer.
This class implements the XYItemRenderer interface.
CHAPTER 36. PACKAGE: ORG.JFREE.CHART.RENDERER.XY
36.19.2
Constructor
The default constructor is the only constructor available:
å public XYErrorRenderer();
Creates a new renderer. By default, error bars are drawn for both the x-values and the y-values,
using the series paint.
36.19.3
Methods
å public boolean getDrawXError();
Returns the flag that controls whether or not error bars are drawn for the x-values in the
dataset. The default value is true.
å public void setDrawXError(boolean draw);
Sets the flag that controls whether or not error bars are drawn for the x-values in the dataset,
and sends a RendererChangeEvent to all registered listeners.
å public boolean getDrawYError();
Returns the flag that controls whether or not error bars are drawn for the y-values in the
dataset. The default value is true.
å public void setDrawYError(boolean draw);
Sets the flag that controls whether or not error bars are drawn for the y-values in the dataset,
and sends a RendererChangeEvent to all registered listeners.
å public double getCapLength();
Returns the length of the caps at each end of the error bar (in Java2D units). The default
value is 4.0.
å public void setCapLength(double length);
Sets the length of the caps at each end of the error bar for each data value and sends a
RendererChangeEvent to all registered listeners. The cap length is specified in Java2D units.
å public Paint getErrorPaint();
Returns the paint used to draw the error bars, or null if the renderer should use the series
paint.
å public void setErrorPaint(Paint paint);
Sets the paint used to draw the error bars and sends a RendererChangeEvent to all registered
listeners. If you set this attribute to null, the error bars will be drawn using the series paint.
å public Range findDomainBounds(XYDataset dataset);
Returns the range required by this renderer to display all of the domain values in the dataset.
If dataset is null, this method returns null. This method is overridden to include the x-interval
when the dataset is an instance of IntervalXYDataset.
å public Range findRangeBounds(XYDataset dataset);
Returns the range required by this renderer to display all of the range values in the dataset. If
dataset is null, this method returns null. This method is overridden to include the y-interval
when the dataset is an isntance of IntervalXYDataset.
36.19.4
Equals, Cloning and Serialization
This class overrides the equals() method:
å public boolean equals(Object obj);
Returns true if obj is equal to this instance.
Instances of this class are Cloneable and Serializable.
36.19.5
Notes
This class was added to JFreeChart at version 1.0.3.
441
CHAPTER 36. PACKAGE: ORG.JFREE.CHART.RENDERER.XY
36.20
XYItemRenderer
36.20.1
Overview
442
An XY item renderer is a plug-in class that works with an XYPlot and assumes responsibility for
drawing individual data items in a chart. This interface defines the methods that every renderer
must support.
A range of different renderers are supplied in the JFreeChart distribution. Figure 36.14 shows the
class hierarchy.
AbstractXYItemRenderer
XYItemRenderer
AreaXYItemRenderer
HighLowRenderer
CandleStickRenderer
DefaultXYItemRenderer
StandardXYItemRenderer
SignalRenderer
WindItemRenderer
XYBarRenderer
ClusteredXYBarRenderer
XYBubbleRenderer
XYDifferenceRenderer
XYDotRenderer
XYStepRenderer
YIntervalRenderer
Figure 36.14: Renderer hierarchy
As well as drawing the visual representation of a data item, the renderer is also responsible for
generating tooltips (for charts displayed in a ChartPanel) and URL references for charts displayed
in an HTML image map.
A summary of the available renderers is given in Table 36.1.
Class:
Description:
HighLowRenderer
StandardXYItemRenderer
WindItemRenderer
XYAreaRenderer
XYBarRenderer
XYBubbleRenderer
XYDifferenceRenderer
XYDotRenderer
XYStepRenderer
YIntervalRenderer
High-low-open-close charts.
Line charts and scatter plots.
Wind charts.
Area charts.
Bar charts with numerical domain values.
Bubble charts.
Difference charts.
Scatter plots.
Step charts.
Interval charts.
Table 36.1: Classes that implement the XYItemRenderer interface
CHAPTER 36. PACKAGE: ORG.JFREE.CHART.RENDERER.XY
36.20.2
443
Core Methods
The initialise() method is called once at the beginning of the chart drawing process, and gives
the renderer a chance to initialise itself:
å public void initialise(Graphics2D g2, Rectangle2D dataArea, XYPlot plot,
XYDataset data, ChartRenderingInfo info);
Initialises the renderer. If possible, a renderer will pre-calculate any values that help to improve
the performance of the drawItem() method.
The drawItem() method is responsible for drawing some representation of a particular data item
within a plot:
å public void drawItem(Graphics2D g2, Rectangle2D dataArea,
ChartRenderingInfo info, XYPlot plot,
ValueAxis domainAxis, ValueAxis rangeAxis,
XYDataset data, int series, int item, CrosshairInfo info);
Draws a single data item on behalf of XYPlot.
You can set your own tooltip generator and URL generator for the renderer.
36.20.3
Annotations
You can assign one or more XYAnnotation instances to a renderer. These annotations will be drawn
relative to the axes that the renderer is mapped to. For example, see AnnotationDemo2.java in the
JFreeChart demos.
å public void addAnnotation(XYAnnotation annotation);
Adds the annotation to the foreground layer for this renderer.
å public void addAnnotation(XYAnnotation annotation, Layer layer);
Adds the annotation to the specified layer for this renderer.
å public boolean removeAnnotation(XYAnnotation annotation);
Removes an annotation from the renderer.
å public void removeAnnotations();
Removes all annotations from the renderer.
å public void drawAnnotations(Graphics2D g2, Rectangle2D dataArea,
ValueAxis domainAxis, ValueAxis rangeAxis, Layer layer,
PlotRenderingInfo info);
Draws the annotations in the specified layer.
Note that you can also add annotations directly to an XYPlot, in which case they are drawn relative
to the plot’s primary axes.
36.20.4
Notes
Some renderers require a dataset that is a specific extension of XYDataset. For example, the
HighLowRenderer requires an OHLCDataset.
See Also
AbstractXYItemRenderer, XYPlot.
36.21
XYItemRendererState
36.21.1
Overview
A state object that retains information between the successive calls to a renderer’s drawItem()
method. This class extends the RendererState class, and is used internally by JFreeChart (you
won’t normally need to use it directly, unless you are writing your own renderer class).
CHAPTER 36. PACKAGE: ORG.JFREE.CHART.RENDERER.XY
36.21.2
444
Constructor
To create a new instance:
å public XYItemRendererState(PlotRenderingInfo info);
Creates a new state instance.
36.21.3
Fields
This class defines a working Line2D instance that can be reused by a renderer to avoid creating
numerous instances that require garbage collection:
å public Line2D workingLine;
A reusable line.
See Also
RendererState
36.22
XYLineAndShapeRenderer
36.22.1
Overview
A renderer that displays items from an XYDataset by drawing a line between each (x, y) point and
overlaying a shape at each (x, y) point. One of the key features of this renderer is that it allows
you to control on a per series basis whether:
• lines are drawn between the data points;
• shapes are drawn at each data point;
• shapes are filled or not filled;
This class implements the XYItemRenderer interface, so it can be used with the XYPlot class. It
extends the AbstractXYItemRenderer base class.
36.22.2
Usage
This renderer is used for time series charts created via the createTimeSeriesChart() method in the
ChartUtilities class.
Given an arbitrary XYPlot, you can install a new instance of this renderer using the following code
(or a variation of it):
XYPlot plot = (XYPlot) chart.getPlot();
XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer();
renderer.setSeriesLinesVisible(0, true);
renderer.setSeriesShapesVisible(0, false);
renderer.setSeriesLinesVisible(1, false);
renderer.setSeriesShapesVisible(1, true);
plot.setRenderer(renderer);
Flags have been set so that items in the first series are connected with lines, while items in the
second series are displayed as individual shapes.
36.22.3
Constructor
This class has two constructors:
å public XYLineAndShapeRenderer();
Creates a new renderer. By default, the renderer will draw lines and filled shapes for all series
in the dataset.
å public XYLineAndShapeRenderer(boolean lines, boolean shapes);
Creates a new renderer, with connecting lines and shapes for each data item as requested.
CHAPTER 36. PACKAGE: ORG.JFREE.CHART.RENDERER.XY
36.22.4
445
Methods
The renderer makes two passes through the dataset, drawing the lines in the first pass, and then
drawing the shapes in the second pass. The number of passes is returned by the following method:
å public int getPassCount();
Returns 2.
To determine whether or not a line is drawn for an item (connecting the current item with the
previous item):
å public boolean getItemLineVisible(int series, int item);
Returns a flag that controls whether or not a line is drawn between the current and previous
items.
To determine whether or not lines are drawn for the items in ALL series:
å public Boolean getLinesVisible();
Returns the flag that controls whether lines are drawn for the items in ALL series. This flag
overrides all other settings, unless it is null.
å public void setLinesVisible(Boolean visible)
Sets the flag that controls whether or not lines are drawn for the items in ALL series. You can
set this flag to null if you prefer to use the “per series” flags.
å public void setLinesVisible(boolean visible)
Sets the flag that controls whether or not lines are drawn for the items in ALL series.
To determine whether or not lines are drawn for the items in one series (this requires the flag above
to be set to null:
å public boolean getSeriesLinesVisible(int series);
Returns a flag that controls whether or not lines are drawn for the items in the specified series.
å public void setSeriesLinesVisible(int series, Boolean flag);
Sets a flag that controls whether or not lines are drawn for the items in the specified series. If
this is set to null, then the default value will apply.
å public void setSeriesLinesVisible(int series, boolean visible);
Sets a flag that controls whether or not lines are drawn for the items in the specified series.
The flags are stored as Boolean objects—if the flag is null for a series, then the default value is
returned. You can set the default value using:
å public void setDefaultLinesVisible(boolean flag);
Sets the default flag that controls whether or not the renderer draws lines between the (x, y)
items in a series.
It is recommended that you set the default value as required first, and then override the setting
on a per series basis. If you have set the flag for a series, but later want to restore the default
value, note that there is a version of the setSeriesLinesVisible() method that accepts a Boolean
flag which you can set to null.
The settings that control whether or not shapes are drawn and filled follow a very similar pattern.
There are default values that can be overridden on a per series basis.
36.22.5
Dashed Lines
It is common to used a dashed stroke to draw the connecting lines between items within a series.
An issue arises when the items within a series are close together on the chart, because by default
the renderer will draw the connecting line individually for each data item (connecting the current
item to the previous item). The stroke pattern for the line is reset for each segment, which can
result in the stroke pattern not being visible for the series. A workaround is available, in which the
connecting lines for the entire series are drawn as a single line:
CHAPTER 36. PACKAGE: ORG.JFREE.CHART.RENDERER.XY
446
å public boolean getDrawSeriesLineAsPath();
Returns the flag that controls whether the connecting lines between data items are drawn as a
path, or individually. The default value is false (individual line segments).
å public void setDrawSeriesLineAsPath(boolean flag);
Sets the flag that controls whether the connecting lines between the data items are drawn as a
path, or individually. If the flag value is changed, a RendererChangeEvent is sent to all registered
listeners.
36.22.6
Legend Customisation
This renderer allows a simple customisation of the legend display where you can specify the shape
(typically a line, but any shape is permitted) that will represent each series in the legend:
å public Shape getLegendLine();
Returns the shape used to represent a series in the legend. The default value is Line2D.Double(-7.0,
0.0, 7.0, 0.0). This method never returns null.
å public void setLegendLine(Shape line);
Sets the shape used to represent a series in the legend and sends a RendererChangeEvent to
all registered listeners. This method throws an IllegalArgumentException if line is null. The
supplied shape should be centered around (0, 0) as it will be translated into position by
JFreeChart’s drawing code.
For an example, see TimeSeriesDemo7.java in the JFreeChart demo collection.
36.22.7
Notes
Some points to note:
• the renderer makes two passes through the data. In the first pass, the lines connecting the
(x, y) data points are drawn. In the second pass, the shapes at each data point are drawn. In
this way, the lines appear to be “under” the shapes, which makes for a better presentation;
• there is some overlap between this class and the StandardXYItemRenderer class;
• there is a demo (XYLineAndShapeRendererDemo1.java) included in the JFreeChart demo collection.
36.23
XYStepRenderer
36.23.1
Overview
An XY step renderer draws items from an XYDataset using “stepped” lines to connect each (x, y)
point. This renderer is designed for use with the XYPlot class.
36.23.2
Usage
A demo (XYStepRendererDemo1.java) is included in the JFreeChart demo distribution.
36.23.3
Constructors
To create a new renderer:
å public XYStepRenderer();
Creates a new default renderer.
å public XYStepRenderer(XYToolTipGenerator toolTipGenerator, XYURLGenerator urlGenerator);
Creates a new renderer with the specified tool tip generator and URL generator.
CHAPTER 36. PACKAGE: ORG.JFREE.CHART.RENDERER.XY
447
Figure 36.15: A sample chart using XYStepRenderer
36.23.4
Equals, Cloning and Serialization
This renderer inherits an equals() method from its superclass. The renderer is both Cloneable and
Serializable.
36.23.5
Notes
Some points to note:
• the “hotspot” for tooltips is a square centered on the data point (but not the corner of the
“step”). You can use the setDefaultEntityRadius() method in the AbstractXYItemRenderer
class to increase the size of the hotspot.
36.24
XYStepAreaRenderer
36.24.1
Overview
To be documented.
36.25
YIntervalRenderer
36.25.1
Overview
An XYItemRenderer that draws lines between the starting and ending y values from an IntervalXYDataset.
This renderer is designed for use with the XYPlot class.
36.25.2
Constructors
To create a new renderer:
å public YIntervalRenderer();
Creates a new renderer with default attributes.
36.25.3
Methods
The following method is called by the XYPlot class for each data item it needs to draw:
CHAPTER 36. PACKAGE: ORG.JFREE.CHART.RENDERER.XY
448
Figure 36.16: A sample chart using YIntervalRenderer
å public void drawItem(Graphics2D g2, XYItemRendererState state, Rectangle2D dataArea,
PlotRenderingInfo info, XYPlot plot, ValueAxis domainAxis, ValueAxis rangeAxis,
XYDataset dataset, int series, int item, CrosshairState crosshairState, int pass)
Draws one item from the dataset. This method is called by the XYPlot class, you won’t normally
call it yourself.
36.25.4
Notes
Some points to note:
• to customise the shapes drawn at the end points of the intervals, use the setSeriesShape(int,
Shape) method inherited from AbstractXYItemRenderer;
• a demo application (YIntervalChartDemo1.java) is included in the JFreeChart demo distribution.
Chapter 37
Package: org.jfree.chart.servlet
37.1
Overview
This package contains servlet utility classes developed for JFreeChart by Richard Atkinson. An
excellent demo for these classes can be found at:
http://homepage.ntlworld.com/richard c atkinson/jfreechart
37.2
ChartDeleter
37.2.1
Overview
A utility class that maintains a list of temporary files (chart images created by the ServletUtilities
class) and deletes them at the expiry of an HttpSession.
37.3
DisplayChart
37.3.1
Overview
A servlet that displays a chart image from the temporary directory.
37.4
ServletUtilities
37.4.1
Overview
A utility class for performing operations in a servlet environment. The methods in this class are all
static.
37.4.2
Saving Charts to Image Files
Several methods are provided to write charts to image files in the system’s temporary directory,
with automatic registration with the ChartDeleter class to remove the temporary files upon expiry
of the session. If you don’t want to use this temporary persistence mechanism, then you should use
the ChartUtilities class directly.
To save a chart in a PNG file in the temporary directory (designated by the system property
java.io.tmpdir):
å public static String saveChartAsPNG(JFreeChart chart, int width, int height,
ChartRenderingInfo info, HttpSession session) throws IOException;
Saves a chart to a PNG image file in the temporary directory and returns the filename used.
449
CHAPTER 37. PACKAGE: ORG.JFREE.CHART.SERVLET
450
The file is registered with a ChartDeleter instance that is linked to the specified session—this
means the image file will be deleted when the session expires. The info parameter should
be, if not null, a new instance of ChartRenderingInfo—it will be populated with information
about the chart as it is drawn for the PNG file (this information could be used to create an
HTML image map, for example). Note that the temporary file name prefix can be set using
the setTempFilePrefix() method.
å public static String saveChartAsPNG(JFreeChart chart, int width, int height,
HttpSession session) throws IOException;
As for the previous method, with the info argument set as null.
Equivalent methods are provided to save charts in JPEG format, but you should note that:
• JPEG is a “lossy” format that is designed for photographic images—the results for most
charts will be better if you use the PNG encoding;
• JPEG is supported by JFreeChart only when running on JRE 1.4.2 or later;
Chapter 38
Package: org.jfree.chart.title
38.1
Overview
This package contains classes that are used as chart titles and/or subtitles. The JFreeChart class
maintains one chart title (an instance of TextTitle) plus a list of subtitles (which can be any subclass
of Title).
When a chart is drawn, the title and/or subtitles will “grab” a rectangular section of the chart area
in which to draw themselves. This reduces the amount of space for plotting data, so although there
is no limit to the number of subtitles you can add to a chart, for practical reasons you need to keep
the number reasonably low.
38.2
Events
When you add a Title to a JFreeChart instance, the chart registers itself as a TitleChangeListener.
Any subsequent changes to the title will result in a TitleChangeEvent being sent to the chart. The
chart then passes the event on to all its registered ChartChangeListeners. If the chart is displayed
in a ChartPanel, the panel will receive a ChartChangeEvent and respond by repainting the chart.
38.3
CompositeTitle
38.3.1
Overview
A chart title that contains other chart titles in some arrangement. This class provides some flexibility
for displaying chart titles side-by-side or in other layouts.
38.3.2
Usage
In DualAxisDemo1.java, the following code is used to add two legends, one on the left of the chart
and the other on the right of the chart:
LegendTitle legend1 = new LegendTitle(plot.getRenderer(0));
legend1.setMargin(new RectangleInsets(2, 2, 2, 2));
legend1.setBorder(new BlockBorder());
LegendTitle legend2 = new LegendTitle(plot.getRenderer(1));
legend2.setMargin(new RectangleInsets(2, 2, 2, 2));
legend2.setBorder(new BlockBorder());
BlockContainer container = new BlockContainer(new BorderArrangement());
container.add(legend1, RectangleEdge.LEFT);
container.add(legend2, RectangleEdge.RIGHT);
container.add(new EmptyBlock(2000, 0));
CompositeTitle legends = new CompositeTitle(container);
legends.setPosition(RectangleEdge.BOTTOM);
chart.addSubtitle(legends);
451
CHAPTER 38. PACKAGE: ORG.JFREE.CHART.TITLE
38.3.3
452
Constructors
To create a new instance:
å public CompositeTitle();
Creates a new (empty) title.
å public CompositeTitle(BlockContainer container);
Creates a new title based on the specified container (which may be pre-populated with the
titles contained by this instance).
38.3.4
Methods
The following methods allow you to access the container used to hold the titles for this composite
title:
å public BlockContainer getContainer();
Returns the container that holds the titles within this composite title. You can use this to add
additional titles.
å public void setTitleContainer(BlockContainer container);
Sets the container for this composite title, replacing any existing container.
38.3.5
Layout and Drawing Methods
The JFreeChart class will call the following methods to layout and draw the titles, you won’t
normally need to call these methods yourself:
å public Size2D arrange(Graphics2D g2, RectangleConstraint constraint);
Arranges the contents of the title within the given constraint, and returns the size of the title
after the arrangement is done.
å public void draw(Graphics2D g2, Rectangle2D area);
Draws the title within the given area.
å public Object draw(Graphics2D g2, Rectangle2D area, Object params);
Draws the title within the given area. The parameters are ignored by this method, and the
returned value is always null (this may change in the future).
38.3.6
Equality, Cloning and Serialization
This class overrides equals():
å public boolean equals(Object obj)
Tests this title for equality with an arbitrary object. This method returns true if and only if:
• obj is an instance of CompositeTitle;
• the container in obj is equal to the container for this composite title.
This class is cloneable and serializable.
38.4
DateTitle
38.4.1
Overview
A chart title that displays the current date (extends TextTitle). This class would normally be used
to add the date to a chart as a subtitle.
38.4.2
Constructor
To create a new date title for the default locale:
å public DateTitle(int style);
Creates a new date title with the specified style (defined by the DateFormat class). The title
position is, by default, the lower right corner of the chart.
CHAPTER 38. PACKAGE: ORG.JFREE.CHART.TITLE
38.4.3
453
Methods
To set the date format:
å public void setDateFormat(int style, Locale locale);
Sets the date format to the given style and locale (the style is defined by constants in the
DateFormat class).
Other methods are inherited from the TextTitle class.
38.5
ImageTitle
38.5.1
Overview
A chart title that displays an image (extends Title).
38.5.2
Constructors
To create an image title:
å public ImageTitle(Image image);
Creates an image title. By default, the title is positioned at the top of the chart, and the image
is centered horizontally within the available space.
38.5.3
Methods
To change the image displayed by the image title:
å public void setImage(Image image);
Sets the image for the title and sends a TitleChangeEvent to all registered listeners.
Other methods are inherited from the Title class.
38.6
LegendGraphic
38.6.1
Overview
A graphical item, displayed as part of a legend item, that provides a visual link to a series in a
chart. The LegendTitle class uses this class in the construction of a chart’s legend.
38.6.2
Constructor
To create a new instance:
å public LegendGraphic(Shape shape, Paint fillPaint);
Creates a new graphic using the given shape and fillPaint.
38.6.3
Shape Attributes
To control whether or not the shape is visible:
å public boolean isShapeVisible();
Returns true if the shape is visible, and false otherwise.
å public void setShapeVisible(boolean visible);
Sets the visibility of the shape.
To access the shape itself:
å public Shape getShape();
Returns the shape for the legend graphic.
CHAPTER 38. PACKAGE: ORG.JFREE.CHART.TITLE
454
å public void setShape(Shape shape);
Sets the shape for the legend graphic.
To control whether or not the shape is filled:
å public boolean isShapeFilled();
Returns true if the shape is filled, and false otherwise.
å public void setShapeFilled(boolean filled);
Sets the flag that controls whether or not the shape is filled.
å public Paint getFillPaint();
Returns the paint used to fill the shape.
å public void setFillPaint(Paint paint);
Sets the paint used to fill the shape.
As of version 1.0.4, this class supports the use of a GradientPaint for the fill paint, by recording a
transformer for the gradient coordinates:1
å public GradientPaintTransformer getFillPaintTransformer(); [1.0.4]
Returns the gradient paint transformer for the fill paint.
å public void setFillPaintTransformer(GradientPaintTransformer transformer); [1.0.4]
Sets the gradient paint transformer for the fill paint.
To control whether or not the shape outline is drawn:
å public boolean isShapeOutlineVisible();
Returns true if the shape outline is displayed, and false otherwise.
å public void setShapeOutlineVisible(boolean visible);
Sets the flag that controls whether or not the shape outline is drawn.
å public Paint getOutlinePaint();
Returns the paint used to draw the shape outline.
å public void setOutlinePaint(Paint paint);
Sets the paint used to draw the shape outline.
å public Stroke getOutlineStroke();
Returns the stroke used to draw the shape outline.
å public void setOutlineStroke(Stroke stroke);
Sets the stroke used to draw the shape outline.
å public RectangleAnchor getShapeAnchor(RectangleAnchor anchor);
Returns the anchor point for the shape.
å public void setShapeAnchor(RectangleAnchor anchor);
Sets the anchor point for the shape.
å public RectangleAnchor getShapeLocation();
Returns the shape location.
å public void setShapeLocation(RectangleAnchor location);
Sets the shape location.
38.6.4
Line Attributes
To control whether or not a line is drawn for the legend graphic:
å public boolean isLineVisible();
Returns true if a line is drawn for this legend graphic, and false otherwise.
å public void setLineVisible(boolean visible);
Sets the flag that controls whether or not a line is drawn for this legend graphic.
1 Only
some renderers support this.
CHAPTER 38. PACKAGE: ORG.JFREE.CHART.TITLE
455
To control the shape of the line:
å public Shape getLine();
Returns the shape used for the line. Usually, this is a Line2D, but it is possible to use another
shape, such as a GeneralPath to draw the line.
å public void setLine(Shape line);
Sets the shape used for the line. Typically this will be a Line2D, but you can use other Shape
instances (for example, a GeneralPath). Note that, for alignment purposes, the (0, 0) coordinate
should lie approximately at the center of the line.
å public Paint getLinePaint();
Returns the Paint used to display the line.
å public void setLinePaint(Paint paint);
Sets the Paint used to display the line.
å public Stroke getLineStroke();
Returns the Stroke used to display the line.
å public void setLineStroke(Stroke stroke);
Sets the Stroke used to display the line.
38.6.5
Other Methods
The following methods are used by JFreeChart for layout and rendering:
å public Size2D arrange(Graphics2D g2, RectangleConstraint constraint);
Arranges the graphics and returns its size.
å public void draw(Graphics2D g2, Rectangle2D area);
Draws the graphic within the specified rectangle.
å public Object draw(Graphics2D g2, Rectangle2D area, Object params);
Draws the graphic within the specified rectangle.
38.6.6
Equals, Cloning and Serialization
To check this legend for equality with another object:
å public boolean equals(Object obj);
Tests this title for equality with an arbitrary object.
This class is Cloneable and Serializable.
See Also
LegendItemBlockContainer.
38.7
LegendItemBlockContainer
38.7.1
Overview
A container used internally by JFreeChart to represent one item in a legend. This is a subclass of
BlockContainer.
38.7.2
Constructors
To create a:
å public LegendItemBlockContainer(Arrangement arrangement, int dataset, int series);
Creates a new container. The dataset and series indices are used to identify the source for this
legend item.
CHAPTER 38. PACKAGE: ORG.JFREE.CHART.TITLE
38.7.3
456
Methods
å public int getDatasetIndex();
Returns the index of the dataset that this legend item represents. This is copied over to the
entity that is (optionally) created when this item is drawn.
å public int getSeriesIndex();
Returns the index of the series that this legend item represents. This is copied over to the
entity that is (optionally) created when this item is drawn.
å public Object draw(Graphics2D g2, Rectangle2D area, Object params);
Draws the container (which represents a legend item). This method is called by JFreeChart,
you won’t normally need to call it directly.
38.7.4
Notes
This class is used internally by the LegendTitle class—you won’t normally need to interact with
this class directly.
See Also
LegendGraphic, LegendTitle.
38.8
LegendTitle
38.8.1
Overview
A legend displays labels for the series in a chart, usually along with a small graphic item that
identifies the series (by color and/or style).
A legend is added to a chart using the addLegend() method in the JFreeChart class. This does the
same thing as calling addSubtitle(), since the legend is treated in the same way as any subtitle (see
Title). It is even possible to add more than one legend to a chart, and configure each to display
different subsets of the series in the chart (for example, see DualAxisDemo1.java in the JFreeChart
demo collection).
38.8.2
Usage
Adding a Legend
A chart typically has just one legend, but you can add multiple legends to your charts if you need
to.
The Legend Position
The legend position can be specified by calling the setPosition(RectangleEdge) method defined in
the Title class. Assuming that your chart has a single legend (the most common case), you can
change the location of the legend as follows:
LegendTitle legend = chart.getLegend();
legend.setPosition(RectangleEdge.BOTTOM);
legend.setHorizontalAlignment(HorizontalAlignment.RIGHT);
38.8.3
Constructors
To create a new legend:
å public LegendTitle(LegendItemSource source);
Creates a new legend that uses the specified source for legend items. Typically, the source is a
plot instance, in which case the legend will display all the series for the plot. It is possible to
display a subset of the series in the plot, by specifying a single renderer as the source.
CHAPTER 38. PACKAGE: ORG.JFREE.CHART.TITLE
457
å public LegendTitle(LegendItemSource source, Arrangement hLayout, Arrangement vLayout);
Creates a new legend that uses the specified source for legend items. The hLayout is used for
layout when the legend is at the top or bottom of the chart, and the vLayout is used when the
legend is at the left or right of the chart.
38.8.4
Legend Item Sources
The legend uses one or more sources for its legend items. A source is any class that implements the
LegendItemSource interface—this includes all plots and renderers in JFreeChart. The legend items
are fetched each time the chart is drawn (or redrawn), which allows for the fact that a dataset
change may alter the items that should be displayed in the legend.
å public LegendItemSource[] getSources();
Returns an array of the sources for the legend. The array may be empty, but is never null.
å public void setSources(LegendItemSource[] sources);
Sets the sources for the legend. A null argument will cause an exception.
By default, the legend will use the plot for the source, which results in all series being displayed
in the legend. You’ll only need to use the setSources() method if you want to display a legend (or
several legends) containing only a subset of the series in the chart.
38.8.5
Legend Appearance and Layout
The legend background is controlled with the following methods:
å public Paint getBackgroundPaint();
Returns the background paint for the legend, which may be null.
å public void setBackgroundPaint(Paint paint);
Sets the background paint for the legend, and sends a TitleChangeEvent to all registered listeners.
If this is null, the legend will be transparent.
38.8.6
Legend Item Appearance and Layout
The legend will typically contain one legend item for each series displayed in a chart. The item
has a small graphic that identifies the series in the chart, and a label that corresponds to the series
name. A number of methods are provided to customise the appearance of these legend items.
To modify the font used to display the legend item labels:
å public Font getItemFont();
Returns the font (never null) for the legend item labels. The default font is SansSerif PLAIN
10.
å public void setItemFont(Font font);
Sets the font for the legend item labels and sends a TitleChangeEvent to all registered listeners.
A null argument will cause an exception.
For example:
LegendTitle legend = chart.getLegend();
if (legend != null) {
legend.setItemFont(new Font("Dialog", Font.PLAIN, 18));
}
To set the padding around the item labels:
å public RectangleInsets getItemLabelPadding();
Returns the padding (never null) for the item labels. The default is (2.0, 2.0, 2.0, 2.0).
å public void setItemLabelPadding(RectangleInsets padding);
Sets the padding for the item labels and sends a TitleChangeEvent to all registered listeners. A
null argument will cause an exception.
CHAPTER 38. PACKAGE: ORG.JFREE.CHART.TITLE
458
To control the location of the item graphic relative to its text:
å public RectangleEdge getLegendItemGraphicEdge();
Returns the location (never null) of the item graphic relative to its text.
å public void setLegendItemGraphicEdge(RectangleEdge edge);
Sets the location of the item graphic relative to its text and sends a TitleChangeEvent to all
registered listeners. A null argument will cause an exception.
The location of the item graphic within its rectangle is determined by two attributes, the anchor
point and the location. The anchor point is a point on the item graphic that can be aligned with
the location point.
å public RectangleAnchor getLegendItemGraphicAnchor();
Returns the anchor (never null), which determines a point relative to the bounding box of the
legend item graphic that is used for alignment.
å public void setLegendItemGraphicAnchor(RectangleAnchor anchor);
Sets the anchor, which determines a point relative to the bounding box of the legend item
graphic that is used for alignment.
å public RectangleAnchor getLegendItemGraphicLocation();
Returns a location, relative to the bounding box of the legend item. The legend graphic will
be aligned relative to this point.
å public void setLegendItemGraphicLocation(RectangleAnchor anchor);
Sets the location, which defines a point relative to the bounding box of the legend item.
The padding around the legend item graphic is controlled with the following methods:
å public RectangleInsets getLegendItemGraphicPadding();
Returns the padding around the legend item graphic.
å public void setLegendItemGraphicPadding(RectangleInsets padding);
Sets the padding around the legend item graphic.
38.8.7
The Legend Wrapper
A legend wrapper provides a mechanism to add one or more items (such as a title and subtitle) to
the legend, while still allowing for the automatic layout of the legend items.
å public void setWrapper(BlockContainer wrapper);
Sets the wrapper for the legend title. One of the blocks contained by wrapper should be the
item container which you can obtain from the getItemContainer() method.
å public BlockContainer getItemContainer();
Returns the container that is populated with legend items each time the legend is drawn.
A demo application (LegendWrapperDemo1.java) that shows how to use the wrapper facility is included
in the JFreeChart demo distribution
38.8.8
Other Methods
The remaining methods in the LegendTitle class are mostly used internally:
å protected void fetchLegendItems();
Fetches the legend items from the sources defined for the legend. This will be done every time
the legend is drawn.
å protected Block createLegendItemBlock(LegendItem item);
Creates a block representing the specified item. This code is contained in a separate method
to allow the possibility of overriding it to change the appearance of individual legend items.
å public Size2D arrange(Graphics2D g2, RectangleConstraint constraint);
Arranges the contents of the legend subject to the specified constraint and returns the size of
the legend.
CHAPTER 38. PACKAGE: ORG.JFREE.CHART.TITLE
459
å public void draw(Graphics2D g2, Rectangle2D area);
Draws the legend within the specified area.
å public Object draw(Graphics2D g2, Rectangle2D area, Object params);
Draws the legend within the specified area.
38.8.9
Equals, Cloning and Serialization
To check this legend for equality with another object:
å public boolean equals(Object obj);
Tests this title for equality with an arbitrary object.
This class is Cloneable and Serializable.
See Also
LegendItemSource.
38.9
PaintScaleLegend
38.9.1
Overview
A chart title that displays a PaintScale (extends Title). This is used to illustrate the color scale
used by a renderer like the XYBlockRenderer.
This class was first introduced in JFreeChart version 1.0.4.
38.9.2
Constructors
To create a new instance:
å public PaintScaleLegend(PaintScale scale, ValueAxis axis); [1.0.4]
Creates a new legend for the given scale. The supplied axis is used to show the numerical range
for the scale.
38.9.3
Methods
The following methods are defined:
å public PaintScale getScale(); [1.0.4]
Returns the paint scale displayed in this legend.
å public void setScale(PaintScale scale); [1.0.4]
Sets the paint scale to be displayed in the legend and sends a TitleChangeEvent to all registered
listeners.
å public ValueAxis getAxis(); [1.0.4]
Returns the axis that shows the numerical range of the paint scale.
å public void setAxis(ValueAxis axis); [1.0.4]
Sets the axis that shows the numerical range of the paint scale and sends a TitleChangeEvent
to all registered listeners.
å public AxisLocation getAxisLocation(); [1.0.4]
Returns the location of the axis relative to the legend.
å public void setAxisLocation(AxisLocation location); [1.0.4]
Sets the location of the axis relative to the legend and sends a TitleChangeEvent to all registered
listeners.
å public double getAxisOffset(); [1.0.4]
Returns the offset (in Java2D units) between the color strip and the axis. The default value is
0.0.
CHAPTER 38. PACKAGE: ORG.JFREE.CHART.TITLE
460
å public void setAxisOffset(double offset); [1.0.4]
Sets the offset (in Java2D units) between the color strip and the axis, then sends a TitleChangeEvent
to all registered listeners.
å public double getStripWidth(); [1.0.4]
Returns the width of the color strip in Java2D units. The default value is 15.0.
å public void setStripWidth(double width); [1.0.4]
Sets the width of the color strip in Java2D units and sends a TitleChangeEvent to all registered
listeners.
å public boolean isStripOutlineVisible(); [1.0.4]
Returns a flag that controls whether or not an outline is drawn for the color strip. The default
value is false.
å public void setStripOutlineVisible(boolean visible); [1.0.4]
Sets a flag that controls whether or not an outline is drawn for the color strip and sends a
TitleChangeEvent to all registered listeners.
å public Paint getStripOutlinePaint(); [1.0.4]
Returns the paint used to draw the outline for the color strip (if the outline is visible).
å public void setStripOutlinePaint(Paint paint); [1.0.4]
Sets the paint used to draw the outline for the color strip (if the outline is visible) and sends a
TitleChangeEvent to all registered listeners.
å public Stroke getStripOutlineStroke(); [1.0.4]
Returns the stroke used to draw the outline for the color strip (if the outline is visible).
å public void setStripOutlineStroke(Stroke stroke); [1.0.4]
Sets the stroke used to draw the outline for the color strip (if the outline is visible) and sends
a TitleChangeEvent to all registered listeners.
å public Paint getBackgroundPaint(); [1.0.4]
Returns the background paint for the legend. The default value is null, which means the legend
background is transparent.
å public void setBackgroundPaint(Paint paint); [1.0.4]
Sets the background paint for the legend (null is permitted) and sends a TitleChangeEvent to
all registered listeners.
Other methods are inherited from the Title class.
38.9.4
Other Methods
The following methods are used by JFreeChart when drawing the legend:
å public Size2D arrange(Graphics2D g2, RectangleConstraint constraint); [1.0.4]
Performs a layout on the legend, subject to the supplied constraint.
å public void draw(Graphics2D g2, Rectangle2D area); [1.0.4]
Draws the legend within the specified area.
å public Object draw(Graphics2D g2, Rectangle2D area, Object params); [1.0.4]
Draws the legend within the specified area.
38.9.5
Equals, Cloning and Serialization
This class overrides the equals() method:
å public boolean equals(Object obj); [1.0.4]
Tests this legend for equality with an arbitrary object.
Instances of this class are Cloneable (also implements PublicCloneable) and Serializable.
CHAPTER 38. PACKAGE: ORG.JFREE.CHART.TITLE
38.9.6
461
Notes
Some points to note:
• several demos (XYBlockChartDemo1-3.java) are included in the JFreeChart demo collection.
See Also
PaintScale, XYBlockRenderer.
38.10
TextTitle
38.10.1
Overview
A chart title that displays a text string (extends Title).
38.10.2
Constructors
To create a text title for a chart:
å public TextTitle(String text);
Creates a chart title using the specified text. By default, the title will be positioned at the
top of the chart, centered horizontally. The font defaults to SansSerif, 12pt bold and the color
defaults to black.
There are other constructors that provide more control over the attributes of the TextTitle.
38.10.3
Methods
To set the title string:
å public void setText(String text);
Sets the text for the title and sends a TitleChangeEvent to all registered listeners.
To set the font for the title:
å public void setFont(Font font);
Sets the font for the title and sends a TitleChangeEvent to all registered listeners.
To set the color of the title:
å public void setPaint(Paint paint);
Sets the paint used to display the title text and sends a TitleChangeEvent to all registered
listeners.
The following method is called by the JFreeChart class to draw the chart title:
å public void draw(Graphics2D g2, Rectangle2D area);
Draws the title onto a graphics device, to occupy the specified area.
There are additional methods inherited from the Title class.
38.10.4
Notes
The title string can contain any characters from the Unicode character set. However, you need to
ensure that the Font that you use to display the title actually supports the characters you want to
display. Most fonts do not support the full range of Unicode characters, but this website has some
information about fonts that you might be able to use:
http://www.ccss.de/slovo/unifonts.htm
CHAPTER 38. PACKAGE: ORG.JFREE.CHART.TITLE
38.11
Title
38.11.1
Overview
462
The base class for all chart titles. Several concrete sub-classes have been implemented, including:
TextTitle, DateTitle, LegendTitle and ImageTitle. All titles inherit margin, border and padding
attributes from the AbstractBlock class.
38.11.2
Constructors
This is an abstract class. The following constructors are available for subclasses to use:
å protected Title();
Creates a title with default attributes.
å protected Title(RectangleEdge position,
HorizontalAlignment horizontalAlignment, VerticalAlignment verticalAlignment);
Creates a title at the specified position using the given alignments.
å protected Title(RectangleEdge position,
HorizontalAlignment horizontalAlignment, VerticalAlignment verticalAlignment,
RectangleInsets padding);
Creates a new Title with the specified position, alignment and padding. All arguments must
be non-null.
38.11.3
Methods
To control the position of the title:
å public RectangleEdge getPosition();
Returns the position of the title (never null).
å public void setPosition(RectangleEdge position);
Sets the position for the title (null not permitted). Following the change, a TitleChangeEvent
is sent to all registered listeners (including, by default, the JFreeChart object that the title
belongs to).
Within the rectangular area allocated for the title, you can specify the horizontal alignment:
å public void setHorizontalAlignment(HorizontalAlignment alignment);
Sets the horizontal alignment for the title (null not permitted). Following the change, a
TitleChangeEvent is sent to all registered listeners.
Similarly, you can specify the vertical alignment:
å public void setVerticalAlignment(VerticalAlignment alignment);
Sets the vertical alignment for the title (null not permitted). Following the change, a TitleChangeEvent
is sent to all registered listeners.
38.11.4
Drawing Titles
Subclasses should implement the following method to draw themselves within the specified area:
å public abstract void draw(Graphics2D g2, Rectangle2D area);
Draws the title. Subclasses must implement this method.
38.11.5
Event Notification
Most changes to a title will generate a TitleChangeEvent which will be sent to all registered listeners.
By default, the chart that a title belongs to will be set up to receive these change events and typically
you won’t need to register any other listeners. However, this can be done with the following methods:
å public void addChangeListener(TitleChangeListener listener);
Registers a listener to receive change events generated by the title.
CHAPTER 38. PACKAGE: ORG.JFREE.CHART.TITLE
463
å public void removeChangeListener(TitleChangeListener listener);
Deregisters a listener so that it no longer receives change events generated by the title.
Subclasses change send a change event to all registered listeners using the following method:
å protected void notifyListeners(TitleChangeEvent event);
Sends the method to all registered listeners.
There is a flag that can be used to temporarily disable change events generated by the title:
å public boolean getNotify();
Returns the flag that indicates whether or not listeners should be notified when any title
attribute is changed.
å public void setNotify(boolean flag);
Sets the flag that indicates whether or not listeners should be notified when any title attribute
is changed. When this flag is set to true, a change event is generated immediately.
38.11.6
Equals, Cloning and Serialization
To test a title for equality with an arbitrary object:
å public boolean equals(Object obj);
Returns true if this title is equal to the specified object.
All titles should be Cloneable and Serializable, otherwise charts using titles will fail to clone and
serialize.
å public Object clone() throws CloneNotSupportedException;
Returns a clone of the title.
38.11.7
Notes
Some points to note:
• the original version of this class was written by David Berry. I’ve since made a few changes
to the original version, but the idea for allowing a chart to have multiple titles came from
David.
• the JFreeChart class implements the TitleChangeListener interface, and receives notification
whenever a chart title is changed (this, in turn, triggers a ChartChangeEvent which usually
results in the chart being redrawn).
• this class implements Cloneable, which is useful when editing title properties because you can
edit a copy of the original, and then either apply the changes or cancel the changes.
Chapter 39
Package: org.jfree.chart.urls
39.1
Overview
This package contains support for URL generation for HTML image maps. URLs are generated (if
they are required) at the point that a renderer draws the visual representation of a data item. The
renderer queries a URL generator via one of the following interfaces:
• CategoryURLGenerator;
• PieURLGenerator;
• XYURLGenerator;
• XYZURLGenerator;
JFreeChart provides standard implementations for each of these interfaces. In addition, you can
easily write your own implementation and take full control of the URLs that are generated within
your image map.
39.2
CategoryURLGenerator
39.2.1
Overview
A category URL generator is used to generate a URL for each data item in a CategoryPlot. The
generator is associated with the plot’s renderer (an instance of CategoryItemRenderer) and the URLs
are used when you create an HTML image map for a chart image.
39.2.2
Methods
This method returns a URL for a specific data item:
å public String generateURL(CategoryDataset dataset, int series, int category);
Returns a URL for the specified data item. The series is the row index, and the category
is the column index for the dataset. A typical implementation of this interface will use these
arguments to construct an appropriate URL for the data item, but of course some implementations may choose to ignore these arguments. Note that JFreeChart calls this method during
chart rendering, you won’t normally call it directly yourself.
39.2.3
Notes
Some points to note:
• the StandardCategoryURLGenerator class is the only implementation of this interface provided
in the JFreeChart class library, but you can add your own implementation(s);
464
CHAPTER 39. PACKAGE: ORG.JFREE.CHART.URLS
465
• the ChartUtilities class contains code for writing HTML image maps.
39.3
CustomPieURLGenerator
39.3.1
Overview
A URL generator where the URLs for each pie section are manually specified in advance. This class
implements the PieURLGenerator interface.
39.3.2
Constructors
To create a new generator:
å public CustomPieURLGenerator();
Creates a new generator, initially with no URL entries assigned.
39.3.3
Methods
To get a URL for a pie section:
å public String generateURL(PieDataset dataset, Comparable key, int pieIndex);
Returns a URL from the generator’s lookup table.
å public int getListCount();
Returns the number of items (Map instances) in the URL list (see the addURLs() method). Each
map contains URLs for the sections in one pie chart (for regular pie charts, only one map is
required, but for use with the MultiplePiePlot class multiple maps are supported).
å public int getURLCount(int list);
Returns the number of URLs in the specified map.
å public String getURL(Comparable key, int pieItem);
Returns the URL for a section in the specified pie chart. JFreeChart will call this method
during chart rendering—you won’t normally need to call this method yourself.
å public void addURLs(Map urlMap);
Adds a collection of URLs for one pie chart.1
39.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.
å public Object clone() throws CloneNotSupportedException;
Returns a clone of the generator.
39.3.5
Notes
Some points to note:
• the API for this class could be filled out a little, particularly in the area of added and removing
maps;
1 This method has several limitations. Once you have added a map, you can’t retrieve it. In addition, you
can’t specify the index for the map (that is, which pie chart it applies to if the generator is being used with a
MultiplePiePlot).
CHAPTER 39. PACKAGE: ORG.JFREE.CHART.URLS
39.4
CustomXYURLGenerator
39.4.1
Overview
466
A URL generator that uses custom strings as the URL for each item in an XYDataset. This class
implements the XYURLGenerator interface.
39.5
PieURLGenerator
39.5.1
Overview
An interface defining the API that a caller (typically the PiePlot class) can use to obtain a URL
for a pie section. The resulting URL is used in the creation of HTML image maps.
There are two implementations of this interface provided in JFreeChart:
• StandardPieURLGenerator;
• CustomPieURLGenerator.
You are, of course, free to write your own implementation.
39.5.2
Usage
In the PiePlot class, a URL generator can be assigned to the plot using the setURLGenerator(PieURLGenerator)
method.
39.5.3
Methods
This method returns a URL for a specific data item:
å public String generateURL(PieDataset dataset, Comparable key, int pieIndex);
Returns a URL for the specified data item. The key is the key for the current section within
the dataset, and the pieIndex is used when multiple pie plots are included within one chart
(see the MultiplePiePlot class).
39.5.4
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.
• the ImageMapUtilities class contains methods to help with writing HTML image maps.
39.6
StandardCategoryURLGenerator
39.6.1
Overview
A class that generates a URL for a data item in a CategoryPlot. By default, this generator will
create URLs in the format:
index.html?series=<serieskey> &amp;category=<categorykey>
CHAPTER 39. PACKAGE: ORG.JFREE.CHART.URLS
467
...where <serieskey> and <categorykey> are replaced with values from the dataset. This class implements the CategoryURLGenerator interface.2
39.6.2
Usage
If you create a chart using the ChartFactory class, you can ask for a default URL generator to be
installed in the renderer just by setting the urls flag (a parameter for most chart creation methods)
to true.
Alternatively, you can create a new generator and register it with the renderer (replacing the existing
generator, if there is one) as follows:
CategoryPlot plot = (CategoryPlot) chart.getPlot();
CategoryItemRenderer renderer = plot.getRenderer();
CategoryURLGenerator generator = new StandardCategoryURLGenerator(
"index.html", "series", "category");
renderer.setItemURLGenerator(generator);
Set the URL generator to null if you do not require URLs to be generated.
39.6.3
Constructors
To create a new generator:
å public StandardCategoryURLGenerator();
Creates a new generator with default values:
• prefix: index.html;
• seriesParameterName: series;
• categoryParameterName: category.
å public StandardCategoryURLGenerator(String prefix);
Creates a new generator with the given prefix and default values for the other attributes:
• seriesParameterName: series;
• categoryParameterName: category.
å public StandardCategoryURLGenerator(String prefix,
String seriesParameterName, String categoryParameterName);
Creates a new generator with the specified attributes.
39.6.4
Methods
The following method is called by the renderer to generator the URL for a single data item in a
chart:
å public String generateURL(CategoryDataset dataset, int series, int category)
Returns a string that will be used as the URL for the specified data item.
39.6.5
Notes
Some points to note:
• this class is the only implementation of the CategoryURLGenerator interface that is provided
by JFreeChart, but you can easily write your own implementation.
2 Note
that the use of &amp; for the parameter separator is to ensure compliance with XHTML 1.0.
CHAPTER 39. PACKAGE: ORG.JFREE.CHART.URLS
39.7
StandardPieURLGenerator
39.7.1
Overview
468
A default URL generator for use when creating HTML image maps for pie charts. An instance of
this class can generate a URL for each section of a pie chart, in the form:
index.html?category=<sectionkey> &amp;pieIndex=<pieIndex>
...where <sectionkey> and <pieIndex> are replaced with appropriate values. This class implements
the PieURLGenerator interface, and instances of this class are immutable.
39.7.2
Usage
If you create a new pie chart using the ChartFactory class, you can request that a default URL
generator be installed simply by passing true as the value of the urls flag. Alternatively, you can
create a new instance and assign it at any time as follows:
PiePlot plot = (PiePlot) chart.getPlot();
PieURLGenerator generator = new StandardPieURLGenerator();
plot.setURLGenerator(generator);
Set the URL generator to null if you do not require URLs to be generated.
39.7.3
Constructor
To create a new generator:
å public StandardPieURLGenerator();
Creates a new generator with default values for the attributes.
å public StandardPieURLGenerator(String prefix);
Creates a new generator with the given prefix and default values for the other attributes.
å public StandardPieURLGenerator(String prefix, String categoryParameterName);
Creates a new generator with the given prefix and categoryParameterName.
å public StandardPieURLGenerator(String prefix, String categoryParameterName,
String indexParameterName);
Creates a new generator with the given attributes.
The default values for unspecified attributes are:
• prefix: index.html;
• categoryParameterName: category;
• indexParameterName: pieIndex.
39.7.4
Methods
To generate a URL for a pie section:
å public String generateURL(PieDataset dataset, Comparable key, int pieIndex);
Returns a stri