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 * CategoryAxis.java
029 * -----------------
030 * (C) Copyright 2000-2017, by Object Refinery Limited and Contributors.
031 *
032 * Original Author:  David Gilbert;
033 * Contributor(s):   Pady Srinivasan (patch 1217634);
034 *                   Peter Kolb (patches 2497611 and 2603321);
035 *
036 * Changes
037 * -------
038 * 21-Aug-2001 : Added standard header. Fixed DOS encoding problem (DG);
039 * 18-Sep-2001 : Updated header (DG);
040 * 04-Dec-2001 : Changed constructors to protected, and tidied up default
041 *               values (DG);
042 * 19-Apr-2002 : Updated import statements (DG);
043 * 05-Sep-2002 : Updated constructor for changes in Axis class (DG);
044 * 06-Nov-2002 : Moved margins from the CategoryPlot class (DG);
045 * 08-Nov-2002 : Moved to new package com.jrefinery.chart.axis (DG);
046 * 22-Jan-2002 : Removed monolithic constructor (DG);
047 * 26-Mar-2003 : Implemented Serializable (DG);
048 * 09-May-2003 : Merged HorizontalCategoryAxis and VerticalCategoryAxis into
049 *               this class (DG);
050 * 13-Aug-2003 : Implemented Cloneable (DG);
051 * 29-Oct-2003 : Added workaround for font alignment in PDF output (DG);
052 * 05-Nov-2003 : Fixed serialization bug (DG);
053 * 26-Nov-2003 : Added category label offset (DG);
054 * 06-Jan-2004 : Moved axis line attributes to Axis class, rationalised
055 *               category label position attributes (DG);
056 * 07-Jan-2004 : Added new implementation for linewrapping of category
057 *               labels (DG);
058 * 17-Feb-2004 : Moved deprecated code to bottom of source file (DG);
059 * 10-Mar-2004 : Changed Dimension --> Dimension2D in text classes (DG);
060 * 16-Mar-2004 : Added support for tooltips on category labels (DG);
061 * 01-Apr-2004 : Changed java.awt.geom.Dimension2D to org.jfree.ui.Size2D
062 *               because of JDK bug 4976448 which persists on JDK 1.3.1 (DG);
063 * 03-Sep-2004 : Added 'maxCategoryLabelLines' attribute (DG);
064 * 04-Oct-2004 : Renamed ShapeUtils --> ShapeUtilities (DG);
065 * 11-Jan-2005 : Removed deprecated methods in preparation for 1.0.0
066 *               release (DG);
067 * 21-Jan-2005 : Modified return type for RectangleAnchor.coordinates()
068 *               method (DG);
069 * 21-Apr-2005 : Replaced Insets with RectangleInsets (DG);
070 * 26-Apr-2005 : Removed LOGGER (DG);
071 * 08-Jun-2005 : Fixed bug in axis layout (DG);
072 * 22-Nov-2005 : Added a method to access the tool tip text for a category
073 *               label (DG);
074 * 23-Nov-2005 : Added per-category font and paint options - see patch
075 *               1217634 (DG);
076 * ------------- JFreeChart 1.0.x ---------------------------------------------
077 * 11-Jan-2006 : Fixed null pointer exception in drawCategoryLabels - see bug
078 *               1403043 (DG);
079 * 18-Aug-2006 : Fix for bug drawing category labels, thanks to Adriaan
080 *               Joubert (1277726) (DG);
081 * 02-Oct-2006 : Updated category label entity (DG);
082 * 30-Oct-2006 : Updated refreshTicks() method to account for possibility of
083 *               multiple domain axes (DG);
084 * 07-Mar-2007 : Fixed bug in axis label positioning (DG);
085 * 27-Sep-2007 : Added getCategorySeriesMiddle() method (DG);
086 * 21-Nov-2007 : Fixed performance bug noted by FindBugs in the
087 *               equalPaintMaps() method (DG);
088 * 23-Apr-2008 : Fixed bug 1942059, bad use of insets in
089 *               calculateTextBlockWidth() (DG);
090 * 26-Jun-2008 : Added new getCategoryMiddle() method (DG);
091 * 27-Oct-2008 : Set font on Graphics2D when creating category labels (DG);
092 * 14-Jan-2009 : Added new variant of getCategorySeriesMiddle() to make it
093 *               simpler for renderers with hidden series (PK);
094 * 19-Mar-2009 : Added entity support - see patch 2603321 by Peter Kolb (DG);
095 * 16-Apr-2009 : Added tick mark drawing (DG);
096 * 29-Jun-2009 : Fixed bug where axis entity is hiding label entities (DG);
097 * 25-Jul-2013 : Added support for URLs on category labels (DG);
098 * 01-Aug-2013 : Added attributedLabel override to support superscripts,
099 *               subscripts and more (DG);
100 * 29-Jul-2014 : Add hint to normalise stroke for tick marks (DG);
101 *
102 */
103
104package org.jfree.chart.axis;
105
106import java.awt.Font;
107import java.awt.Graphics2D;
108import java.awt.Paint;
109import java.awt.RenderingHints;
110import java.awt.Shape;
111import java.awt.geom.Line2D;
112import java.awt.geom.Point2D;
113import java.awt.geom.Rectangle2D;
114import java.io.IOException;
115import java.io.ObjectInputStream;
116import java.io.ObjectOutputStream;
117import java.io.Serializable;
118import java.util.HashMap;
119import java.util.Iterator;
120import java.util.List;
121import java.util.Map;
122import java.util.Set;
123
124import org.jfree.chart.entity.CategoryLabelEntity;
125import org.jfree.chart.entity.EntityCollection;
126import org.jfree.chart.event.AxisChangeEvent;
127import org.jfree.chart.plot.CategoryPlot;
128import org.jfree.chart.plot.Plot;
129import org.jfree.chart.plot.PlotRenderingInfo;
130import org.jfree.chart.text.G2TextMeasurer;
131import org.jfree.chart.text.TextBlock;
132import org.jfree.chart.text.TextUtils;
133import org.jfree.chart.ui.RectangleEdge;
134import org.jfree.chart.ui.RectangleInsets;
135import org.jfree.chart.ui.Size2D;
136import org.jfree.chart.util.ObjectUtils;
137import org.jfree.chart.util.PaintUtils;
138import org.jfree.chart.util.Args;
139import org.jfree.chart.util.SerialUtils;
140import org.jfree.chart.util.ShapeUtils;
141import org.jfree.data.category.CategoryDataset;
142
143/**
144 * An axis that displays categories.
145 */
146public class CategoryAxis extends Axis implements Cloneable, Serializable {
147
148    /** For serialization. */
149    private static final long serialVersionUID = 5886554608114265863L;
150
151    /**
152     * The default margin for the axis (used for both lower and upper margins).
153     */
154    public static final double DEFAULT_AXIS_MARGIN = 0.05;
155
156    /**
157     * The default margin between categories (a percentage of the overall axis
158     * length).
159     */
160    public static final double DEFAULT_CATEGORY_MARGIN = 0.20;
161
162    /** The amount of space reserved at the start of the axis. */
163    private double lowerMargin;
164
165    /** The amount of space reserved at the end of the axis. */
166    private double upperMargin;
167
168    /** The amount of space reserved between categories. */
169    private double categoryMargin;
170
171    /** The maximum number of lines for category labels. */
172    private int maximumCategoryLabelLines;
173
174    /**
175     * A ratio that is multiplied by the width of one category to determine the
176     * maximum label width.
177     */
178    private float maximumCategoryLabelWidthRatio;
179
180    /** The category label offset. */
181    private int categoryLabelPositionOffset;
182
183    /**
184     * A structure defining the category label positions for each axis
185     * location.
186     */
187    private CategoryLabelPositions categoryLabelPositions;
188
189    /** Storage for tick label font overrides (if any). */
190    private Map tickLabelFontMap;
191
192    /** Storage for tick label paint overrides (if any). */
193    private transient Map tickLabelPaintMap;
194
195    /** Storage for the category label tooltips (if any). */
196    private Map categoryLabelToolTips;
197
198    /** Storage for the category label URLs (if any). */
199    private Map categoryLabelURLs;
200    
201    /**
202     * Creates a new category axis with no label.
203     */
204    public CategoryAxis() {
205        this(null);
206    }
207
208    /**
209     * Constructs a category axis, using default values where necessary.
210     *
211     * @param label  the axis label ({@code null} permitted).
212     */
213    public CategoryAxis(String label) {
214        super(label);
215
216        this.lowerMargin = DEFAULT_AXIS_MARGIN;
217        this.upperMargin = DEFAULT_AXIS_MARGIN;
218        this.categoryMargin = DEFAULT_CATEGORY_MARGIN;
219        this.maximumCategoryLabelLines = 1;
220        this.maximumCategoryLabelWidthRatio = 0.0f;
221
222        this.categoryLabelPositionOffset = 4;
223        this.categoryLabelPositions = CategoryLabelPositions.STANDARD;
224        this.tickLabelFontMap = new HashMap();
225        this.tickLabelPaintMap = new HashMap();
226        this.categoryLabelToolTips = new HashMap();
227        this.categoryLabelURLs = new HashMap();
228    }
229
230    /**
231     * Returns the lower margin for the axis.
232     *
233     * @return The margin.
234     *
235     * @see #getUpperMargin()
236     * @see #setLowerMargin(double)
237     */
238    public double getLowerMargin() {
239        return this.lowerMargin;
240    }
241
242    /**
243     * Sets the lower margin for the axis and sends an {@link AxisChangeEvent}
244     * to all registered listeners.
245     *
246     * @param margin  the margin as a percentage of the axis length (for
247     *                example, 0.05 is five percent).
248     *
249     * @see #getLowerMargin()
250     */
251    public void setLowerMargin(double margin) {
252        this.lowerMargin = margin;
253        fireChangeEvent();
254    }
255
256    /**
257     * Returns the upper margin for the axis.
258     *
259     * @return The margin.
260     *
261     * @see #getLowerMargin()
262     * @see #setUpperMargin(double)
263     */
264    public double getUpperMargin() {
265        return this.upperMargin;
266    }
267
268    /**
269     * Sets the upper margin for the axis and sends an {@link AxisChangeEvent}
270     * to all registered listeners.
271     *
272     * @param margin  the margin as a percentage of the axis length (for
273     *                example, 0.05 is five percent).
274     *
275     * @see #getUpperMargin()
276     */
277    public void setUpperMargin(double margin) {
278        this.upperMargin = margin;
279        fireChangeEvent();
280    }
281
282    /**
283     * Returns the category margin.
284     *
285     * @return The margin.
286     *
287     * @see #setCategoryMargin(double)
288     */
289    public double getCategoryMargin() {
290        return this.categoryMargin;
291    }
292
293    /**
294     * Sets the category margin and sends an {@link AxisChangeEvent} to all
295     * registered listeners.  The overall category margin is distributed over
296     * N-1 gaps, where N is the number of categories on the axis.
297     *
298     * @param margin  the margin as a percentage of the axis length (for
299     *                example, 0.05 is five percent).
300     *
301     * @see #getCategoryMargin()
302     */
303    public void setCategoryMargin(double margin) {
304        this.categoryMargin = margin;
305        fireChangeEvent();
306    }
307
308    /**
309     * Returns the maximum number of lines to use for each category label.
310     *
311     * @return The maximum number of lines.
312     *
313     * @see #setMaximumCategoryLabelLines(int)
314     */
315    public int getMaximumCategoryLabelLines() {
316        return this.maximumCategoryLabelLines;
317    }
318
319    /**
320     * Sets the maximum number of lines to use for each category label and
321     * sends an {@link AxisChangeEvent} to all registered listeners.
322     *
323     * @param lines  the maximum number of lines.
324     *
325     * @see #getMaximumCategoryLabelLines()
326     */
327    public void setMaximumCategoryLabelLines(int lines) {
328        this.maximumCategoryLabelLines = lines;
329        fireChangeEvent();
330    }
331
332    /**
333     * Returns the category label width ratio.
334     *
335     * @return The ratio.
336     *
337     * @see #setMaximumCategoryLabelWidthRatio(float)
338     */
339    public float getMaximumCategoryLabelWidthRatio() {
340        return this.maximumCategoryLabelWidthRatio;
341    }
342
343    /**
344     * Sets the maximum category label width ratio and sends an
345     * {@link AxisChangeEvent} to all registered listeners.
346     *
347     * @param ratio  the ratio.
348     *
349     * @see #getMaximumCategoryLabelWidthRatio()
350     */
351    public void setMaximumCategoryLabelWidthRatio(float ratio) {
352        this.maximumCategoryLabelWidthRatio = ratio;
353        fireChangeEvent();
354    }
355
356    /**
357     * Returns the offset between the axis and the category labels (before
358     * label positioning is taken into account).
359     *
360     * @return The offset (in Java2D units).
361     *
362     * @see #setCategoryLabelPositionOffset(int)
363     */
364    public int getCategoryLabelPositionOffset() {
365        return this.categoryLabelPositionOffset;
366    }
367
368    /**
369     * Sets the offset between the axis and the category labels (before label
370     * positioning is taken into account) and sends a change event to all 
371     * registered listeners.
372     *
373     * @param offset  the offset (in Java2D units).
374     *
375     * @see #getCategoryLabelPositionOffset()
376     */
377    public void setCategoryLabelPositionOffset(int offset) {
378        this.categoryLabelPositionOffset = offset;
379        fireChangeEvent();
380    }
381
382    /**
383     * Returns the category label position specification (this contains label
384     * positioning info for all four possible axis locations).
385     *
386     * @return The positions (never {@code null}).
387     *
388     * @see #setCategoryLabelPositions(CategoryLabelPositions)
389     */
390    public CategoryLabelPositions getCategoryLabelPositions() {
391        return this.categoryLabelPositions;
392    }
393
394    /**
395     * Sets the category label position specification for the axis and sends an
396     * {@link AxisChangeEvent} to all registered listeners.
397     *
398     * @param positions  the positions ({@code null} not permitted).
399     *
400     * @see #getCategoryLabelPositions()
401     */
402    public void setCategoryLabelPositions(CategoryLabelPositions positions) {
403        Args.nullNotPermitted(positions, "positions");
404        this.categoryLabelPositions = positions;
405        fireChangeEvent();
406    }
407
408    /**
409     * Returns the font for the tick label for the given category.
410     *
411     * @param category  the category ({@code null} not permitted).
412     *
413     * @return The font (never {@code null}).
414     *
415     * @see #setTickLabelFont(Comparable, Font)
416     */
417    public Font getTickLabelFont(Comparable category) {
418        Args.nullNotPermitted(category, "category");
419        Font result = (Font) this.tickLabelFontMap.get(category);
420        // if there is no specific font, use the general one...
421        if (result == null) {
422            result = getTickLabelFont();
423        }
424        return result;
425    }
426
427    /**
428     * Sets the font for the tick label for the specified category and sends
429     * an {@link AxisChangeEvent} to all registered listeners.
430     *
431     * @param category  the category ({@code null} not permitted).
432     * @param font  the font ({@code null} permitted).
433     *
434     * @see #getTickLabelFont(Comparable)
435     */
436    public void setTickLabelFont(Comparable category, Font font) {
437        Args.nullNotPermitted(category, "category");
438        if (font == null) {
439            this.tickLabelFontMap.remove(category);
440        }
441        else {
442            this.tickLabelFontMap.put(category, font);
443        }
444        fireChangeEvent();
445    }
446
447    /**
448     * Returns the paint for the tick label for the given category.
449     *
450     * @param category  the category ({@code null} not permitted).
451     *
452     * @return The paint (never {@code null}).
453     *
454     * @see #setTickLabelPaint(Paint)
455     */
456    public Paint getTickLabelPaint(Comparable category) {
457        Args.nullNotPermitted(category, "category");
458        Paint result = (Paint) this.tickLabelPaintMap.get(category);
459        // if there is no specific paint, use the general one...
460        if (result == null) {
461            result = getTickLabelPaint();
462        }
463        return result;
464    }
465
466    /**
467     * Sets the paint for the tick label for the specified category and sends
468     * an {@link AxisChangeEvent} to all registered listeners.
469     *
470     * @param category  the category ({@code null} not permitted).
471     * @param paint  the paint ({@code null} permitted).
472     *
473     * @see #getTickLabelPaint(Comparable)
474     */
475    public void setTickLabelPaint(Comparable category, Paint paint) {
476        Args.nullNotPermitted(category, "category");
477        if (paint == null) {
478            this.tickLabelPaintMap.remove(category);
479        }
480        else {
481            this.tickLabelPaintMap.put(category, paint);
482        }
483        fireChangeEvent();
484    }
485
486    /**
487     * Adds a tooltip to the specified category and sends an
488     * {@link AxisChangeEvent} to all registered listeners.
489     *
490     * @param category  the category ({@code null} not permitted).
491     * @param tooltip  the tooltip text ({@code null} permitted).
492     *
493     * @see #removeCategoryLabelToolTip(Comparable)
494     */
495    public void addCategoryLabelToolTip(Comparable category, String tooltip) {
496        Args.nullNotPermitted(category, "category");
497        this.categoryLabelToolTips.put(category, tooltip);
498        fireChangeEvent();
499    }
500
501    /**
502     * Returns the tool tip text for the label belonging to the specified
503     * category.
504     *
505     * @param category  the category ({@code null} not permitted).
506     *
507     * @return The tool tip text (possibly {@code null}).
508     *
509     * @see #addCategoryLabelToolTip(Comparable, String)
510     * @see #removeCategoryLabelToolTip(Comparable)
511     */
512    public String getCategoryLabelToolTip(Comparable category) {
513        Args.nullNotPermitted(category, "category");
514        return (String) this.categoryLabelToolTips.get(category);
515    }
516
517    /**
518     * Removes the tooltip for the specified category and, if there was a value
519     * associated with that category, sends an {@link AxisChangeEvent} to all 
520     * registered listeners.
521     *
522     * @param category  the category ({@code null} not permitted).
523     *
524     * @see #addCategoryLabelToolTip(Comparable, String)
525     * @see #clearCategoryLabelToolTips()
526     */
527    public void removeCategoryLabelToolTip(Comparable category) {
528        Args.nullNotPermitted(category, "category");
529        if (this.categoryLabelToolTips.remove(category) != null) {
530            fireChangeEvent();
531        }
532    }
533
534    /**
535     * Clears the category label tooltips and sends an {@link AxisChangeEvent}
536     * to all registered listeners.
537     *
538     * @see #addCategoryLabelToolTip(Comparable, String)
539     * @see #removeCategoryLabelToolTip(Comparable)
540     */
541    public void clearCategoryLabelToolTips() {
542        this.categoryLabelToolTips.clear();
543        fireChangeEvent();
544    }
545
546    /**
547     * Adds a URL (to be used in image maps) to the specified category and 
548     * sends an {@link AxisChangeEvent} to all registered listeners.
549     *
550     * @param category  the category ({@code null} not permitted).
551     * @param url  the URL text ({@code null} permitted).
552     *
553     * @see #removeCategoryLabelURL(Comparable)
554     * 
555     * @since 1.0.16
556     */
557    public void addCategoryLabelURL(Comparable category, String url) {
558        Args.nullNotPermitted(category, "category");
559        this.categoryLabelURLs.put(category, url);
560        fireChangeEvent();
561    }
562
563    /**
564     * Returns the URL for the label belonging to the specified category.
565     *
566     * @param category  the category ({@code null} not permitted).
567     *
568     * @return The URL text (possibly {@code null}).
569     * 
570     * @see #addCategoryLabelURL(Comparable, String)
571     * @see #removeCategoryLabelURL(Comparable)
572     * 
573     * @since 1.0.16
574     */
575    public String getCategoryLabelURL(Comparable category) {
576        Args.nullNotPermitted(category, "category");
577        return (String) this.categoryLabelURLs.get(category);
578    }
579
580    /**
581     * Removes the URL for the specified category and, if there was a URL 
582     * associated with that category, sends an {@link AxisChangeEvent} to all 
583     * registered listeners.
584     *
585     * @param category  the category ({@code null} not permitted).
586     *
587     * @see #addCategoryLabelURL(Comparable, String)
588     * @see #clearCategoryLabelURLs()
589     * 
590     * @since 1.0.16
591     */
592    public void removeCategoryLabelURL(Comparable category) {
593        Args.nullNotPermitted(category, "category");
594        if (this.categoryLabelURLs.remove(category) != null) {
595            fireChangeEvent();
596        }
597    }
598
599    /**
600     * Clears the category label URLs and sends an {@link AxisChangeEvent}
601     * to all registered listeners.
602     *
603     * @see #addCategoryLabelURL(Comparable, String)
604     * @see #removeCategoryLabelURL(Comparable)
605     * 
606     * @since 1.0.16
607     */
608    public void clearCategoryLabelURLs() {
609        this.categoryLabelURLs.clear();
610        fireChangeEvent();
611    }
612    
613    /**
614     * Returns the Java 2D coordinate for a category.
615     *
616     * @param anchor  the anchor point.
617     * @param category  the category index.
618     * @param categoryCount  the category count.
619     * @param area  the data area.
620     * @param edge  the location of the axis.
621     *
622     * @return The coordinate.
623     */
624    public double getCategoryJava2DCoordinate(CategoryAnchor anchor, 
625            int category, int categoryCount, Rectangle2D area, 
626            RectangleEdge edge) {
627
628        double result = 0.0;
629        if (anchor == CategoryAnchor.START) {
630            result = getCategoryStart(category, categoryCount, area, edge);
631        }
632        else if (anchor == CategoryAnchor.MIDDLE) {
633            result = getCategoryMiddle(category, categoryCount, area, edge);
634        }
635        else if (anchor == CategoryAnchor.END) {
636            result = getCategoryEnd(category, categoryCount, area, edge);
637        }
638        return result;
639
640    }
641
642    /**
643     * Returns the starting coordinate for the specified category.
644     *
645     * @param category  the category.
646     * @param categoryCount  the number of categories.
647     * @param area  the data area.
648     * @param edge  the axis location.
649     *
650     * @return The coordinate.
651     *
652     * @see #getCategoryMiddle(int, int, Rectangle2D, RectangleEdge)
653     * @see #getCategoryEnd(int, int, Rectangle2D, RectangleEdge)
654     */
655    public double getCategoryStart(int category, int categoryCount, 
656            Rectangle2D area, RectangleEdge edge) {
657
658        double result = 0.0;
659        if ((edge == RectangleEdge.TOP) || (edge == RectangleEdge.BOTTOM)) {
660            result = area.getX() + area.getWidth() * getLowerMargin();
661        }
662        else if ((edge == RectangleEdge.LEFT)
663                || (edge == RectangleEdge.RIGHT)) {
664            result = area.getMinY() + area.getHeight() * getLowerMargin();
665        }
666
667        double categorySize = calculateCategorySize(categoryCount, area, edge);
668        double categoryGapWidth = calculateCategoryGapSize(categoryCount, area,
669                edge);
670
671        result = result + category * (categorySize + categoryGapWidth);
672        return result;
673    }
674
675    /**
676     * Returns the middle coordinate for the specified category.
677     *
678     * @param category  the category.
679     * @param categoryCount  the number of categories.
680     * @param area  the data area.
681     * @param edge  the axis location.
682     *
683     * @return The coordinate.
684     *
685     * @see #getCategoryStart(int, int, Rectangle2D, RectangleEdge)
686     * @see #getCategoryEnd(int, int, Rectangle2D, RectangleEdge)
687     */
688    public double getCategoryMiddle(int category, int categoryCount,
689            Rectangle2D area, RectangleEdge edge) {
690
691        if (category < 0 || category >= categoryCount) {
692            throw new IllegalArgumentException("Invalid category index: "
693                    + category);
694        }
695        return getCategoryStart(category, categoryCount, area, edge)
696               + calculateCategorySize(categoryCount, area, edge) / 2;
697
698    }
699
700    /**
701     * Returns the end coordinate for the specified category.
702     *
703     * @param category  the category.
704     * @param categoryCount  the number of categories.
705     * @param area  the data area.
706     * @param edge  the axis location.
707     *
708     * @return The coordinate.
709     *
710     * @see #getCategoryStart(int, int, Rectangle2D, RectangleEdge)
711     * @see #getCategoryMiddle(int, int, Rectangle2D, RectangleEdge)
712     */
713    public double getCategoryEnd(int category, int categoryCount,
714            Rectangle2D area, RectangleEdge edge) {
715        return getCategoryStart(category, categoryCount, area, edge)
716               + calculateCategorySize(categoryCount, area, edge);
717    }
718
719    /**
720     * A convenience method that returns the axis coordinate for the centre of
721     * a category.
722     *
723     * @param category  the category key ({@code null} not permitted).
724     * @param categories  the categories ({@code null} not permitted).
725     * @param area  the data area ({@code null} not permitted).
726     * @param edge  the edge along which the axis lies ({@code null} not
727     *     permitted).
728     *
729     * @return The centre coordinate.
730     *
731     * @since 1.0.11
732     *
733     * @see #getCategorySeriesMiddle(Comparable, Comparable, CategoryDataset,
734     *     double, Rectangle2D, RectangleEdge)
735     */
736    public double getCategoryMiddle(Comparable category,
737            List categories, Rectangle2D area, RectangleEdge edge) {
738        Args.nullNotPermitted(categories, "categories");
739        int categoryIndex = categories.indexOf(category);
740        int categoryCount = categories.size();
741        return getCategoryMiddle(categoryIndex, categoryCount, area, edge);
742    }
743
744    /**
745     * Returns the middle coordinate (in Java2D space) for a series within a
746     * category.
747     *
748     * @param category  the category ({@code null} not permitted).
749     * @param seriesKey  the series key ({@code null} not permitted).
750     * @param dataset  the dataset ({@code null} not permitted).
751     * @param itemMargin  the item margin (0.0 &lt;= itemMargin &lt; 1.0);
752     * @param area  the area ({@code null} not permitted).
753     * @param edge  the edge ({@code null} not permitted).
754     *
755     * @return The coordinate in Java2D space.
756     *
757     * @since 1.0.7
758     */
759    public double getCategorySeriesMiddle(Comparable category,
760            Comparable seriesKey, CategoryDataset dataset, double itemMargin,
761            Rectangle2D area, RectangleEdge edge) {
762
763        int categoryIndex = dataset.getColumnIndex(category);
764        int categoryCount = dataset.getColumnCount();
765        int seriesIndex = dataset.getRowIndex(seriesKey);
766        int seriesCount = dataset.getRowCount();
767        double start = getCategoryStart(categoryIndex, categoryCount, area,
768                edge);
769        double end = getCategoryEnd(categoryIndex, categoryCount, area, edge);
770        double width = end - start;
771        if (seriesCount == 1) {
772            return start + width / 2.0;
773        }
774        else {
775            double gap = (width * itemMargin) / (seriesCount - 1);
776            double ww = (width * (1 - itemMargin)) / seriesCount;
777            return start + (seriesIndex * (ww + gap)) + ww / 2.0;
778        }
779    }
780
781    /**
782     * Returns the middle coordinate (in Java2D space) for a series within a
783     * category.
784     *
785     * @param categoryIndex  the category index.
786     * @param categoryCount  the category count.
787     * @param seriesIndex the series index.
788     * @param seriesCount the series count.
789     * @param itemMargin  the item margin (0.0 &lt;= itemMargin &lt; 1.0);
790     * @param area  the area ({@code null} not permitted).
791     * @param edge  the edge ({@code null} not permitted).
792     *
793     * @return The coordinate in Java2D space.
794     *
795     * @since 1.0.13
796     */
797    public double getCategorySeriesMiddle(int categoryIndex, int categoryCount,
798            int seriesIndex, int seriesCount, double itemMargin,
799            Rectangle2D area, RectangleEdge edge) {
800
801        double start = getCategoryStart(categoryIndex, categoryCount, area,
802                edge);
803        double end = getCategoryEnd(categoryIndex, categoryCount, area, edge);
804        double width = end - start;
805        if (seriesCount == 1) {
806            return start + width / 2.0;
807        }
808        else {
809            double gap = (width * itemMargin) / (seriesCount - 1);
810            double ww = (width * (1 - itemMargin)) / seriesCount;
811            return start + (seriesIndex * (ww + gap)) + ww / 2.0;
812        }
813    }
814
815    /**
816     * Calculates the size (width or height, depending on the location of the
817     * axis) of a category.
818     *
819     * @param categoryCount  the number of categories.
820     * @param area  the area within which the categories will be drawn.
821     * @param edge  the axis location.
822     *
823     * @return The category size.
824     */
825    protected double calculateCategorySize(int categoryCount, Rectangle2D area,
826            RectangleEdge edge) {
827        double result;
828        double available = 0.0;
829
830        if ((edge == RectangleEdge.TOP) || (edge == RectangleEdge.BOTTOM)) {
831            available = area.getWidth();
832        }
833        else if ((edge == RectangleEdge.LEFT)
834                || (edge == RectangleEdge.RIGHT)) {
835            available = area.getHeight();
836        }
837        if (categoryCount > 1) {
838            result = available * (1 - getLowerMargin() - getUpperMargin()
839                     - getCategoryMargin());
840            result = result / categoryCount;
841        }
842        else {
843            result = available * (1 - getLowerMargin() - getUpperMargin());
844        }
845        return result;
846    }
847
848    /**
849     * Calculates the size (width or height, depending on the location of the
850     * axis) of a category gap.
851     *
852     * @param categoryCount  the number of categories.
853     * @param area  the area within which the categories will be drawn.
854     * @param edge  the axis location.
855     *
856     * @return The category gap width.
857     */
858    protected double calculateCategoryGapSize(int categoryCount, 
859            Rectangle2D area, RectangleEdge edge) {
860
861        double result = 0.0;
862        double available = 0.0;
863
864        if ((edge == RectangleEdge.TOP) || (edge == RectangleEdge.BOTTOM)) {
865            available = area.getWidth();
866        }
867        else if ((edge == RectangleEdge.LEFT)
868                || (edge == RectangleEdge.RIGHT)) {
869            available = area.getHeight();
870        }
871
872        if (categoryCount > 1) {
873            result = available * getCategoryMargin() / (categoryCount - 1);
874        }
875        return result;
876    }
877
878    /**
879     * Estimates the space required for the axis, given a specific drawing area.
880     *
881     * @param g2  the graphics device (used to obtain font information).
882     * @param plot  the plot that the axis belongs to.
883     * @param plotArea  the area within which the axis should be drawn.
884     * @param edge  the axis location (top or bottom).
885     * @param space  the space already reserved.
886     *
887     * @return The space required to draw the axis.
888     */
889    @Override
890    public AxisSpace reserveSpace(Graphics2D g2, Plot plot, 
891            Rectangle2D plotArea, RectangleEdge edge, AxisSpace space) {
892
893        // create a new space object if one wasn't supplied...
894        if (space == null) {
895            space = new AxisSpace();
896        }
897
898        // if the axis is not visible, no additional space is required...
899        if (!isVisible()) {
900            return space;
901        }
902
903        // calculate the max size of the tick labels (if visible)...
904        double tickLabelHeight = 0.0;
905        double tickLabelWidth = 0.0;
906        if (isTickLabelsVisible()) {
907            g2.setFont(getTickLabelFont());
908            AxisState state = new AxisState();
909            // we call refresh ticks just to get the maximum width or height
910            refreshTicks(g2, state, plotArea, edge);
911            if (edge == RectangleEdge.TOP) {
912                tickLabelHeight = state.getMax();
913            }
914            else if (edge == RectangleEdge.BOTTOM) {
915                tickLabelHeight = state.getMax();
916            }
917            else if (edge == RectangleEdge.LEFT) {
918                tickLabelWidth = state.getMax();
919            }
920            else if (edge == RectangleEdge.RIGHT) {
921                tickLabelWidth = state.getMax();
922            }
923        }
924
925        // get the axis label size and update the space object...
926        Rectangle2D labelEnclosure = getLabelEnclosure(g2, edge);
927        double labelHeight, labelWidth;
928        if (RectangleEdge.isTopOrBottom(edge)) {
929            labelHeight = labelEnclosure.getHeight();
930            space.add(labelHeight + tickLabelHeight
931                    + this.categoryLabelPositionOffset, edge);
932        }
933        else if (RectangleEdge.isLeftOrRight(edge)) {
934            labelWidth = labelEnclosure.getWidth();
935            space.add(labelWidth + tickLabelWidth
936                    + this.categoryLabelPositionOffset, edge);
937        }
938        return space;
939    }
940
941    /**
942     * Configures the axis against the current plot.
943     */
944    @Override
945    public void configure() {
946        // nothing required
947    }
948
949    /**
950     * Draws the axis on a Java 2D graphics device (such as the screen or a
951     * printer).
952     *
953     * @param g2  the graphics device ({@code null} not permitted).
954     * @param cursor  the cursor location.
955     * @param plotArea  the area within which the axis should be drawn
956     *                  ({@code null} not permitted).
957     * @param dataArea  the area within which the plot is being drawn
958     *                  ({@code null} not permitted).
959     * @param edge  the location of the axis ({@code null} not permitted).
960     * @param plotState  collects information about the plot
961     *                   ({@code null} permitted).
962     *
963     * @return The axis state (never {@code null}).
964     */
965    @Override
966    public AxisState draw(Graphics2D g2, double cursor, Rectangle2D plotArea,
967            Rectangle2D dataArea, RectangleEdge edge,
968            PlotRenderingInfo plotState) {
969
970        // if the axis is not visible, don't draw it...
971        if (!isVisible()) {
972            return new AxisState(cursor);
973        }
974
975        if (isAxisLineVisible()) {
976            drawAxisLine(g2, cursor, dataArea, edge);
977        }
978        AxisState state = new AxisState(cursor);
979        if (isTickMarksVisible()) {
980            drawTickMarks(g2, cursor, dataArea, edge, state);
981        }
982
983        createAndAddEntity(cursor, state, dataArea, edge, plotState);
984
985        // draw the category labels and axis label
986        state = drawCategoryLabels(g2, plotArea, dataArea, edge, state,
987                plotState);
988        if (getAttributedLabel() != null) {
989            state = drawAttributedLabel(getAttributedLabel(), g2, plotArea, 
990                    dataArea, edge, state);
991            
992        } else {
993            state = drawLabel(getLabel(), g2, plotArea, dataArea, edge, state);
994        }
995        return state;
996
997    }
998
999    /**
1000     * Draws the category labels and returns the updated axis state.
1001     *
1002     * @param g2  the graphics device ({@code null} not permitted).
1003     * @param plotArea  the plot area ({@code null} not permitted).
1004     * @param dataArea  the area inside the axes ({@code null} not
1005     *                  permitted).
1006     * @param edge  the axis location ({@code null} not permitted).
1007     * @param state  the axis state ({@code null} not permitted).
1008     * @param plotState  collects information about the plot ({@code null}
1009     *                   permitted).
1010     *
1011     * @return The updated axis state (never {@code null}).
1012     */
1013    protected AxisState drawCategoryLabels(Graphics2D g2, Rectangle2D plotArea,
1014            Rectangle2D dataArea, RectangleEdge edge, AxisState state,
1015            PlotRenderingInfo plotState) {
1016
1017        Args.nullNotPermitted(state, "state");
1018        if (!isTickLabelsVisible()) {
1019            return state;
1020        }
1021 
1022        List ticks = refreshTicks(g2, state, plotArea, edge);
1023        state.setTicks(ticks);
1024        int categoryIndex = 0;
1025        Iterator iterator = ticks.iterator();
1026        while (iterator.hasNext()) {
1027            CategoryTick tick = (CategoryTick) iterator.next();
1028            g2.setFont(getTickLabelFont(tick.getCategory()));
1029            g2.setPaint(getTickLabelPaint(tick.getCategory()));
1030
1031            CategoryLabelPosition position
1032                    = this.categoryLabelPositions.getLabelPosition(edge);
1033            double x0 = 0.0;
1034            double x1 = 0.0;
1035            double y0 = 0.0;
1036            double y1 = 0.0;
1037            if (edge == RectangleEdge.TOP) {
1038                x0 = getCategoryStart(categoryIndex, ticks.size(), dataArea, 
1039                        edge);
1040                x1 = getCategoryEnd(categoryIndex, ticks.size(), dataArea, 
1041                        edge);
1042                y1 = state.getCursor() - this.categoryLabelPositionOffset;
1043                y0 = y1 - state.getMax();
1044            }
1045            else if (edge == RectangleEdge.BOTTOM) {
1046                x0 = getCategoryStart(categoryIndex, ticks.size(), dataArea, 
1047                        edge);
1048                x1 = getCategoryEnd(categoryIndex, ticks.size(), dataArea, 
1049                        edge);
1050                y0 = state.getCursor() + this.categoryLabelPositionOffset;
1051                y1 = y0 + state.getMax();
1052            }
1053            else if (edge == RectangleEdge.LEFT) {
1054                y0 = getCategoryStart(categoryIndex, ticks.size(), dataArea, 
1055                        edge);
1056                y1 = getCategoryEnd(categoryIndex, ticks.size(), dataArea,
1057                        edge);
1058                x1 = state.getCursor() - this.categoryLabelPositionOffset;
1059                x0 = x1 - state.getMax();
1060            }
1061            else if (edge == RectangleEdge.RIGHT) {
1062                y0 = getCategoryStart(categoryIndex, ticks.size(), dataArea, 
1063                        edge);
1064                y1 = getCategoryEnd(categoryIndex, ticks.size(), dataArea,
1065                        edge);
1066                x0 = state.getCursor() + this.categoryLabelPositionOffset;
1067                x1 = x0 - state.getMax();
1068            }
1069            Rectangle2D area = new Rectangle2D.Double(x0, y0, (x1 - x0),
1070                    (y1 - y0));
1071            Point2D anchorPoint = position.getCategoryAnchor().getAnchorPoint(area);
1072            TextBlock block = tick.getLabel();
1073            block.draw(g2, (float) anchorPoint.getX(),
1074                    (float) anchorPoint.getY(), position.getLabelAnchor(),
1075                    (float) anchorPoint.getX(), (float) anchorPoint.getY(),
1076                    position.getAngle());
1077            Shape bounds = block.calculateBounds(g2,
1078                    (float) anchorPoint.getX(), (float) anchorPoint.getY(),
1079                    position.getLabelAnchor(), (float) anchorPoint.getX(),
1080                    (float) anchorPoint.getY(), position.getAngle());
1081            if (plotState != null && plotState.getOwner() != null) {
1082                EntityCollection entities = plotState.getOwner()
1083                        .getEntityCollection();
1084                if (entities != null) {
1085                    String tooltip = getCategoryLabelToolTip(
1086                            tick.getCategory());
1087                    String url = getCategoryLabelURL(tick.getCategory());
1088                    entities.add(new CategoryLabelEntity(tick.getCategory(),
1089                            bounds, tooltip, url));
1090                }
1091            }
1092            categoryIndex++;
1093        }
1094
1095        if (edge.equals(RectangleEdge.TOP)) {
1096            double h = state.getMax() + this.categoryLabelPositionOffset;
1097            state.cursorUp(h);
1098        }
1099        else if (edge.equals(RectangleEdge.BOTTOM)) {
1100            double h = state.getMax() + this.categoryLabelPositionOffset;
1101            state.cursorDown(h);
1102        }
1103        else if (edge == RectangleEdge.LEFT) {
1104            double w = state.getMax() + this.categoryLabelPositionOffset;
1105            state.cursorLeft(w);
1106        }
1107        else if (edge == RectangleEdge.RIGHT) {
1108            double w = state.getMax() + this.categoryLabelPositionOffset;
1109            state.cursorRight(w);
1110        }
1111        return state;
1112    }
1113
1114    /**
1115     * Creates a temporary list of ticks that can be used when drawing the axis.
1116     *
1117     * @param g2  the graphics device (used to get font measurements).
1118     * @param state  the axis state.
1119     * @param dataArea  the area inside the axes.
1120     * @param edge  the location of the axis.
1121     *
1122     * @return A list of ticks.
1123     */
1124    @Override
1125    public List refreshTicks(Graphics2D g2, AxisState state, 
1126            Rectangle2D dataArea, RectangleEdge edge) {
1127
1128        List ticks = new java.util.ArrayList();
1129
1130        // sanity check for data area...
1131        if (dataArea.getHeight() <= 0.0 || dataArea.getWidth() < 0.0) {
1132            return ticks;
1133        }
1134
1135        CategoryPlot plot = (CategoryPlot) getPlot();
1136        List categories = plot.getCategoriesForAxis(this);
1137        double max = 0.0;
1138
1139        if (categories != null) {
1140            CategoryLabelPosition position
1141                    = this.categoryLabelPositions.getLabelPosition(edge);
1142            float r = this.maximumCategoryLabelWidthRatio;
1143            if (r <= 0.0) {
1144                r = position.getWidthRatio();
1145            }
1146
1147            float l;
1148            if (position.getWidthType() == CategoryLabelWidthType.CATEGORY) {
1149                l = (float) calculateCategorySize(categories.size(), dataArea,
1150                        edge);
1151            }
1152            else {
1153                if (RectangleEdge.isLeftOrRight(edge)) {
1154                    l = (float) dataArea.getWidth();
1155                }
1156                else {
1157                    l = (float) dataArea.getHeight();
1158                }
1159            }
1160            int categoryIndex = 0;
1161            Iterator iterator = categories.iterator();
1162            while (iterator.hasNext()) {
1163                Comparable category = (Comparable) iterator.next();
1164                g2.setFont(getTickLabelFont(category));
1165                TextBlock label = createLabel(category, l * r, edge, g2);
1166                if (edge == RectangleEdge.TOP || edge == RectangleEdge.BOTTOM) {
1167                    max = Math.max(max, calculateTextBlockHeight(label,
1168                            position, g2));
1169                }
1170                else if (edge == RectangleEdge.LEFT
1171                        || edge == RectangleEdge.RIGHT) {
1172                    max = Math.max(max, calculateTextBlockWidth(label,
1173                            position, g2));
1174                }
1175                Tick tick = new CategoryTick(category, label,
1176                        position.getLabelAnchor(),
1177                        position.getRotationAnchor(), position.getAngle());
1178                ticks.add(tick);
1179                categoryIndex = categoryIndex + 1;
1180            }
1181        }
1182        state.setMax(max);
1183        return ticks;
1184
1185    }
1186
1187    /**
1188     * Draws the tick marks.
1189     * 
1190     * @param g2  the graphics target.
1191     * @param cursor  the cursor position (an offset when drawing multiple axes)
1192     * @param dataArea  the area for plotting the data.
1193     * @param edge  the location of the axis.
1194     * @param state  the axis state.
1195     *
1196     * @since 1.0.13
1197     */
1198    public void drawTickMarks(Graphics2D g2, double cursor,
1199            Rectangle2D dataArea, RectangleEdge edge, AxisState state) {
1200
1201        Plot p = getPlot();
1202        if (p == null) {
1203            return;
1204        }
1205        CategoryPlot plot = (CategoryPlot) p;
1206        double il = getTickMarkInsideLength();
1207        double ol = getTickMarkOutsideLength();
1208        Line2D line = new Line2D.Double();
1209        List categories = plot.getCategoriesForAxis(this);
1210        g2.setPaint(getTickMarkPaint());
1211        g2.setStroke(getTickMarkStroke());
1212        Object saved = g2.getRenderingHint(RenderingHints.KEY_STROKE_CONTROL);
1213        g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, 
1214                RenderingHints.VALUE_STROKE_NORMALIZE);
1215        if (edge.equals(RectangleEdge.TOP)) {
1216            Iterator iterator = categories.iterator();
1217            while (iterator.hasNext()) {
1218                Comparable key = (Comparable) iterator.next();
1219                double x = getCategoryMiddle(key, categories, dataArea, edge);
1220                line.setLine(x, cursor, x, cursor + il);
1221                g2.draw(line);
1222                line.setLine(x, cursor, x, cursor - ol);
1223                g2.draw(line);
1224            }
1225            state.cursorUp(ol);
1226        } else if (edge.equals(RectangleEdge.BOTTOM)) {
1227            Iterator iterator = categories.iterator();
1228            while (iterator.hasNext()) {
1229                Comparable key = (Comparable) iterator.next();
1230                double x = getCategoryMiddle(key, categories, dataArea, edge);
1231                line.setLine(x, cursor, x, cursor - il);
1232                g2.draw(line);
1233                line.setLine(x, cursor, x, cursor + ol);
1234                g2.draw(line);
1235            }
1236            state.cursorDown(ol);
1237        } else if (edge.equals(RectangleEdge.LEFT)) {
1238            Iterator iterator = categories.iterator();
1239            while (iterator.hasNext()) {
1240                Comparable key = (Comparable) iterator.next();
1241                double y = getCategoryMiddle(key, categories, dataArea, edge);
1242                line.setLine(cursor, y, cursor + il, y);
1243                g2.draw(line);
1244                line.setLine(cursor, y, cursor - ol, y);
1245                g2.draw(line);
1246            }
1247            state.cursorLeft(ol);
1248        } else if (edge.equals(RectangleEdge.RIGHT)) {
1249            Iterator iterator = categories.iterator();
1250            while (iterator.hasNext()) {
1251                Comparable key = (Comparable) iterator.next();
1252                double y = getCategoryMiddle(key, categories, dataArea, edge);
1253                line.setLine(cursor, y, cursor - il, y);
1254                g2.draw(line);
1255                line.setLine(cursor, y, cursor + ol, y);
1256                g2.draw(line);
1257            }
1258            state.cursorRight(ol);
1259        }
1260        g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, saved);
1261    }
1262
1263    /**
1264     * Creates a label.
1265     *
1266     * @param category  the category.
1267     * @param width  the available width.
1268     * @param edge  the edge on which the axis appears.
1269     * @param g2  the graphics device.
1270     *
1271     * @return A label.
1272     */
1273    protected TextBlock createLabel(Comparable category, float width,
1274            RectangleEdge edge, Graphics2D g2) {
1275        TextBlock label = TextUtils.createTextBlock(category.toString(),
1276                getTickLabelFont(category), getTickLabelPaint(category), width,
1277                this.maximumCategoryLabelLines, new G2TextMeasurer(g2));
1278        return label;
1279    }
1280
1281    /**
1282     * A utility method for determining the width of a text block.
1283     *
1284     * @param block  the text block.
1285     * @param position  the position.
1286     * @param g2  the graphics device.
1287     *
1288     * @return The width.
1289     */
1290    protected double calculateTextBlockWidth(TextBlock block,
1291            CategoryLabelPosition position, Graphics2D g2) {
1292        RectangleInsets insets = getTickLabelInsets();
1293        Size2D size = block.calculateDimensions(g2);
1294        Rectangle2D box = new Rectangle2D.Double(0.0, 0.0, size.getWidth(),
1295                size.getHeight());
1296        Shape rotatedBox = ShapeUtils.rotateShape(box, position.getAngle(),
1297                0.0f, 0.0f);
1298        double w = rotatedBox.getBounds2D().getWidth() + insets.getLeft()
1299                + insets.getRight();
1300        return w;
1301    }
1302
1303    /**
1304     * A utility method for determining the height of a text block.
1305     *
1306     * @param block  the text block.
1307     * @param position  the label position.
1308     * @param g2  the graphics device.
1309     *
1310     * @return The height.
1311     */
1312    protected double calculateTextBlockHeight(TextBlock block,
1313            CategoryLabelPosition position, Graphics2D g2) {
1314        RectangleInsets insets = getTickLabelInsets();
1315        Size2D size = block.calculateDimensions(g2);
1316        Rectangle2D box = new Rectangle2D.Double(0.0, 0.0, size.getWidth(),
1317                size.getHeight());
1318        Shape rotatedBox = ShapeUtils.rotateShape(box, position.getAngle(),
1319                0.0f, 0.0f);
1320        double h = rotatedBox.getBounds2D().getHeight()
1321                   + insets.getTop() + insets.getBottom();
1322        return h;
1323    }
1324
1325    /**
1326     * Creates a clone of the axis.
1327     *
1328     * @return A clone.
1329     *
1330     * @throws CloneNotSupportedException if some component of the axis does
1331     *         not support cloning.
1332     */
1333    @Override
1334    public Object clone() throws CloneNotSupportedException {
1335        CategoryAxis clone = (CategoryAxis) super.clone();
1336        clone.tickLabelFontMap = new HashMap(this.tickLabelFontMap);
1337        clone.tickLabelPaintMap = new HashMap(this.tickLabelPaintMap);
1338        clone.categoryLabelToolTips = new HashMap(this.categoryLabelToolTips);
1339        clone.categoryLabelURLs = new HashMap(this.categoryLabelToolTips);
1340        return clone;
1341    }
1342
1343    /**
1344     * Tests this axis for equality with an arbitrary object.
1345     *
1346     * @param obj  the object ({@code null} permitted).
1347     *
1348     * @return A boolean.
1349     */
1350    @Override
1351    public boolean equals(Object obj) {
1352        if (obj == this) {
1353            return true;
1354        }
1355        if (!(obj instanceof CategoryAxis)) {
1356            return false;
1357        }
1358        if (!super.equals(obj)) {
1359            return false;
1360        }
1361        CategoryAxis that = (CategoryAxis) obj;
1362        if (that.lowerMargin != this.lowerMargin) {
1363            return false;
1364        }
1365        if (that.upperMargin != this.upperMargin) {
1366            return false;
1367        }
1368        if (that.categoryMargin != this.categoryMargin) {
1369            return false;
1370        }
1371        if (that.maximumCategoryLabelWidthRatio
1372                != this.maximumCategoryLabelWidthRatio) {
1373            return false;
1374        }
1375        if (that.categoryLabelPositionOffset
1376                != this.categoryLabelPositionOffset) {
1377            return false;
1378        }
1379        if (!ObjectUtils.equal(that.categoryLabelPositions,
1380                this.categoryLabelPositions)) {
1381            return false;
1382        }
1383        if (!ObjectUtils.equal(that.categoryLabelToolTips,
1384                this.categoryLabelToolTips)) {
1385            return false;
1386        }
1387        if (!ObjectUtils.equal(this.categoryLabelURLs, 
1388                that.categoryLabelURLs)) {
1389            return false;
1390        }
1391        if (!ObjectUtils.equal(this.tickLabelFontMap,
1392                that.tickLabelFontMap)) {
1393            return false;
1394        }
1395        if (!equalPaintMaps(this.tickLabelPaintMap, that.tickLabelPaintMap)) {
1396            return false;
1397        }
1398        return true;
1399    }
1400
1401    /**
1402     * Returns a hash code for this object.
1403     *
1404     * @return A hash code.
1405     */
1406    @Override
1407    public int hashCode() {
1408        return super.hashCode();
1409    }
1410
1411    /**
1412     * Provides serialization support.
1413     *
1414     * @param stream  the output stream.
1415     *
1416     * @throws IOException  if there is an I/O error.
1417     */
1418    private void writeObject(ObjectOutputStream stream) throws IOException {
1419        stream.defaultWriteObject();
1420        writePaintMap(this.tickLabelPaintMap, stream);
1421    }
1422
1423    /**
1424     * Provides serialization support.
1425     *
1426     * @param stream  the input stream.
1427     *
1428     * @throws IOException  if there is an I/O error.
1429     * @throws ClassNotFoundException  if there is a classpath problem.
1430     */
1431    private void readObject(ObjectInputStream stream)
1432        throws IOException, ClassNotFoundException {
1433        stream.defaultReadObject();
1434        this.tickLabelPaintMap = readPaintMap(stream);
1435    }
1436
1437    /**
1438     * Reads a {@code Map} of ({@code Comparable}, {@code Paint})
1439     * elements from a stream.
1440     *
1441     * @param in  the input stream.
1442     *
1443     * @return The map.
1444     *
1445     * @throws IOException
1446     * @throws ClassNotFoundException
1447     *
1448     * @see #writePaintMap(Map, ObjectOutputStream)
1449     */
1450    private Map readPaintMap(ObjectInputStream in)
1451            throws IOException, ClassNotFoundException {
1452        boolean isNull = in.readBoolean();
1453        if (isNull) {
1454            return null;
1455        }
1456        Map result = new HashMap();
1457        int count = in.readInt();
1458        for (int i = 0; i < count; i++) {
1459            Comparable category = (Comparable) in.readObject();
1460            Paint paint = SerialUtils.readPaint(in);
1461            result.put(category, paint);
1462        }
1463        return result;
1464    }
1465
1466    /**
1467     * Writes a map of ({@code Comparable}, {@code Paint})
1468     * elements to a stream.
1469     *
1470     * @param map  the map ({@code null} permitted).
1471     *
1472     * @param out
1473     * @throws IOException
1474     *
1475     * @see #readPaintMap(ObjectInputStream)
1476     */
1477    private void writePaintMap(Map map, ObjectOutputStream out)
1478            throws IOException {
1479        if (map == null) {
1480            out.writeBoolean(true);
1481        }
1482        else {
1483            out.writeBoolean(false);
1484            Set keys = map.keySet();
1485            int count = keys.size();
1486            out.writeInt(count);
1487            Iterator iterator = keys.iterator();
1488            while (iterator.hasNext()) {
1489                Comparable key = (Comparable) iterator.next();
1490                out.writeObject(key);
1491                SerialUtils.writePaint((Paint) map.get(key), out);
1492            }
1493        }
1494    }
1495
1496    /**
1497     * Tests two maps containing ({@code Comparable}, {@code Paint})
1498     * elements for equality.
1499     *
1500     * @param map1  the first map ({@code null} not permitted).
1501     * @param map2  the second map ({@code null} not permitted).
1502     *
1503     * @return A boolean.
1504     */
1505    private boolean equalPaintMaps(Map map1, Map map2) {
1506        if (map1.size() != map2.size()) {
1507            return false;
1508        }
1509        Set entries = map1.entrySet();
1510        Iterator iterator = entries.iterator();
1511        while (iterator.hasNext()) {
1512            Map.Entry entry = (Map.Entry) iterator.next();
1513            Paint p1 = (Paint) entry.getValue();
1514            Paint p2 = (Paint) map2.get(entry.getKey());
1515            if (!PaintUtils.equal(p1, p2)) {
1516                return false;
1517            }
1518        }
1519        return true;
1520    }
1521
1522}