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