001/* ===========================================================
002 * JFreeChart : a free chart library for the Java(tm) platform
003 * ===========================================================
004 *
005 * (C) Copyright 2000-2020, by Object Refinery Limited and Contributors.
006 *
007 * Project Info:  http://www.jfree.org/jfreechart/index.html
008 *
009 * This library is free software; you can redistribute it and/or modify it
010 * under the terms of the GNU Lesser General Public License as published by
011 * the Free Software Foundation; either version 2.1 of the License, or
012 * (at your option) any later version.
013 *
014 * This library is distributed in the hope that it will be useful, but
015 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
016 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
017 * License for more details.
018 *
019 * You should have received a copy of the GNU Lesser General Public
020 * License along with this library; if not, write to the Free Software
021 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301,
022 * USA.
023 *
024 * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. 
025 * Other names may be trademarks of their respective owners.]
026 *
027 * ---------------
028 * JFreeChart.java
029 * ---------------
030 * (C) Copyright 2000-2020, by Object Refinery Limited and Contributors.
031 *
032 * Original Author:  David Gilbert (for Object Refinery Limited);
033 * Contributor(s):   Andrzej Porebski;
034 *                   David Li;
035 *                   Wolfgang Irler;
036 *                   Christian W. Zuckschwerdt;
037 *                   Klaus Rheinwald;
038 *                   Nicolas Brodu;
039 *                   Peter Kolb (patch 2603321);
040 *
041 * NOTE: The above list of contributors lists only the people that have
042 * contributed to this source file (JFreeChart.java) - for a list of ALL
043 * contributors to the project, please see the README.txt file.
044 *
045 * Changes (from 20-Jun-2001)
046 * --------------------------
047 * 20-Jun-2001 : Modifications submitted by Andrzej Porebski for legend
048 *               placement;
049 * 21-Jun-2001 : Removed JFreeChart parameter from Plot constructors (DG);
050 * 22-Jun-2001 : Multiple titles added (original code by David Berry, with
051 *               reworkings by DG);
052 * 18-Sep-2001 : Updated header (DG);
053 * 15-Oct-2001 : Moved data source classes into new package
054 *               com.jrefinery.data.* (DG);
055 * 18-Oct-2001 : New factory method for creating VerticalXYBarChart (DG);
056 * 19-Oct-2001 : Moved series paint and stroke methods to the Plot class (DG);
057 *               Moved static chart creation methods to new ChartFactory
058 *               class (DG);
059 * 22-Oct-2001 : Renamed DataSource.java --> Dataset.java etc. (DG);
060 *               Fixed bug where chart isn't registered with the dataset (DG);
061 * 07-Nov-2001 : Fixed bug where null title in constructor causes
062 *               exception (DG);
063 *               Tidied up event notification code (DG);
064 * 17-Nov-2001 : Added getLegendItemCount() method (DG);
065 * 21-Nov-2001 : Set clipping in draw method to ensure that nothing gets drawn
066 *               outside the chart area (DG);
067 * 11-Dec-2001 : Added the createBufferedImage() method, taken from the
068 *               JFreeChartServletDemo class (DG);
069 * 13-Dec-2001 : Added tooltips (DG);
070 * 16-Jan-2002 : Added handleClick() method (DG);
071 * 22-Jan-2002 : Fixed bug correlating legend labels with pie data (DG);
072 * 05-Feb-2002 : Removed redundant tooltips code (DG);
073 * 19-Feb-2002 : Added accessor methods for the backgroundImage and
074 *               backgroundImageAlpha attributes (DG);
075 * 21-Feb-2002 : Added static fields for INFO, COPYRIGHT, LICENCE, CONTRIBUTORS
076 *               and LIBRARIES.  These can be used to display information about
077 *               JFreeChart (DG);
078 * 06-Mar-2002 : Moved constants to JFreeChartConstants interface (DG);
079 * 18-Apr-2002 : PieDataset is no longer sorted (oldman);
080 * 23-Apr-2002 : Moved dataset to the Plot class (DG);
081 * 13-Jun-2002 : Added an extra draw() method (DG);
082 * 25-Jun-2002 : Implemented the Drawable interface and removed redundant
083 *               imports (DG);
084 * 26-Jun-2002 : Added another createBufferedImage() method (DG);
085 * 18-Sep-2002 : Fixed issues reported by Checkstyle (DG);
086 * 23-Sep-2002 : Added new contributor (DG);
087 * 28-Oct-2002 : Created main title and subtitle list to replace existing title
088 *               list (DG);
089 * 08-Jan-2003 : Added contributor (DG);
090 * 17-Jan-2003 : Added new constructor (DG);
091 * 22-Jan-2003 : Added ChartColor class by Cameron Riley, and background image
092 *               alignment code by Christian W. Zuckschwerdt (DG);
093 * 11-Feb-2003 : Added flag to allow suppression of chart change events, based
094 *               on a suggestion by Klaus Rheinwald (DG);
095 * 04-Mar-2003 : Added small fix for suppressed chart change events (see bug id
096 *               690865) (DG);
097 * 10-Mar-2003 : Added Benoit Xhenseval to contributors (DG);
098 * 26-Mar-2003 : Implemented Serializable (DG);
099 * 15-Jul-2003 : Added an optional border for the chart (DG);
100 * 11-Sep-2003 : Took care of listeners while cloning (NB);
101 * 16-Sep-2003 : Changed ChartRenderingInfo --> PlotRenderingInfo (DG);
102 * 22-Sep-2003 : Added nullpointer checks.
103 * 25-Sep-2003 : Added nullpointer checks too (NB).
104 * 03-Dec-2003 : Legends are now registered by this class instead of using the
105 *               old constructor way (TM);
106 * 03-Dec-2003 : Added anchorPoint to draw() method (DG);
107 * 08-Jan-2004 : Reworked title code, introducing line wrapping (DG);
108 * 09-Feb-2004 : Created additional createBufferedImage() method (DG);
109 * 05-Apr-2004 : Added new createBufferedImage() method (DG);
110 * 27-May-2004 : Moved constants from JFreeChartConstants.java back to this
111 *               class (DG);
112 * 25-Nov-2004 : Updates for changes to Title class (DG);
113 * 06-Jan-2005 : Change lookup for default background color (DG);
114 * 31-Jan-2005 : Added Don Elliott to contributors (DG);
115 * 02-Feb-2005 : Added clearSubtitles() method (DG);
116 * 03-Feb-2005 : Added Mofeed Shahin to contributors (DG);
117 * 08-Feb-2005 : Updated for RectangleConstraint changes (DG);
118 * 28-Mar-2005 : Renamed Legend --> OldLegend (DG);
119 * 12-Apr-2005 : Added methods to access legend(s) in subtitle list (DG);
120 * 13-Apr-2005 : Added removeLegend() and removeSubtitle() methods (DG);
121 * 20-Apr-2005 : Modified to collect chart entities from titles and
122 *               subtitles (DG);
123 * 26-Apr-2005 : Removed LOGGER (DG);
124 * 06-Jun-2005 : Added addLegend() method and padding attribute, fixed equals()
125 *               method (DG);
126 * 24-Nov-2005 : Removed OldLegend and related code - don't want to support
127 *               this in 1.0.0 final (DG);
128 * ------------- JFREECHART 1.0.x ---------------------------------------------
129 * 27-Jan-2006 : Updated version number (DG);
130 * 07-Dec-2006 : Added some missing credits (DG);
131 * 17-Jan-2007 : Added Darren Jung to contributor list (DG);
132 * 05-Mar-2007 : Added Sergei Ivanov to the contributor list (DG);
133 * 16-Mar-2007 : Modified initial legend border (DG);
134 * 22-Mar-2007 : New methods for text anti-aliasing (DG);
135 * 16-May-2007 : Fixed argument check in getSubtitle(), copy list in
136 *               get/setSubtitles(), and added new addSubtitle(int, Title)
137 *               method (DG);
138 * 05-Jun-2007 : Add change listener to default legend (DG);
139 * 04-Dec-2007 : In createBufferedImage() methods, make the default image type
140 *               BufferedImage.TYPE_INT_ARGB (thanks to Klaus Rheinwald) (DG);
141 * 05-Dec-2007 : Fixed bug 1749124 (not registering as listener with
142 *               TextTitle) (DG);
143 * 23-Apr-2008 : Added new contributor (Diego Pierangeli) (DG);
144 * 16-May-2008 : Added new contributor (Michael Siemer) (DG);
145 * 19-Sep-2008 : Check for title visibility (DG);
146 * 18-Dec-2008 : Use ResourceBundleWrapper - see patch 1607918 by
147 *               Jess Thrysoee (DG);
148 * 19-Mar-2009 : Added entity support - see patch 2603321 by Peter Kolb (DG);
149 * 19-May-2009 : Fixed FindBugs warnings, patch by Michal Wozniak (DG);
150 * 29-Jun-2009 : Check visibility flag in main title (DG);
151 * 02-Jul-2013 : Use ParamChecks class (DG);
152 * 21-Jun-2014 : Set default hint value for stroke control (DG);
153 *
154 */
155
156package org.jfree.chart;
157
158import java.awt.AlphaComposite;
159import java.awt.BasicStroke;
160import java.awt.Color;
161import java.awt.Composite;
162import java.awt.Font;
163import java.awt.Graphics2D;
164import java.awt.Image;
165import java.awt.Paint;
166import java.awt.RenderingHints;
167import java.awt.Shape;
168import java.awt.Stroke;
169import java.awt.geom.AffineTransform;
170import java.awt.geom.Point2D;
171import java.awt.geom.Rectangle2D;
172import java.awt.image.BufferedImage;
173import java.io.IOException;
174import java.io.ObjectInputStream;
175import java.io.ObjectOutputStream;
176import java.io.Serializable;
177import java.util.ArrayList;
178import java.util.HashMap;
179import java.util.Iterator;
180import java.util.List;
181import java.util.Map;
182import javax.swing.UIManager;
183import javax.swing.event.EventListenerList;
184
185import org.jfree.chart.block.BlockParams;
186import org.jfree.chart.block.EntityBlockResult;
187import org.jfree.chart.block.LengthConstraintType;
188import org.jfree.chart.block.RectangleConstraint;
189import org.jfree.chart.entity.EntityCollection;
190import org.jfree.chart.entity.JFreeChartEntity;
191import org.jfree.chart.event.ChartChangeEvent;
192import org.jfree.chart.event.ChartChangeListener;
193import org.jfree.chart.event.ChartProgressEvent;
194import org.jfree.chart.event.ChartProgressListener;
195import org.jfree.chart.event.PlotChangeEvent;
196import org.jfree.chart.event.PlotChangeListener;
197import org.jfree.chart.event.TitleChangeEvent;
198import org.jfree.chart.event.TitleChangeListener;
199import org.jfree.chart.plot.CategoryPlot;
200import org.jfree.chart.plot.Plot;
201import org.jfree.chart.plot.PlotRenderingInfo;
202import org.jfree.chart.plot.XYPlot;
203import org.jfree.chart.title.LegendTitle;
204import org.jfree.chart.title.TextTitle;
205import org.jfree.chart.title.Title;
206import org.jfree.chart.ui.Align;
207import org.jfree.chart.ui.Drawable;
208import org.jfree.chart.ui.HorizontalAlignment;
209import org.jfree.chart.ui.RectangleEdge;
210import org.jfree.chart.ui.RectangleInsets;
211import org.jfree.chart.ui.Size2D;
212import org.jfree.chart.ui.VerticalAlignment;
213import org.jfree.chart.util.ObjectUtils;
214import org.jfree.chart.util.PaintUtils;
215import org.jfree.chart.util.Args;
216import org.jfree.chart.util.SerialUtils;
217import org.jfree.data.Range;
218
219/**
220 * A chart class implemented using the Java 2D APIs.  The current version
221 * supports bar charts, line charts, pie charts and xy plots (including time
222 * series data).
223 * <P>
224 * JFreeChart coordinates several objects to achieve its aim of being able to
225 * draw a chart on a Java 2D graphics device: a list of {@link Title} objects
226 * (which often includes the chart's legend), a {@link Plot} and a
227 * {@link org.jfree.data.general.Dataset} (the plot in turn manages a
228 * domain axis and a range axis).
229 * <P>
230 * You should use a {@link ChartPanel} to display a chart in a GUI.
231 * <P>
232 * The {@link ChartFactory} class contains static methods for creating
233 * 'ready-made' charts.
234 *
235 * @see ChartPanel
236 * @see ChartFactory
237 * @see Title
238 * @see Plot
239 */
240public class JFreeChart implements Drawable, TitleChangeListener,
241        PlotChangeListener, Serializable, Cloneable {
242
243    /** For serialization. */
244    private static final long serialVersionUID = -3470703747817429120L;
245
246    /** The default font for titles. */
247    public static final Font DEFAULT_TITLE_FONT
248            = new Font("SansSerif", Font.BOLD, 18);
249
250    /** The default background color. */
251    public static final Paint DEFAULT_BACKGROUND_PAINT
252            = UIManager.getColor("Panel.background");
253
254    /** The default background image. */
255    public static final Image DEFAULT_BACKGROUND_IMAGE = null;
256
257    /** The default background image alignment. */
258    public static final int DEFAULT_BACKGROUND_IMAGE_ALIGNMENT = Align.FIT;
259
260    /** The default background image alpha. */
261    public static final float DEFAULT_BACKGROUND_IMAGE_ALPHA = 0.5f;
262
263    /**
264     * The key for a rendering hint that can suppress the generation of a 
265     * shadow effect when drawing the chart.  The hint value must be a 
266     * Boolean.
267     * 
268     * @since 1.0.16
269     */
270    public static final RenderingHints.Key KEY_SUPPRESS_SHADOW_GENERATION
271            = new RenderingHints.Key(0) {
272        @Override
273        public boolean isCompatibleValue(Object val) {
274            return val instanceof Boolean;
275        }
276    };
277    
278    /**
279     * Rendering hints that will be used for chart drawing.  This should never
280     * be {@code null}.
281     */
282    private transient RenderingHints renderingHints;
283
284    /** The chart id (optional, will be used by JFreeSVG export). */
285    private String id;
286    
287    /** A flag that controls whether or not the chart border is drawn. */
288    private boolean borderVisible;
289
290    /** The stroke used to draw the chart border (if visible). */
291    private transient Stroke borderStroke;
292
293    /** The paint used to draw the chart border (if visible). */
294    private transient Paint borderPaint;
295
296    /** The padding between the chart border and the chart drawing area. */
297    private RectangleInsets padding;
298
299    /** The chart title (optional). */
300    private TextTitle title;
301
302    /**
303     * The chart subtitles (zero, one or many).  This field should never be
304     * {@code null}.
305     */
306    private List subtitles;
307
308    /** Draws the visual representation of the data. */
309    private Plot plot;
310
311    /** Paint used to draw the background of the chart. */
312    private transient Paint backgroundPaint;
313
314    /** An optional background image for the chart. */
315    private transient Image backgroundImage;  // todo: not serialized yet
316
317    /** The alignment for the background image. */
318    private int backgroundImageAlignment = Align.FIT;
319
320    /** The alpha transparency for the background image. */
321    private float backgroundImageAlpha = 0.5f;
322
323    /** Storage for registered change listeners. */
324    private transient EventListenerList changeListeners;
325
326    /** Storage for registered progress listeners. */
327    private transient EventListenerList progressListeners;
328
329    /**
330     * A flag that can be used to enable/disable notification of chart change
331     * events.
332     */
333    private boolean notify;
334
335    /** 
336     * A flag that controls whether or not rendering hints that identify
337     * chart element should be added during rendering.  This defaults to false
338     * and it should only be enabled if the output target will use the hints.
339     * JFreeSVG is one output target that supports these hints.
340     */
341    private boolean elementHinting;
342    
343    /**
344     * Creates a new chart based on the supplied plot.  The chart will have
345     * a legend added automatically, but no title (although you can easily add
346     * one later).
347     * <br><br>
348     * Note that the  {@link ChartFactory} class contains a range
349     * of static methods that will return ready-made charts, and often this
350     * is a more convenient way to create charts than using this constructor.
351     *
352     * @param plot  the plot ({@code null} not permitted).
353     */
354    public JFreeChart(Plot plot) {
355        this(null, null, plot, true);
356    }
357
358    /**
359     * Creates a new chart with the given title and plot.  A default font
360     * ({@link #DEFAULT_TITLE_FONT}) is used for the title, and the chart will
361     * have a legend added automatically.
362     * <br><br>
363     * Note that the {@link ChartFactory} class contains a range
364     * of static methods that will return ready-made charts, and often this
365     * is a more convenient way to create charts than using this constructor.
366     *
367     * @param title  the chart title ({@code null} permitted).
368     * @param plot  the plot ({@code null} not permitted).
369     */
370    public JFreeChart(String title, Plot plot) {
371        this(title, JFreeChart.DEFAULT_TITLE_FONT, plot, true);
372    }
373
374    /**
375     * Creates a new chart with the given title and plot.  The
376     * {@code createLegend} argument specifies whether or not a legend
377     * should be added to the chart.
378     * <br><br>
379     * Note that the  {@link ChartFactory} class contains a range
380     * of static methods that will return ready-made charts, and often this
381     * is a more convenient way to create charts than using this constructor.
382     *
383     * @param title  the chart title ({@code null} permitted).
384     * @param titleFont  the font for displaying the chart title
385     *                   ({@code null} permitted).
386     * @param plot  controller of the visual representation of the data
387     *              ({@code null} not permitted).
388     * @param createLegend  a flag indicating whether or not a legend should
389     *                      be created for the chart.
390     */
391    public JFreeChart(String title, Font titleFont, Plot plot,
392                      boolean createLegend) {
393
394        Args.nullNotPermitted(plot, "plot");
395        this.id = null;
396        plot.setChart(this);
397        
398        // create storage for listeners...
399        this.progressListeners = new EventListenerList();
400        this.changeListeners = new EventListenerList();
401        this.notify = true;  // default is to notify listeners when the
402                             // chart changes
403
404        this.renderingHints = new RenderingHints(
405                RenderingHints.KEY_ANTIALIASING,
406                RenderingHints.VALUE_ANTIALIAS_ON);
407        // added the following hint because of 
408        // http://stackoverflow.com/questions/7785082/
409        this.renderingHints.put(RenderingHints.KEY_STROKE_CONTROL,
410                RenderingHints.VALUE_STROKE_PURE);
411        
412        this.borderVisible = false;
413        this.borderStroke = new BasicStroke(1.0f);
414        this.borderPaint = Color.BLACK;
415
416        this.padding = RectangleInsets.ZERO_INSETS;
417
418        this.plot = plot;
419        plot.addChangeListener(this);
420
421        this.subtitles = new ArrayList();
422
423        // create a legend, if requested...
424        if (createLegend) {
425            LegendTitle legend = new LegendTitle(this.plot);
426            legend.setMargin(new RectangleInsets(1.0, 1.0, 1.0, 1.0));
427            legend.setBackgroundPaint(Color.WHITE);
428            legend.setPosition(RectangleEdge.BOTTOM);
429            this.subtitles.add(legend);
430            legend.addChangeListener(this);
431        }
432
433        // add the chart title, if one has been specified...
434        if (title != null) {
435            if (titleFont == null) {
436                titleFont = DEFAULT_TITLE_FONT;
437            }
438            this.title = new TextTitle(title, titleFont);
439            this.title.addChangeListener(this);
440        }
441
442        this.backgroundPaint = DEFAULT_BACKGROUND_PAINT;
443
444        this.backgroundImage = DEFAULT_BACKGROUND_IMAGE;
445        this.backgroundImageAlignment = DEFAULT_BACKGROUND_IMAGE_ALIGNMENT;
446        this.backgroundImageAlpha = DEFAULT_BACKGROUND_IMAGE_ALPHA;
447    }
448
449    /**
450     * Returns the ID for the chart.
451     * 
452     * @return The ID for the chart (possibly {@code null}).
453     * 
454     * @since 1.0.20
455     */
456    public String getID() {
457        return this.id;
458    }
459    
460    /**
461     * Sets the ID for the chart.
462     * 
463     * @param id  the id ({@code null} permitted). 
464     * 
465     * @since 1.0.20
466     */
467    public void setID(String id) {
468        this.id = id;
469    }
470    
471    /**
472     * Returns the flag that controls whether or not rendering hints 
473     * ({@link ChartHints#KEY_BEGIN_ELEMENT} and 
474     * {@link ChartHints#KEY_END_ELEMENT}) that identify chart elements are 
475     * added during rendering.  The default value is {@code false}.
476     * 
477     * @return A boolean.
478     * 
479     * @see #setElementHinting(boolean) 
480     * @since 1.0.20
481     */
482    public boolean getElementHinting() {
483        return this.elementHinting;
484    }
485    
486    /**
487     * Sets the flag that controls whether or not rendering hints 
488     * ({@link ChartHints#KEY_BEGIN_ELEMENT} and 
489     * {@link ChartHints#KEY_END_ELEMENT}) that identify chart elements are 
490     * added during rendering.
491     * 
492     * @param hinting  the new flag value.
493     * 
494     * @see #getElementHinting() 
495     * @since 1.0.20
496     */
497    public void setElementHinting(boolean hinting) {
498        this.elementHinting = hinting;
499    }
500    
501    /**
502     * Returns the collection of rendering hints for the chart.
503     *
504     * @return The rendering hints for the chart (never {@code null}).
505     *
506     * @see #setRenderingHints(RenderingHints)
507     */
508    public RenderingHints getRenderingHints() {
509        return this.renderingHints;
510    }
511
512    /**
513     * Sets the rendering hints for the chart.  These will be added (using the
514     * {@code Graphics2D.addRenderingHints()} method) near the start of the
515     * {@code JFreeChart.draw()} method.
516     *
517     * @param renderingHints  the rendering hints ({@code null} not permitted).
518     *
519     * @see #getRenderingHints()
520     */
521    public void setRenderingHints(RenderingHints renderingHints) {
522        Args.nullNotPermitted(renderingHints, "renderingHints");
523        this.renderingHints = renderingHints;
524        fireChartChanged();
525    }
526
527    /**
528     * Returns a flag that controls whether or not a border is drawn around the
529     * outside of the chart.
530     *
531     * @return A boolean.
532     *
533     * @see #setBorderVisible(boolean)
534     */
535    public boolean isBorderVisible() {
536        return this.borderVisible;
537    }
538
539    /**
540     * Sets a flag that controls whether or not a border is drawn around the
541     * outside of the chart.
542     *
543     * @param visible  the flag.
544     *
545     * @see #isBorderVisible()
546     */
547    public void setBorderVisible(boolean visible) {
548        this.borderVisible = visible;
549        fireChartChanged();
550    }
551
552    /**
553     * Returns the stroke used to draw the chart border (if visible).
554     *
555     * @return The border stroke.
556     *
557     * @see #setBorderStroke(Stroke)
558     */
559    public Stroke getBorderStroke() {
560        return this.borderStroke;
561    }
562
563    /**
564     * Sets the stroke used to draw the chart border (if visible).
565     *
566     * @param stroke  the stroke.
567     *
568     * @see #getBorderStroke()
569     */
570    public void setBorderStroke(Stroke stroke) {
571        this.borderStroke = stroke;
572        fireChartChanged();
573    }
574
575    /**
576     * Returns the paint used to draw the chart border (if visible).
577     *
578     * @return The border paint.
579     *
580     * @see #setBorderPaint(Paint)
581     */
582    public Paint getBorderPaint() {
583        return this.borderPaint;
584    }
585
586    /**
587     * Sets the paint used to draw the chart border (if visible).
588     *
589     * @param paint  the paint.
590     *
591     * @see #getBorderPaint()
592     */
593    public void setBorderPaint(Paint paint) {
594        this.borderPaint = paint;
595        fireChartChanged();
596    }
597
598    /**
599     * Returns the padding between the chart border and the chart drawing area.
600     *
601     * @return The padding (never {@code null}).
602     *
603     * @see #setPadding(RectangleInsets)
604     */
605    public RectangleInsets getPadding() {
606        return this.padding;
607    }
608
609    /**
610     * Sets the padding between the chart border and the chart drawing area,
611     * and sends a {@link ChartChangeEvent} to all registered listeners.
612     *
613     * @param padding  the padding ({@code null} not permitted).
614     *
615     * @see #getPadding()
616     */
617    public void setPadding(RectangleInsets padding) {
618        Args.nullNotPermitted(padding, "padding");
619        this.padding = padding;
620        notifyListeners(new ChartChangeEvent(this));
621    }
622
623    /**
624     * Returns the main chart title.  Very often a chart will have just one
625     * title, so we make this case simple by providing accessor methods for
626     * the main title.  However, multiple titles are supported - see the
627     * {@link #addSubtitle(Title)} method.
628     *
629     * @return The chart title (possibly {@code null}).
630     *
631     * @see #setTitle(TextTitle)
632     */
633    public TextTitle getTitle() {
634        return this.title;
635    }
636
637    /**
638     * Sets the main title for the chart and sends a {@link ChartChangeEvent}
639     * to all registered listeners.  If you do not want a title for the
640     * chart, set it to {@code null}.  If you want more than one title on
641     * a chart, use the {@link #addSubtitle(Title)} method.
642     *
643     * @param title  the title ({@code null} permitted).
644     *
645     * @see #getTitle()
646     */
647    public void setTitle(TextTitle title) {
648        if (this.title != null) {
649            this.title.removeChangeListener(this);
650        }
651        this.title = title;
652        if (title != null) {
653            title.addChangeListener(this);
654        }
655        fireChartChanged();
656    }
657
658    /**
659     * Sets the chart title and sends a {@link ChartChangeEvent} to all
660     * registered listeners.  This is a convenience method that ends up calling
661     * the {@link #setTitle(TextTitle)} method.  If there is an existing title,
662     * its text is updated, otherwise a new title using the default font is
663     * added to the chart.  If {@code text} is {@code null} the chart
664     * title is set to {@code null}.
665     *
666     * @param text  the title text ({@code null} permitted).
667     *
668     * @see #getTitle()
669     */
670    public void setTitle(String text) {
671        if (text != null) {
672            if (this.title == null) {
673                setTitle(new TextTitle(text, JFreeChart.DEFAULT_TITLE_FONT));
674            } else {
675                this.title.setText(text);
676            }
677        }
678        else {
679            setTitle((TextTitle) null);
680        }
681    }
682
683    /**
684     * Adds a legend to the plot and sends a {@link ChartChangeEvent} to all
685     * registered listeners.
686     *
687     * @param legend  the legend ({@code null} not permitted).
688     *
689     * @see #removeLegend()
690     */
691    public void addLegend(LegendTitle legend) {
692        addSubtitle(legend);
693    }
694
695    /**
696     * Returns the legend for the chart, if there is one.  Note that a chart
697     * can have more than one legend - this method returns the first.
698     *
699     * @return The legend (possibly {@code null}).
700     *
701     * @see #getLegend(int)
702     */
703    public LegendTitle getLegend() {
704        return getLegend(0);
705    }
706
707    /**
708     * Returns the nth legend for a chart, or {@code null}.
709     *
710     * @param index  the legend index (zero-based).
711     *
712     * @return The legend (possibly {@code null}).
713     *
714     * @see #addLegend(LegendTitle)
715     */
716    public LegendTitle getLegend(int index) {
717        int seen = 0;
718        Iterator iterator = this.subtitles.iterator();
719        while (iterator.hasNext()) {
720            Title subtitle = (Title) iterator.next();
721            if (subtitle instanceof LegendTitle) {
722                if (seen == index) {
723                    return (LegendTitle) subtitle;
724                }
725                else {
726                    seen++;
727                }
728            }
729        }
730        return null;
731    }
732
733    /**
734     * Removes the first legend in the chart and sends a
735     * {@link ChartChangeEvent} to all registered listeners.
736     *
737     * @see #getLegend()
738     */
739    public void removeLegend() {
740        removeSubtitle(getLegend());
741    }
742
743    /**
744     * Returns the list of subtitles for the chart.
745     *
746     * @return The subtitle list (possibly empty, but never {@code null}).
747     *
748     * @see #setSubtitles(List)
749     */
750    public List getSubtitles() {
751        return new ArrayList(this.subtitles);
752    }
753
754    /**
755     * Sets the title list for the chart (completely replaces any existing
756     * titles) and sends a {@link ChartChangeEvent} to all registered
757     * listeners.
758     *
759     * @param subtitles  the new list of subtitles ({@code null} not
760     *                   permitted).
761     *
762     * @see #getSubtitles()
763     */
764    public void setSubtitles(List subtitles) {
765        if (subtitles == null) {
766            throw new NullPointerException("Null 'subtitles' argument.");
767        }
768        setNotify(false);
769        clearSubtitles();
770        Iterator iterator = subtitles.iterator();
771        while (iterator.hasNext()) {
772            Title t = (Title) iterator.next();
773            if (t != null) {
774                addSubtitle(t);
775            }
776        }
777        setNotify(true);  // this fires a ChartChangeEvent
778    }
779
780    /**
781     * Returns the number of titles for the chart.
782     *
783     * @return The number of titles for the chart.
784     *
785     * @see #getSubtitles()
786     */
787    public int getSubtitleCount() {
788        return this.subtitles.size();
789    }
790
791    /**
792     * Returns a chart subtitle.
793     *
794     * @param index  the index of the chart subtitle (zero based).
795     *
796     * @return A chart subtitle.
797     *
798     * @see #addSubtitle(Title)
799     */
800    public Title getSubtitle(int index) {
801        if ((index < 0) || (index >= getSubtitleCount())) {
802            throw new IllegalArgumentException("Index out of range.");
803        }
804        return (Title) this.subtitles.get(index);
805    }
806
807    /**
808     * Adds a chart subtitle, and notifies registered listeners that the chart
809     * has been modified.
810     *
811     * @param subtitle  the subtitle ({@code null} not permitted).
812     *
813     * @see #getSubtitle(int)
814     */
815    public void addSubtitle(Title subtitle) {
816        Args.nullNotPermitted(subtitle, "subtitle");
817        this.subtitles.add(subtitle);
818        subtitle.addChangeListener(this);
819        fireChartChanged();
820    }
821
822    /**
823     * Adds a subtitle at a particular position in the subtitle list, and sends
824     * a {@link ChartChangeEvent} to all registered listeners.
825     *
826     * @param index  the index (in the range 0 to {@link #getSubtitleCount()}).
827     * @param subtitle  the subtitle to add ({@code null} not permitted).
828     *
829     * @since 1.0.6
830     */
831    public void addSubtitle(int index, Title subtitle) {
832        if (index < 0 || index > getSubtitleCount()) {
833            throw new IllegalArgumentException(
834                    "The 'index' argument is out of range.");
835        }
836        Args.nullNotPermitted(subtitle, "subtitle");
837        this.subtitles.add(index, subtitle);
838        subtitle.addChangeListener(this);
839        fireChartChanged();
840    }
841
842    /**
843     * Clears all subtitles from the chart and sends a {@link ChartChangeEvent}
844     * to all registered listeners.
845     *
846     * @see #addSubtitle(Title)
847     */
848    public void clearSubtitles() {
849        Iterator iterator = this.subtitles.iterator();
850        while (iterator.hasNext()) {
851            Title t = (Title) iterator.next();
852            t.removeChangeListener(this);
853        }
854        this.subtitles.clear();
855        fireChartChanged();
856    }
857
858    /**
859     * Removes the specified subtitle and sends a {@link ChartChangeEvent} to
860     * all registered listeners.
861     *
862     * @param title  the title.
863     *
864     * @see #addSubtitle(Title)
865     */
866    public void removeSubtitle(Title title) {
867        this.subtitles.remove(title);
868        fireChartChanged();
869    }
870
871    /**
872     * Returns the plot for the chart.  The plot is a class responsible for
873     * coordinating the visual representation of the data, including the axes
874     * (if any).
875     *
876     * @return The plot.
877     */
878    public Plot getPlot() {
879        return this.plot;
880    }
881
882    /**
883     * Returns the plot cast as a {@link CategoryPlot}.
884     * <p>
885     * NOTE: if the plot is not an instance of {@link CategoryPlot}, then a
886     * {@code ClassCastException} is thrown.
887     *
888     * @return The plot.
889     *
890     * @see #getPlot()
891     */
892    public CategoryPlot getCategoryPlot() {
893        return (CategoryPlot) this.plot;
894    }
895
896    /**
897     * Returns the plot cast as an {@link XYPlot}.
898     * <p>
899     * NOTE: if the plot is not an instance of {@link XYPlot}, then a
900     * {@code ClassCastException} is thrown.
901     *
902     * @return The plot.
903     *
904     * @see #getPlot()
905     */
906    public XYPlot getXYPlot() {
907        return (XYPlot) this.plot;
908    }
909
910    /**
911     * Returns a flag that indicates whether or not anti-aliasing is used when
912     * the chart is drawn.
913     *
914     * @return The flag.
915     *
916     * @see #setAntiAlias(boolean)
917     */
918    public boolean getAntiAlias() {
919        Object val = this.renderingHints.get(RenderingHints.KEY_ANTIALIASING);
920        return RenderingHints.VALUE_ANTIALIAS_ON.equals(val);
921    }
922
923    /**
924     * Sets a flag that indicates whether or not anti-aliasing is used when the
925     * chart is drawn.
926     * <P>
927     * Anti-aliasing usually improves the appearance of charts, but is slower.
928     *
929     * @param flag  the new value of the flag.
930     *
931     * @see #getAntiAlias()
932     */
933    public void setAntiAlias(boolean flag) {
934        Object hint = flag ? RenderingHints.VALUE_ANTIALIAS_ON 
935                : RenderingHints.VALUE_ANTIALIAS_OFF;
936        this.renderingHints.put(RenderingHints.KEY_ANTIALIASING, hint);
937        fireChartChanged();
938    }
939
940    /**
941     * Returns the current value stored in the rendering hints table for
942     * {@link RenderingHints#KEY_TEXT_ANTIALIASING}.
943     *
944     * @return The hint value (possibly {@code null}).
945     *
946     * @since 1.0.5
947     *
948     * @see #setTextAntiAlias(Object)
949     */
950    public Object getTextAntiAlias() {
951        return this.renderingHints.get(RenderingHints.KEY_TEXT_ANTIALIASING);
952    }
953
954    /**
955     * Sets the value in the rendering hints table for
956     * {@link RenderingHints#KEY_TEXT_ANTIALIASING} to either
957     * {@link RenderingHints#VALUE_TEXT_ANTIALIAS_ON} or
958     * {@link RenderingHints#VALUE_TEXT_ANTIALIAS_OFF}, then sends a
959     * {@link ChartChangeEvent} to all registered listeners.
960     *
961     * @param flag  the new value of the flag.
962     *
963     * @since 1.0.5
964     *
965     * @see #getTextAntiAlias()
966     * @see #setTextAntiAlias(Object)
967     */
968    public void setTextAntiAlias(boolean flag) {
969        if (flag) {
970            setTextAntiAlias(RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
971        }
972        else {
973            setTextAntiAlias(RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);
974        }
975    }
976
977    /**
978     * Sets the value in the rendering hints table for
979     * {@link RenderingHints#KEY_TEXT_ANTIALIASING} and sends a
980     * {@link ChartChangeEvent} to all registered listeners.
981     *
982     * @param val  the new value ({@code null} permitted).
983     *
984     * @since 1.0.5
985     *
986     * @see #getTextAntiAlias()
987     * @see #setTextAntiAlias(boolean)
988     */
989    public void setTextAntiAlias(Object val) {
990        this.renderingHints.put(RenderingHints.KEY_TEXT_ANTIALIASING, val);
991        notifyListeners(new ChartChangeEvent(this));
992    }
993
994    /**
995     * Returns the paint used for the chart background.
996     *
997     * @return The paint (possibly {@code null}).
998     *
999     * @see #setBackgroundPaint(Paint)
1000     */
1001    public Paint getBackgroundPaint() {
1002        return this.backgroundPaint;
1003    }
1004
1005    /**
1006     * Sets the paint used to fill the chart background and sends a
1007     * {@link ChartChangeEvent} to all registered listeners.
1008     *
1009     * @param paint  the paint ({@code null} permitted).
1010     *
1011     * @see #getBackgroundPaint()
1012     */
1013    public void setBackgroundPaint(Paint paint) {
1014
1015        if (this.backgroundPaint != null) {
1016            if (!this.backgroundPaint.equals(paint)) {
1017                this.backgroundPaint = paint;
1018                fireChartChanged();
1019            }
1020        }
1021        else {
1022            if (paint != null) {
1023                this.backgroundPaint = paint;
1024                fireChartChanged();
1025            }
1026        }
1027
1028    }
1029
1030    /**
1031     * Returns the background image for the chart, or {@code null} if
1032     * there is no image.
1033     *
1034     * @return The image (possibly {@code null}).
1035     *
1036     * @see #setBackgroundImage(Image)
1037     */
1038    public Image getBackgroundImage() {
1039        return this.backgroundImage;
1040    }
1041
1042    /**
1043     * Sets the background image for the chart and sends a
1044     * {@link ChartChangeEvent} to all registered listeners.
1045     *
1046     * @param image  the image ({@code null} permitted).
1047     *
1048     * @see #getBackgroundImage()
1049     */
1050    public void setBackgroundImage(Image image) {
1051
1052        if (this.backgroundImage != null) {
1053            if (!this.backgroundImage.equals(image)) {
1054                this.backgroundImage = image;
1055                fireChartChanged();
1056            }
1057        }
1058        else {
1059            if (image != null) {
1060                this.backgroundImage = image;
1061                fireChartChanged();
1062            }
1063        }
1064
1065    }
1066
1067    /**
1068     * Returns the background image alignment. Alignment constants are defined
1069     * in the {@link Align} class.
1070     *
1071     * @return The alignment.
1072     *
1073     * @see #setBackgroundImageAlignment(int)
1074     */
1075    public int getBackgroundImageAlignment() {
1076        return this.backgroundImageAlignment;
1077    }
1078
1079    /**
1080     * Sets the background alignment.  Alignment options are defined by the
1081     * {@link org.jfree.chart.ui.Align} class.
1082     *
1083     * @param alignment  the alignment.
1084     *
1085     * @see #getBackgroundImageAlignment()
1086     */
1087    public void setBackgroundImageAlignment(int alignment) {
1088        if (this.backgroundImageAlignment != alignment) {
1089            this.backgroundImageAlignment = alignment;
1090            fireChartChanged();
1091        }
1092    }
1093
1094    /**
1095     * Returns the alpha-transparency for the chart's background image.
1096     *
1097     * @return The alpha-transparency.
1098     *
1099     * @see #setBackgroundImageAlpha(float)
1100     */
1101    public float getBackgroundImageAlpha() {
1102        return this.backgroundImageAlpha;
1103    }
1104
1105    /**
1106     * Sets the alpha-transparency for the chart's background image.
1107     * Registered listeners are notified that the chart has been changed.
1108     *
1109     * @param alpha  the alpha value.
1110     *
1111     * @see #getBackgroundImageAlpha()
1112     */
1113    public void setBackgroundImageAlpha(float alpha) {
1114        if (this.backgroundImageAlpha != alpha) {
1115            this.backgroundImageAlpha = alpha;
1116            fireChartChanged();
1117        }
1118    }
1119
1120    /**
1121     * Returns a flag that controls whether or not change events are sent to
1122     * registered listeners.
1123     *
1124     * @return A boolean.
1125     *
1126     * @see #setNotify(boolean)
1127     */
1128    public boolean isNotify() {
1129        return this.notify;
1130    }
1131
1132    /**
1133     * Sets a flag that controls whether or not listeners receive
1134     * {@link ChartChangeEvent} notifications.
1135     *
1136     * @param notify  a boolean.
1137     *
1138     * @see #isNotify()
1139     */
1140    public void setNotify(boolean notify) {
1141        this.notify = notify;
1142        // if the flag is being set to true, there may be queued up changes...
1143        if (notify) {
1144            notifyListeners(new ChartChangeEvent(this));
1145        }
1146    }
1147
1148    /**
1149     * Draws the chart on a Java 2D graphics device (such as the screen or a
1150     * printer).
1151     * <P>
1152     * This method is the focus of the entire JFreeChart library.
1153     *
1154     * @param g2  the graphics device.
1155     * @param area  the area within which the chart should be drawn.
1156     */
1157    @Override
1158    public void draw(Graphics2D g2, Rectangle2D area) {
1159        draw(g2, area, null, null);
1160    }
1161
1162    /**
1163     * Draws the chart on a Java 2D graphics device (such as the screen or a
1164     * printer).  This method is the focus of the entire JFreeChart library.
1165     *
1166     * @param g2  the graphics device.
1167     * @param area  the area within which the chart should be drawn.
1168     * @param info  records info about the drawing (null means collect no info).
1169     */
1170    public void draw(Graphics2D g2, Rectangle2D area, ChartRenderingInfo info) {
1171        draw(g2, area, null, info);
1172    }
1173
1174    /**
1175     * Draws the chart on a Java 2D graphics device (such as the screen or a
1176     * printer).
1177     * <P>
1178     * This method is the focus of the entire JFreeChart library.
1179     *
1180     * @param g2  the graphics device.
1181     * @param chartArea  the area within which the chart should be drawn.
1182     * @param anchor  the anchor point (in Java2D space) for the chart
1183     *                ({@code null} permitted).
1184     * @param info  records info about the drawing (null means collect no info).
1185     */
1186    public void draw(Graphics2D g2, Rectangle2D chartArea, Point2D anchor,
1187             ChartRenderingInfo info) {
1188
1189        notifyListeners(new ChartProgressEvent(this, this,
1190                ChartProgressEvent.DRAWING_STARTED, 0));
1191        
1192        if (this.elementHinting) {
1193            Map m = new HashMap<String, String>();
1194            if (this.id != null) {
1195                m.put("id", this.id);
1196            }
1197            m.put("ref", "JFREECHART_TOP_LEVEL");            
1198            g2.setRenderingHint(ChartHints.KEY_BEGIN_ELEMENT, m);            
1199        }
1200        
1201        EntityCollection entities = null;
1202        // record the chart area, if info is requested...
1203        if (info != null) {
1204            info.clear();
1205            info.setChartArea(chartArea);
1206            entities = info.getEntityCollection();
1207        }
1208        if (entities != null) {
1209            entities.add(new JFreeChartEntity((Rectangle2D) chartArea.clone(),
1210                    this));
1211        }
1212
1213        // ensure no drawing occurs outside chart area...
1214        Shape savedClip = g2.getClip();
1215        g2.clip(chartArea);
1216
1217        g2.addRenderingHints(this.renderingHints);
1218
1219        // draw the chart background...
1220        if (this.backgroundPaint != null) {
1221            g2.setPaint(this.backgroundPaint);
1222            g2.fill(chartArea);
1223        }
1224
1225        if (this.backgroundImage != null) {
1226            Composite originalComposite = g2.getComposite();
1227            g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,
1228                    this.backgroundImageAlpha));
1229            Rectangle2D dest = new Rectangle2D.Double(0.0, 0.0,
1230                    this.backgroundImage.getWidth(null),
1231                    this.backgroundImage.getHeight(null));
1232            Align.align(dest, chartArea, this.backgroundImageAlignment);
1233            g2.drawImage(this.backgroundImage, (int) dest.getX(),
1234                    (int) dest.getY(), (int) dest.getWidth(),
1235                    (int) dest.getHeight(), null);
1236            g2.setComposite(originalComposite);
1237        }
1238
1239        if (isBorderVisible()) {
1240            Paint paint = getBorderPaint();
1241            Stroke stroke = getBorderStroke();
1242            if (paint != null && stroke != null) {
1243                Rectangle2D borderArea = new Rectangle2D.Double(
1244                        chartArea.getX(), chartArea.getY(),
1245                        chartArea.getWidth() - 1.0, chartArea.getHeight()
1246                        - 1.0);
1247                g2.setPaint(paint);
1248                g2.setStroke(stroke);
1249                g2.draw(borderArea);
1250            }
1251        }
1252
1253        // draw the title and subtitles...
1254        Rectangle2D nonTitleArea = new Rectangle2D.Double();
1255        nonTitleArea.setRect(chartArea);
1256        this.padding.trim(nonTitleArea);
1257
1258        if (this.title != null && this.title.isVisible()) {
1259            EntityCollection e = drawTitle(this.title, g2, nonTitleArea,
1260                    (entities != null));
1261            if (e != null && entities != null) {
1262                entities.addAll(e);
1263            }
1264        }
1265
1266        Iterator iterator = this.subtitles.iterator();
1267        while (iterator.hasNext()) {
1268            Title currentTitle = (Title) iterator.next();
1269            if (currentTitle.isVisible()) {
1270                EntityCollection e = drawTitle(currentTitle, g2, nonTitleArea,
1271                        (entities != null));
1272                if (e != null && entities != null) {
1273                    entities.addAll(e);
1274                }
1275            }
1276        }
1277
1278        Rectangle2D plotArea = nonTitleArea;
1279
1280        // draw the plot (axes and data visualisation)
1281        PlotRenderingInfo plotInfo = null;
1282        if (info != null) {
1283            plotInfo = info.getPlotInfo();
1284        }
1285        this.plot.draw(g2, plotArea, anchor, null, plotInfo);
1286        g2.setClip(savedClip);
1287        if (this.elementHinting) {         
1288            g2.setRenderingHint(ChartHints.KEY_END_ELEMENT, Boolean.TRUE);            
1289        }
1290
1291        notifyListeners(new ChartProgressEvent(this, this,
1292                ChartProgressEvent.DRAWING_FINISHED, 100));
1293    }
1294
1295    /**
1296     * Creates a rectangle that is aligned to the frame.
1297     *
1298     * @param dimensions  the dimensions for the rectangle.
1299     * @param frame  the frame to align to.
1300     * @param hAlign  the horizontal alignment.
1301     * @param vAlign  the vertical alignment.
1302     *
1303     * @return A rectangle.
1304     */
1305    private Rectangle2D createAlignedRectangle2D(Size2D dimensions,
1306            Rectangle2D frame, HorizontalAlignment hAlign,
1307            VerticalAlignment vAlign) {
1308        double x = Double.NaN;
1309        double y = Double.NaN;
1310        if (hAlign == HorizontalAlignment.LEFT) {
1311            x = frame.getX();
1312        }
1313        else if (hAlign == HorizontalAlignment.CENTER) {
1314            x = frame.getCenterX() - (dimensions.width / 2.0);
1315        }
1316        else if (hAlign == HorizontalAlignment.RIGHT) {
1317            x = frame.getMaxX() - dimensions.width;
1318        }
1319        if (vAlign == VerticalAlignment.TOP) {
1320            y = frame.getY();
1321        }
1322        else if (vAlign == VerticalAlignment.CENTER) {
1323            y = frame.getCenterY() - (dimensions.height / 2.0);
1324        }
1325        else if (vAlign == VerticalAlignment.BOTTOM) {
1326            y = frame.getMaxY() - dimensions.height;
1327        }
1328
1329        return new Rectangle2D.Double(x, y, dimensions.width,
1330                dimensions.height);
1331    }
1332
1333    /**
1334     * Draws a title.  The title should be drawn at the top, bottom, left or
1335     * right of the specified area, and the area should be updated to reflect
1336     * the amount of space used by the title.
1337     *
1338     * @param t  the title ({@code null} not permitted).
1339     * @param g2  the graphics device ({@code null} not permitted).
1340     * @param area  the chart area, excluding any existing titles
1341     *              ({@code null} not permitted).
1342     * @param entities  a flag that controls whether or not an entity
1343     *                  collection is returned for the title.
1344     *
1345     * @return An entity collection for the title (possibly {@code null}).
1346     */
1347    protected EntityCollection drawTitle(Title t, Graphics2D g2,
1348                                         Rectangle2D area, boolean entities) {
1349
1350        Args.nullNotPermitted(t, "t");
1351        Args.nullNotPermitted(area, "area");
1352        Rectangle2D titleArea;
1353        RectangleEdge position = t.getPosition();
1354        double ww = area.getWidth();
1355        if (ww <= 0.0) {
1356            return null;
1357        }
1358        double hh = area.getHeight();
1359        if (hh <= 0.0) {
1360            return null;
1361        }
1362        RectangleConstraint constraint = new RectangleConstraint(ww,
1363                new Range(0.0, ww), LengthConstraintType.RANGE, hh,
1364                new Range(0.0, hh), LengthConstraintType.RANGE);
1365        Object retValue = null;
1366        BlockParams p = new BlockParams();
1367        p.setGenerateEntities(entities);
1368        if (position == RectangleEdge.TOP) {
1369            Size2D size = t.arrange(g2, constraint);
1370            titleArea = createAlignedRectangle2D(size, area,
1371                    t.getHorizontalAlignment(), VerticalAlignment.TOP);
1372            retValue = t.draw(g2, titleArea, p);
1373            area.setRect(area.getX(), Math.min(area.getY() + size.height,
1374                    area.getMaxY()), area.getWidth(), Math.max(area.getHeight()
1375                    - size.height, 0));
1376        } else if (position == RectangleEdge.BOTTOM) {
1377            Size2D size = t.arrange(g2, constraint);
1378            titleArea = createAlignedRectangle2D(size, area,
1379                    t.getHorizontalAlignment(), VerticalAlignment.BOTTOM);
1380            retValue = t.draw(g2, titleArea, p);
1381            area.setRect(area.getX(), area.getY(), area.getWidth(),
1382                    area.getHeight() - size.height);
1383        } else if (position == RectangleEdge.RIGHT) {
1384            Size2D size = t.arrange(g2, constraint);
1385            titleArea = createAlignedRectangle2D(size, area,
1386                    HorizontalAlignment.RIGHT, t.getVerticalAlignment());
1387            retValue = t.draw(g2, titleArea, p);
1388            area.setRect(area.getX(), area.getY(), area.getWidth()
1389                    - size.width, area.getHeight());
1390        } else if (position == RectangleEdge.LEFT) {
1391            Size2D size = t.arrange(g2, constraint);
1392            titleArea = createAlignedRectangle2D(size, area,
1393                    HorizontalAlignment.LEFT, t.getVerticalAlignment());
1394            retValue = t.draw(g2, titleArea, p);
1395            area.setRect(area.getX() + size.width, area.getY(), area.getWidth()
1396                    - size.width, area.getHeight());
1397        }
1398        else {
1399            throw new RuntimeException("Unrecognised title position.");
1400        }
1401        EntityCollection result = null;
1402        if (retValue instanceof EntityBlockResult) {
1403            EntityBlockResult ebr = (EntityBlockResult) retValue;
1404            result = ebr.getEntityCollection();
1405        }
1406        return result;
1407    }
1408
1409    /**
1410     * Creates and returns a buffered image into which the chart has been drawn.
1411     *
1412     * @param width  the width.
1413     * @param height  the height.
1414     *
1415     * @return A buffered image.
1416     */
1417    public BufferedImage createBufferedImage(int width, int height) {
1418        return createBufferedImage(width, height, null);
1419    }
1420
1421    /**
1422     * Creates and returns a buffered image into which the chart has been drawn.
1423     *
1424     * @param width  the width.
1425     * @param height  the height.
1426     * @param info  carries back chart state information ({@code null}
1427     *              permitted).
1428     *
1429     * @return A buffered image.
1430     */
1431    public BufferedImage createBufferedImage(int width, int height,
1432                                             ChartRenderingInfo info) {
1433        return createBufferedImage(width, height, BufferedImage.TYPE_INT_ARGB,
1434                info);
1435    }
1436
1437    /**
1438     * Creates and returns a buffered image into which the chart has been drawn.
1439     *
1440     * @param width  the width.
1441     * @param height  the height.
1442     * @param imageType  the image type.
1443     * @param info  carries back chart state information ({@code null}
1444     *              permitted).
1445     *
1446     * @return A buffered image.
1447     */
1448    public BufferedImage createBufferedImage(int width, int height,
1449            int imageType, ChartRenderingInfo info) {
1450        BufferedImage image = new BufferedImage(width, height, imageType);
1451        Graphics2D g2 = image.createGraphics();
1452        draw(g2, new Rectangle2D.Double(0, 0, width, height), null, info);
1453        g2.dispose();
1454        return image;
1455    }
1456
1457    /**
1458     * Creates and returns a buffered image into which the chart has been drawn.
1459     *
1460     * @param imageWidth  the image width.
1461     * @param imageHeight  the image height.
1462     * @param drawWidth  the width for drawing the chart (will be scaled to
1463     *                   fit image).
1464     * @param drawHeight  the height for drawing the chart (will be scaled to
1465     *                    fit image).
1466     * @param info  optional object for collection chart dimension and entity
1467     *              information.
1468     *
1469     * @return A buffered image.
1470     */
1471    public BufferedImage createBufferedImage(int imageWidth,
1472                                             int imageHeight,
1473                                             double drawWidth,
1474                                             double drawHeight,
1475                                             ChartRenderingInfo info) {
1476
1477        BufferedImage image = new BufferedImage(imageWidth, imageHeight,
1478                BufferedImage.TYPE_INT_ARGB);
1479        Graphics2D g2 = image.createGraphics();
1480        double scaleX = imageWidth / drawWidth;
1481        double scaleY = imageHeight / drawHeight;
1482        AffineTransform st = AffineTransform.getScaleInstance(scaleX, scaleY);
1483        g2.transform(st);
1484        draw(g2, new Rectangle2D.Double(0, 0, drawWidth, drawHeight), null,
1485                info);
1486        g2.dispose();
1487        return image;
1488    }
1489
1490    /**
1491     * Handles a 'click' on the chart.  JFreeChart is not a UI component, so
1492     * some other object (for example, {@link ChartPanel}) needs to capture
1493     * the click event and pass it onto the JFreeChart object.
1494     * If you are not using JFreeChart in a client application, then this
1495     * method is not required.
1496     *
1497     * @param x  x-coordinate of the click (in Java2D space).
1498     * @param y  y-coordinate of the click (in Java2D space).
1499     * @param info  contains chart dimension and entity information
1500     *              ({@code null} not permitted).
1501     */
1502    public void handleClick(int x, int y, ChartRenderingInfo info) {
1503        // pass the click on to the plot...
1504        // rely on the plot to post a plot change event and redraw the chart...
1505        this.plot.handleClick(x, y, info.getPlotInfo());
1506    }
1507
1508    /**
1509     * Registers an object for notification of changes to the chart.
1510     *
1511     * @param listener  the listener ({@code null} not permitted).
1512     *
1513     * @see #removeChangeListener(ChartChangeListener)
1514     */
1515    public void addChangeListener(ChartChangeListener listener) {
1516        Args.nullNotPermitted(listener, "listener");
1517        this.changeListeners.add(ChartChangeListener.class, listener);
1518    }
1519
1520    /**
1521     * Deregisters an object for notification of changes to the chart.
1522     *
1523     * @param listener  the listener ({@code null} not permitted)
1524     *
1525     * @see #addChangeListener(ChartChangeListener)
1526     */
1527    public void removeChangeListener(ChartChangeListener listener) {
1528        Args.nullNotPermitted(listener, "listener");
1529        this.changeListeners.remove(ChartChangeListener.class, listener);
1530    }
1531
1532    /**
1533     * Sends a default {@link ChartChangeEvent} to all registered listeners.
1534     * <P>
1535     * This method is for convenience only.
1536     */
1537    public void fireChartChanged() {
1538        ChartChangeEvent event = new ChartChangeEvent(this);
1539        notifyListeners(event);
1540    }
1541
1542    /**
1543     * Sends a {@link ChartChangeEvent} to all registered listeners.
1544     *
1545     * @param event  information about the event that triggered the
1546     *               notification.
1547     */
1548    protected void notifyListeners(ChartChangeEvent event) {
1549        if (this.notify) {
1550            Object[] listeners = this.changeListeners.getListenerList();
1551            for (int i = listeners.length - 2; i >= 0; i -= 2) {
1552                if (listeners[i] == ChartChangeListener.class) {
1553                    ((ChartChangeListener) listeners[i + 1]).chartChanged(
1554                            event);
1555                }
1556            }
1557        }
1558    }
1559
1560    /**
1561     * Registers an object for notification of progress events relating to the
1562     * chart.
1563     *
1564     * @param listener  the object being registered.
1565     *
1566     * @see #removeProgressListener(ChartProgressListener)
1567     */
1568    public void addProgressListener(ChartProgressListener listener) {
1569        this.progressListeners.add(ChartProgressListener.class, listener);
1570    }
1571
1572    /**
1573     * Deregisters an object for notification of changes to the chart.
1574     *
1575     * @param listener  the object being deregistered.
1576     *
1577     * @see #addProgressListener(ChartProgressListener)
1578     */
1579    public void removeProgressListener(ChartProgressListener listener) {
1580        this.progressListeners.remove(ChartProgressListener.class, listener);
1581    }
1582
1583    /**
1584     * Sends a {@link ChartProgressEvent} to all registered listeners.
1585     *
1586     * @param event  information about the event that triggered the
1587     *               notification.
1588     */
1589    protected void notifyListeners(ChartProgressEvent event) {
1590        Object[] listeners = this.progressListeners.getListenerList();
1591        for (int i = listeners.length - 2; i >= 0; i -= 2) {
1592            if (listeners[i] == ChartProgressListener.class) {
1593                ((ChartProgressListener) listeners[i + 1]).chartProgress(event);
1594            }
1595        }
1596    }
1597
1598    /**
1599     * Receives notification that a chart title has changed, and passes this
1600     * on to registered listeners.
1601     *
1602     * @param event  information about the chart title change.
1603     */
1604    @Override
1605    public void titleChanged(TitleChangeEvent event) {
1606        event.setChart(this);
1607        notifyListeners(event);
1608    }
1609
1610    /**
1611     * Receives notification that the plot has changed, and passes this on to
1612     * registered listeners.
1613     *
1614     * @param event  information about the plot change.
1615     */
1616    @Override
1617    public void plotChanged(PlotChangeEvent event) {
1618        event.setChart(this);
1619        notifyListeners(event);
1620    }
1621
1622    /**
1623     * Tests this chart for equality with another object.
1624     *
1625     * @param obj  the object ({@code null} permitted).
1626     *
1627     * @return A boolean.
1628     */
1629    @Override
1630    public boolean equals(Object obj) {
1631        if (obj == this) {
1632            return true;
1633        }
1634        if (!(obj instanceof JFreeChart)) {
1635            return false;
1636        }
1637        JFreeChart that = (JFreeChart) obj;
1638        if (!this.renderingHints.equals(that.renderingHints)) {
1639            return false;
1640        }
1641        if (this.borderVisible != that.borderVisible) {
1642            return false;
1643        }
1644        if (!ObjectUtils.equal(this.borderStroke, that.borderStroke)) {
1645            return false;
1646        }
1647        if (!PaintUtils.equal(this.borderPaint, that.borderPaint)) {
1648            return false;
1649        }
1650        if (!this.padding.equals(that.padding)) {
1651            return false;
1652        }
1653        if (!ObjectUtils.equal(this.title, that.title)) {
1654            return false;
1655        }
1656        if (!ObjectUtils.equal(this.subtitles, that.subtitles)) {
1657            return false;
1658        }
1659        if (!ObjectUtils.equal(this.plot, that.plot)) {
1660            return false;
1661        }
1662        if (!PaintUtils.equal(
1663            this.backgroundPaint, that.backgroundPaint
1664        )) {
1665            return false;
1666        }
1667        if (!ObjectUtils.equal(this.backgroundImage,
1668                that.backgroundImage)) {
1669            return false;
1670        }
1671        if (this.backgroundImageAlignment != that.backgroundImageAlignment) {
1672            return false;
1673        }
1674        if (this.backgroundImageAlpha != that.backgroundImageAlpha) {
1675            return false;
1676        }
1677        if (this.notify != that.notify) {
1678            return false;
1679        }
1680        return true;
1681    }
1682
1683    /**
1684     * Provides serialization support.
1685     *
1686     * @param stream  the output stream.
1687     *
1688     * @throws IOException  if there is an I/O error.
1689     */
1690    private void writeObject(ObjectOutputStream stream) throws IOException {
1691        stream.defaultWriteObject();
1692        SerialUtils.writeStroke(this.borderStroke, stream);
1693        SerialUtils.writePaint(this.borderPaint, stream);
1694        SerialUtils.writePaint(this.backgroundPaint, stream);
1695    }
1696
1697    /**
1698     * Provides serialization support.
1699     *
1700     * @param stream  the input stream.
1701     *
1702     * @throws IOException  if there is an I/O error.
1703     * @throws ClassNotFoundException  if there is a classpath problem.
1704     */
1705    private void readObject(ObjectInputStream stream)
1706        throws IOException, ClassNotFoundException {
1707        stream.defaultReadObject();
1708        this.borderStroke = SerialUtils.readStroke(stream);
1709        this.borderPaint = SerialUtils.readPaint(stream);
1710        this.backgroundPaint = SerialUtils.readPaint(stream);
1711        this.progressListeners = new EventListenerList();
1712        this.changeListeners = new EventListenerList();
1713        this.renderingHints = new RenderingHints(
1714                RenderingHints.KEY_ANTIALIASING,
1715                RenderingHints.VALUE_ANTIALIAS_ON);
1716        this.renderingHints.put(RenderingHints.KEY_STROKE_CONTROL,
1717                RenderingHints.VALUE_STROKE_PURE);
1718        
1719        // register as a listener with sub-components...
1720        if (this.title != null) {
1721            this.title.addChangeListener(this);
1722        }
1723
1724        for (int i = 0; i < getSubtitleCount(); i++) {
1725            getSubtitle(i).addChangeListener(this);
1726        }
1727        this.plot.addChangeListener(this);
1728    }
1729
1730    /**
1731     * Clones the object, and takes care of listeners.
1732     * Note: caller shall register its own listeners on cloned graph.
1733     *
1734     * @return A clone.
1735     *
1736     * @throws CloneNotSupportedException if the chart is not cloneable.
1737     */
1738    @Override
1739    public Object clone() throws CloneNotSupportedException {
1740        JFreeChart chart = (JFreeChart) super.clone();
1741
1742        chart.renderingHints = (RenderingHints) this.renderingHints.clone();
1743        // private boolean borderVisible;
1744        // private transient Stroke borderStroke;
1745        // private transient Paint borderPaint;
1746
1747        if (this.title != null) {
1748            chart.title = (TextTitle) this.title.clone();
1749            chart.title.addChangeListener(chart);
1750        }
1751
1752        chart.subtitles = new ArrayList();
1753        for (int i = 0; i < getSubtitleCount(); i++) {
1754            Title subtitle = (Title) getSubtitle(i).clone();
1755            chart.subtitles.add(subtitle);
1756            subtitle.addChangeListener(chart);
1757        }
1758
1759        if (this.plot != null) {
1760            chart.plot = (Plot) this.plot.clone();
1761            chart.plot.addChangeListener(chart);
1762        }
1763
1764        chart.progressListeners = new EventListenerList();
1765        chart.changeListeners = new EventListenerList();
1766        return chart;
1767    }
1768
1769}