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 * DateAxis.java
029 * -------------
030 * (C) Copyright 2000-2008, by Object Refinery Limited and Contributors.
031 *
032 * Original Author: David Gilbert;
033 * Contributor(s): Jonathan Nash;
034 * David Li;
035 * Michael Rauch;
036 * Bill Kelemen;
037 * Pawel Pabis;
038 * Chris Boek;
039 * Peter Kolb (patch 1934255);
040 * Andrew Mickish (patch 1870189);
041 * Fawad Halim (bug 2201869);
042 *
043 * Changes (from 23-Jun-2001)
044 * --------------------------
045 * 23-Jun-2001 : Modified to work with null data source (DG);
046 * 18-Sep-2001 : Updated header (DG);
047 * 27-Nov-2001 : Changed constructors from public to protected, updated Javadoc
048 * comments (DG);
049 * 16-Jan-2002 : Added an optional crosshair, based on the implementation by
050 * Jonathan Nash (DG);
051 * 26-Feb-2002 : Updated import statements (DG);
052 * 22-Apr-2002 : Added a setRange() method (DG);
053 * 25-Jun-2002 : Removed redundant local variable (DG);
054 * 25-Jul-2002 : Changed order of parameters in ValueAxis constructor (DG);
055 * 21-Aug-2002 : The setTickUnit() method now turns off auto-tick unit
056 * selection (fix for bug id 528885) (DG);
057 * 05-Sep-2002 : Updated the constructors to reflect changes in the Axis
058 * class (DG);
059 * 18-Sep-2002 : Fixed errors reported by Checkstyle (DG);
060 * 25-Sep-2002 : Added new setRange() methods, and deprecated
061 * setAxisRange() (DG);
062 * 04-Oct-2002 : Changed auto tick selection to parallel number axis
063 * classes (DG);
064 * 24-Oct-2002 : Added a date format override (DG);
065 * 08-Nov-2002 : Moved to new package com.jrefinery.chart.axis (DG);
066 * 14-Jan-2003 : Changed autoRangeMinimumSize from Number --> double, moved
067 * crosshair settings to the plot (DG);
068 * 15-Jan-2003 : Removed anchor date (DG);
069 * 20-Jan-2003 : Removed unnecessary constructors (DG);
070 * 26-Mar-2003 : Implemented Serializable (DG);
071 * 02-May-2003 : Added additional units to createStandardDateTickUnits()
072 * method, as suggested by mhilpert in bug report 723187 (DG);
073 * 13-May-2003 : Merged HorizontalDateAxis and VerticalDateAxis (DG);
074 * 24-May-2003 : Added support for underlying timeline for
075 * SegmentedTimeline (BK);
076 * 16-Jul-2003 : Applied patch from Pawel Pabis to fix overlapping dates (DG);
077 * 22-Jul-2003 : Applied patch from Pawel Pabis for monthly ticks (DG);
078 * 25-Jul-2003 : Fixed bug 777561 and 777586 (DG);
079 * 13-Aug-2003 : Implemented Cloneable and added equals() method (DG);
080 * 02-Sep-2003 : Fixes for bug report 790506 (DG);
081 * 04-Sep-2003 : Fixed tick label alignment when axis appears at the top (DG);
082 * 10-Sep-2003 : Fixes for segmented timeline (DG);
083 * 17-Sep-2003 : Fixed a layout bug when multiple domain axes are used (DG);
084 * 29-Oct-2003 : Added workaround for font alignment in PDF output (DG);
085 * 07-Nov-2003 : Modified to use new tick classes (DG);
086 * 12-Nov-2003 : Modified tick labelling to use roll unit from DateTickUnit
087 * when a calculated tick value is hidden (which can occur in
088 * segmented date axes) (DG);
089 * 24-Nov-2003 : Fixed some problems with the auto tick unit selection, and
090 * fixed bug 846277 (labels missing for inverted axis) (DG);
091 * 30-Dec-2003 : Fixed bug in refreshTicksHorizontal() when start of time unit
092 * (ex. 1st of month) was hidden, causing infinite loop (BK);
093 * 13-Jan-2004 : Fixed bug in previousStandardDate() method (fix by Richard
094 * Wardle) (DG);
095 * 21-Jan-2004 : Renamed translateJava2DToValue --> java2DToValue, and
096 * translateValueToJava2D --> valueToJava2D (DG);
097 * 12-Mar-2004 : Fixed bug where date format override is ignored for vertical
098 * axis (DG);
099 * 16-Mar-2004 : Added plotState to draw() method (DG);
100 * 07-Apr-2004 : Changed string width calculation (DG);
101 * 21-Apr-2004 : Fixed bug in estimateMaximumTickLabelWidth() method (bug id
102 * 939148) (DG);
103 * 11-Jan-2005 : Removed deprecated methods in preparation for 1.0.0
104 * release (DG);
105 * 13-Jan-2005 : Fixed bug (see
106 * http://www.jfree.org/forum/viewtopic.php?t=11330) (DG);
107 * 21-Apr-2005 : Replaced Insets with RectangleInsets, removed redundant
108 * argument from selectAutoTickUnit() (DG);
109 * ------------- JFREECHART 1.0.x ---------------------------------------------
110 * 10-Feb-2006 : Added some API doc comments in respect of bug 821046 (DG);
111 * 19-Apr-2006 : Fixed bug 1472942 in equals() method (DG);
112 * 25-Sep-2006 : Fixed bug 1564977 missing tick labels (DG);
113 * 15-Jan-2007 : Added get/setTimeZone() suggested by 'skunk' (DG);
114 * 18-Jan-2007 : Fixed bug 1638678, time zone for calendar in
115 * previousStandardDate() (DG);
116 * 04-Apr-2007 : Use time zone in date calculations (CB);
117 * 19-Apr-2007 : Fix exceptions in setMinimum/MaximumDate() (DG);
118 * 03-May-2007 : Fixed minor bugs in previousStandardDate(), with new JUnit
119 * tests (DG);
120 * 21-Nov-2007 : Fixed warnings from FindBugs (DG);
121 * 01-Sep-2008 : Use new methods from DateRange, added fix for bug
122 * 2078057 (DG);
123 * 18-Sep-2008 : Added locale to go with timezone (DG);
124 * 25-Sep-2008 : Added minor tick support, see patch 1934255 by Peter Kolb (DG);
125 * 25-Nov-2008 : Added bug fix 2201869 by Fawad Halim (DG);
126 *
127 */
128
129 package org.jfree.chart.axis;
130
131 import java.awt.Font;
132 import java.awt.FontMetrics;
133 import java.awt.Graphics2D;
134 import java.awt.font.FontRenderContext;
135 import java.awt.font.LineMetrics;
136 import java.awt.geom.Rectangle2D;
137 import java.io.Serializable;
138 import java.text.DateFormat;
139 import java.text.SimpleDateFormat;
140 import java.util.Calendar;
141 import java.util.Date;
142 import java.util.List;
143 import java.util.Locale;
144 import java.util.TimeZone;
145
146 import org.jfree.chart.event.AxisChangeEvent;
147 import org.jfree.chart.plot.Plot;
148 import org.jfree.chart.plot.PlotRenderingInfo;
149 import org.jfree.chart.plot.ValueAxisPlot;
150 import org.jfree.data.Range;
151 import org.jfree.data.time.DateRange;
152 import org.jfree.data.time.Month;
153 import org.jfree.data.time.RegularTimePeriod;
154 import org.jfree.data.time.Year;
155 import org.jfree.ui.RectangleEdge;
156 import org.jfree.ui.RectangleInsets;
157 import org.jfree.ui.TextAnchor;
158 import org.jfree.util.ObjectUtilities;
159
160 /**
161 * The base class for axes that display dates. You will find it easier to
162 * understand how this axis works if you bear in mind that it really
163 * displays/measures integer (or long) data, where the integers are
164 * milliseconds since midnight, 1-Jan-1970. When displaying tick labels, the
165 * millisecond values are converted back to dates using a
166 * <code>DateFormat</code> instance.
167 * <P>
168 * You can also create a {@link org.jfree.chart.axis.Timeline} and supply in
169 * the constructor to create an axis that only contains certain domain values.
170 * For example, this allows you to create a date axis that only contains
171 * working days.
172 */
173 public class DateAxis extends ValueAxis implements Cloneable, Serializable {
174
175 /** For serialization. */
176 private static final long serialVersionUID = -1013460999649007604L;
177
178 /** The default axis range. */
179 public static final DateRange DEFAULT_DATE_RANGE = new DateRange();
180
181 /** The default minimum auto range size. */
182 public static final double
183 DEFAULT_AUTO_RANGE_MINIMUM_SIZE_IN_MILLISECONDS = 2.0;
184
185 /** The default date tick unit. */
186 public static final DateTickUnit DEFAULT_DATE_TICK_UNIT
187 = new DateTickUnit(DateTickUnit.DAY, 1, new SimpleDateFormat());
188
189 /** The default anchor date. */
190 public static final Date DEFAULT_ANCHOR_DATE = new Date();
191
192 /** The current tick unit. */
193 private DateTickUnit tickUnit;
194
195 /** The override date format. */
196 private DateFormat dateFormatOverride;
197
198 /**
199 * Tick marks can be displayed at the start or the middle of the time
200 * period.
201 */
202 private DateTickMarkPosition tickMarkPosition = DateTickMarkPosition.START;
203
204 /**
205 * A timeline that includes all milliseconds (as defined by
206 * <code>java.util.Date</code>) in the real time line.
207 */
208 private static class DefaultTimeline implements Timeline, Serializable {
209
210 /**
211 * Converts a millisecond into a timeline value.
212 *
213 * @param millisecond the millisecond.
214 *
215 * @return The timeline value.
216 */
217 public long toTimelineValue(long millisecond) {
218 return millisecond;
219 }
220
221 /**
222 * Converts a date into a timeline value.
223 *
224 * @param date the domain value.
225 *
226 * @return The timeline value.
227 */
228 public long toTimelineValue(Date date) {
229 return date.getTime();
230 }
231
232 /**
233 * Converts a timeline value into a millisecond (as encoded by
234 * <code>java.util.Date</code>).
235 *
236 * @param value the value.
237 *
238 * @return The millisecond.
239 */
240 public long toMillisecond(long value) {
241 return value;
242 }
243
244 /**
245 * Returns <code>true</code> if the timeline includes the specified
246 * domain value.
247 *
248 * @param millisecond the millisecond.
249 *
250 * @return <code>true</code>.
251 */
252 public boolean containsDomainValue(long millisecond) {
253 return true;
254 }
255
256 /**
257 * Returns <code>true</code> if the timeline includes the specified
258 * domain value.
259 *
260 * @param date the date.
261 *
262 * @return <code>true</code>.
263 */
264 public boolean containsDomainValue(Date date) {
265 return true;
266 }
267
268 /**
269 * Returns <code>true</code> if the timeline includes the specified
270 * domain value range.
271 *
272 * @param from the start value.
273 * @param to the end value.
274 *
275 * @return <code>true</code>.
276 */
277 public boolean containsDomainRange(long from, long to) {
278 return true;
279 }
280
281 /**
282 * Returns <code>true</code> if the timeline includes the specified
283 * domain value range.
284 *
285 * @param from the start date.
286 * @param to the end date.
287 *
288 * @return <code>true</code>.
289 */
290 public boolean containsDomainRange(Date from, Date to) {
291 return true;
292 }
293
294 /**
295 * Tests an object for equality with this instance.
296 *
297 * @param object the object.
298 *
299 * @return A boolean.
300 */
301 public boolean equals(Object object) {
302 if (object == null) {
303 return false;
304 }
305 if (object == this) {
306 return true;
307 }
308 if (object instanceof DefaultTimeline) {
309 return true;
310 }
311 return false;
312 }
313 }
314
315 /** A static default timeline shared by all standard DateAxis */
316 private static final Timeline DEFAULT_TIMELINE = new DefaultTimeline();
317
318 /** The time zone for the axis. */
319 private TimeZone timeZone;
320
321 /**
322 * The locale for the axis (<code>null</code> is not permitted).
323 *
324 * @since 1.0.11
325 */
326 private Locale locale;
327
328 /** Our underlying timeline. */
329 private Timeline timeline;
330
331 /**
332 * Creates a date axis with no label.
333 */
334 public DateAxis() {
335 this(null);
336 }
337
338 /**
339 * Creates a date axis with the specified label.
340 *
341 * @param label the axis label (<code>null</code> permitted).
342 */
343 public DateAxis(String label) {
344 this(label, TimeZone.getDefault());
345 }
346
347 /**
348 * Creates a date axis. A timeline is specified for the axis. This allows
349 * special transformations to occur between a domain of values and the
350 * values included in the axis.
351 *
352 * @see org.jfree.chart.axis.SegmentedTimeline
353 *
354 * @param label the axis label (<code>null</code> permitted).
355 * @param zone the time zone.
356 *
357 * @deprecated From 1.0.11 onwards, use {@link #DateAxis(String, TimeZone,
358 * Locale)} instead, to explicitly set the locale.
359 */
360 public DateAxis(String label, TimeZone zone) {
361 this(label, zone, Locale.getDefault());
362 }
363
364 /**
365 * Creates a date axis. A timeline is specified for the axis. This allows
366 * special transformations to occur between a domain of values and the
367 * values included in the axis.
368 *
369 * @see org.jfree.chart.axis.SegmentedTimeline
370 *
371 * @param label the axis label (<code>null</code> permitted).
372 * @param zone the time zone.
373 * @param locale the locale (<code>null</code> not permitted).
374 *
375 * @since 1.0.11
376 */
377 public DateAxis(String label, TimeZone zone, Locale locale) {
378 super(label, DateAxis.createStandardDateTickUnits(zone, locale));
379 setTickUnit(DateAxis.DEFAULT_DATE_TICK_UNIT, false, false);
380 setAutoRangeMinimumSize(
381 DEFAULT_AUTO_RANGE_MINIMUM_SIZE_IN_MILLISECONDS);
382 setRange(DEFAULT_DATE_RANGE, false, false);
383 this.dateFormatOverride = null;
384 this.timeZone = zone;
385 this.locale = locale;
386 this.timeline = DEFAULT_TIMELINE;
387 }
388
389 /**
390 * Returns the time zone for the axis.
391 *
392 * @return The time zone (never <code>null</code>).
393 *
394 * @since 1.0.4
395 *
396 * @see #setTimeZone(TimeZone)
397 */
398 public TimeZone getTimeZone() {
399 return this.timeZone;
400 }
401
402 /**
403 * Sets the time zone for the axis and sends an {@link AxisChangeEvent} to
404 * all registered listeners.
405 *
406 * @param zone the time zone (<code>null</code> not permitted).
407 *
408 * @since 1.0.4
409 *
410 * @see #getTimeZone()
411 */
412 public void setTimeZone(TimeZone zone) {
413 if (zone == null) {
414 throw new IllegalArgumentException("Null 'zone' argument.");
415 }
416 if (!this.timeZone.equals(zone)) {
417 this.timeZone = zone;
418 setStandardTickUnits(createStandardDateTickUnits(zone,
419 this.locale));
420 notifyListeners(new AxisChangeEvent(this));
421 }
422 }
423
424 /**
425 * Returns the underlying timeline used by this axis.
426 *
427 * @return The timeline.
428 */
429 public Timeline getTimeline() {
430 return this.timeline;
431 }
432
433 /**
434 * Sets the underlying timeline to use for this axis.
435 * <P>
436 * If the timeline is changed, an {@link AxisChangeEvent} is sent to all
437 * registered listeners.
438 *
439 * @param timeline the timeline.
440 */
441 public void setTimeline(Timeline timeline) {
442 if (this.timeline != timeline) {
443 this.timeline = timeline;
444 notifyListeners(new AxisChangeEvent(this));
445 }
446 }
447
448 /**
449 * Returns the tick unit for the axis.
450 * <p>
451 * Note: if the <code>autoTickUnitSelection</code> flag is
452 * <code>true</code> the tick unit may be changed while the axis is being
453 * drawn, so in that case the return value from this method may be
454 * irrelevant if the method is called before the axis has been drawn.
455 *
456 * @return The tick unit (possibly <code>null</code>).
457 *
458 * @see #setTickUnit(DateTickUnit)
459 * @see ValueAxis#isAutoTickUnitSelection()
460 */
461 public DateTickUnit getTickUnit() {
462 return this.tickUnit;
463 }
464
465 /**
466 * Sets the tick unit for the axis. The auto-tick-unit-selection flag is
467 * set to <code>false</code>, and registered listeners are notified that
468 * the axis has been changed.
469 *
470 * @param unit the tick unit.
471 *
472 * @see #getTickUnit()
473 * @see #setTickUnit(DateTickUnit, boolean, boolean)
474 */
475 public void setTickUnit(DateTickUnit unit) {
476 setTickUnit(unit, true, true);
477 }
478
479 /**
480 * Sets the tick unit attribute.
481 *
482 * @param unit the new tick unit.
483 * @param notify notify registered listeners?
484 * @param turnOffAutoSelection turn off auto selection?
485 *
486 * @see #getTickUnit()
487 */
488 public void setTickUnit(DateTickUnit unit, boolean notify,
489 boolean turnOffAutoSelection) {
490
491 this.tickUnit = unit;
492 if (turnOffAutoSelection) {
493 setAutoTickUnitSelection(false, false);
494 }
495 if (notify) {
496 notifyListeners(new AxisChangeEvent(this));
497 }
498
499 }
500
501 /**
502 * Returns the date format override. If this is non-null, then it will be
503 * used to format the dates on the axis.
504 *
505 * @return The formatter (possibly <code>null</code>).
506 */
507 public DateFormat getDateFormatOverride() {
508 return this.dateFormatOverride;
509 }
510
511 /**
512 * Sets the date format override. If this is non-null, then it will be
513 * used to format the dates on the axis.
514 *
515 * @param formatter the date formatter (<code>null</code> permitted).
516 */
517 public void setDateFormatOverride(DateFormat formatter) {
518 this.dateFormatOverride = formatter;
519 notifyListeners(new AxisChangeEvent(this));
520 }
521
522 /**
523 * Sets the upper and lower bounds for the axis and sends an
524 * {@link AxisChangeEvent} to all registered listeners. As a side-effect,
525 * the auto-range flag is set to false.
526 *
527 * @param range the new range (<code>null</code> not permitted).
528 */
529 public void setRange(Range range) {
530 setRange(range, true, true);
531 }
532
533 /**
534 * Sets the range for the axis, if requested, sends an
535 * {@link AxisChangeEvent} to all registered listeners. As a side-effect,
536 * the auto-range flag is set to <code>false</code> (optional).
537 *
538 * @param range the range (<code>null</code> not permitted).
539 * @param turnOffAutoRange a flag that controls whether or not the auto
540 * range is turned off.
541 * @param notify a flag that controls whether or not listeners are
542 * notified.
543 */
544 public void setRange(Range range, boolean turnOffAutoRange,
545 boolean notify) {
546 if (range == null) {
547 throw new IllegalArgumentException("Null 'range' argument.");
548 }
549 // usually the range will be a DateRange, but if it isn't do a
550 // conversion...
551 if (!(range instanceof DateRange)) {
552 range = new DateRange(range);
553 }
554 super.setRange(range, turnOffAutoRange, notify);
555 }
556
557 /**
558 * Sets the axis range and sends an {@link AxisChangeEvent} to all
559 * registered listeners.
560 *
561 * @param lower the lower bound for the axis.
562 * @param upper the upper bound for the axis.
563 */
564 public void setRange(Date lower, Date upper) {
565 if (lower.getTime() >= upper.getTime()) {
566 throw new IllegalArgumentException("Requires 'lower' < 'upper'.");
567 }
568 setRange(new DateRange(lower, upper));
569 }
570
571 /**
572 * Sets the axis range and sends an {@link AxisChangeEvent} to all
573 * registered listeners.
574 *
575 * @param lower the lower bound for the axis.
576 * @param upper the upper bound for the axis.
577 */
578 public void setRange(double lower, double upper) {
579 if (lower >= upper) {
580 throw new IllegalArgumentException("Requires 'lower' < 'upper'.");
581 }
582 setRange(new DateRange(lower, upper));
583 }
584
585 /**
586 * Returns the earliest date visible on the axis.
587 *
588 * @return The date.
589 *
590 * @see #setMinimumDate(Date)
591 * @see #getMaximumDate()
592 */
593 public Date getMinimumDate() {
594 Date result = null;
595 Range range = getRange();
596 if (range instanceof DateRange) {
597 DateRange r = (DateRange) range;
598 result = r.getLowerDate();
599 }
600 else {
601 result = new Date((long) range.getLowerBound());
602 }
603 return result;
604 }
605
606 /**
607 * Sets the minimum date visible on the axis and sends an
608 * {@link AxisChangeEvent} to all registered listeners. If
609 * <code>date</code> is on or after the current maximum date for
610 * the axis, the maximum date will be shifted to preserve the current
611 * length of the axis.
612 *
613 * @param date the date (<code>null</code> not permitted).
614 *
615 * @see #getMinimumDate()
616 * @see #setMaximumDate(Date)
617 */
618 public void setMinimumDate(Date date) {
619 if (date == null) {
620 throw new IllegalArgumentException("Null 'date' argument.");
621 }
622 // check the new minimum date relative to the current maximum date
623 Date maxDate = getMaximumDate();
624 long maxMillis = maxDate.getTime();
625 long newMinMillis = date.getTime();
626 if (maxMillis <= newMinMillis) {
627 Date oldMin = getMinimumDate();
628 long length = maxMillis - oldMin.getTime();
629 maxDate = new Date(newMinMillis + length);
630 }
631 setRange(new DateRange(date, maxDate), true, false);
632 notifyListeners(new AxisChangeEvent(this));
633 }
634
635 /**
636 * Returns the latest date visible on the axis.
637 *
638 * @return The date.
639 *
640 * @see #setMaximumDate(Date)
641 * @see #getMinimumDate()
642 */
643 public Date getMaximumDate() {
644 Date result = null;
645 Range range = getRange();
646 if (range instanceof DateRange) {
647 DateRange r = (DateRange) range;
648 result = r.getUpperDate();
649 }
650 else {
651 result = new Date((long) range.getUpperBound());
652 }
653 return result;
654 }
655
656 /**
657 * Sets the maximum date visible on the axis and sends an
658 * {@link AxisChangeEvent} to all registered listeners. If
659 * <code>maximumDate</code> is on or before the current minimum date for
660 * the axis, the minimum date will be shifted to preserve the current
661 * length of the axis.
662 *
663 * @param maximumDate the date (<code>null</code> not permitted).
664 *
665 * @see #getMinimumDate()
666 * @see #setMinimumDate(Date)
667 */
668 public void setMaximumDate(Date maximumDate) {
669 if (maximumDate == null) {
670 throw new IllegalArgumentException("Null 'maximumDate' argument.");
671 }
672 // check the new maximum date relative to the current minimum date
673 Date minDate = getMinimumDate();
674 long minMillis = minDate.getTime();
675 long newMaxMillis = maximumDate.getTime();
676 if (minMillis >= newMaxMillis) {
677 Date oldMax = getMaximumDate();
678 long length = oldMax.getTime() - minMillis;
679 minDate = new Date(newMaxMillis - length);
680 }
681 setRange(new DateRange(minDate, maximumDate), true, false);
682 notifyListeners(new AxisChangeEvent(this));
683 }
684
685 /**
686 * Returns the tick mark position (start, middle or end of the time period).
687 *
688 * @return The position (never <code>null</code>).
689 */
690 public DateTickMarkPosition getTickMarkPosition() {
691 return this.tickMarkPosition;
692 }
693
694 /**
695 * Sets the tick mark position (start, middle or end of the time period)
696 * and sends an {@link AxisChangeEvent} to all registered listeners.
697 *
698 * @param position the position (<code>null</code> not permitted).
699 */
700 public void setTickMarkPosition(DateTickMarkPosition position) {
701 if (position == null) {
702 throw new IllegalArgumentException("Null 'position' argument.");
703 }
704 this.tickMarkPosition = position;
705 notifyListeners(new AxisChangeEvent(this));
706 }
707
708 /**
709 * Configures the axis to work with the specified plot. If the axis has
710 * auto-scaling, then sets the maximum and minimum values.
711 */
712 public void configure() {
713 if (isAutoRange()) {
714 autoAdjustRange();
715 }
716 }
717
718 /**
719 * Returns <code>true</code> if the axis hides this value, and
720 * <code>false</code> otherwise.
721 *
722 * @param millis the data value.
723 *
724 * @return A value.
725 */
726 public boolean isHiddenValue(long millis) {
727 return (!this.timeline.containsDomainValue(new Date(millis)));
728 }
729
730 /**
731 * Translates the data value to the display coordinates (Java 2D User Space)
732 * of the chart.
733 *
734 * @param value the date to be plotted.
735 * @param area the rectangle (in Java2D space) where the data is to be
736 * plotted.
737 * @param edge the axis location.
738 *
739 * @return The coordinate corresponding to the supplied data value.
740 */
741 public double valueToJava2D(double value, Rectangle2D area,
742 RectangleEdge edge) {
743
744 value = this.timeline.toTimelineValue((long) value);
745
746 DateRange range = (DateRange) getRange();
747 double axisMin = this.timeline.toTimelineValue(range.getLowerMillis());
748 double axisMax = this.timeline.toTimelineValue(range.getUpperMillis());
749 double result = 0.0;
750 if (RectangleEdge.isTopOrBottom(edge)) {
751 double minX = area.getX();
752 double maxX = area.getMaxX();
753 if (isInverted()) {
754 result = maxX + ((value - axisMin) / (axisMax - axisMin))
755 * (minX - maxX);
756 }
757 else {
758 result = minX + ((value - axisMin) / (axisMax - axisMin))
759 * (maxX - minX);
760 }
761 }
762 else if (RectangleEdge.isLeftOrRight(edge)) {
763 double minY = area.getMinY();
764 double maxY = area.getMaxY();
765 if (isInverted()) {
766 result = minY + (((value - axisMin) / (axisMax - axisMin))
767 * (maxY - minY));
768 }
769 else {
770 result = maxY - (((value - axisMin) / (axisMax - axisMin))
771 * (maxY - minY));
772 }
773 }
774 return result;
775
776 }
777
778 /**
779 * Translates a date to Java2D coordinates, based on the range displayed by
780 * this axis for the specified data area.
781 *
782 * @param date the date.
783 * @param area the rectangle (in Java2D space) where the data is to be
784 * plotted.
785 * @param edge the axis location.
786 *
787 * @return The coordinate corresponding to the supplied date.
788 */
789 public double dateToJava2D(Date date, Rectangle2D area,
790 RectangleEdge edge) {
791 double value = date.getTime();
792 return valueToJava2D(value, area, edge);
793 }
794
795 /**
796 * Translates a Java2D coordinate into the corresponding data value. To
797 * perform this translation, you need to know the area used for plotting
798 * data, and which edge the axis is located on.
799 *
800 * @param java2DValue the coordinate in Java2D space.
801 * @param area the rectangle (in Java2D space) where the data is to be
802 * plotted.
803 * @param edge the axis location.
804 *
805 * @return A data value.
806 */
807 public double java2DToValue(double java2DValue, Rectangle2D area,
808 RectangleEdge edge) {
809
810 DateRange range = (DateRange) getRange();
811 double axisMin = this.timeline.toTimelineValue(range.getLowerMillis());
812 double axisMax = this.timeline.toTimelineValue(range.getUpperMillis());
813
814 double min = 0.0;
815 double max = 0.0;
816 if (RectangleEdge.isTopOrBottom(edge)) {
817 min = area.getX();
818 max = area.getMaxX();
819 }
820 else if (RectangleEdge.isLeftOrRight(edge)) {
821 min = area.getMaxY();
822 max = area.getY();
823 }
824
825 double result;
826 if (isInverted()) {
827 result = axisMax - ((java2DValue - min) / (max - min)
828 * (axisMax - axisMin));
829 }
830 else {
831 result = axisMin + ((java2DValue - min) / (max - min)
832 * (axisMax - axisMin));
833 }
834
835 return this.timeline.toMillisecond((long) result);
836 }
837
838 /**
839 * Calculates the value of the lowest visible tick on the axis.
840 *
841 * @param unit date unit to use.
842 *
843 * @return The value of the lowest visible tick on the axis.
844 */
845 public Date calculateLowestVisibleTickValue(DateTickUnit unit) {
846 return nextStandardDate(getMinimumDate(), unit);
847 }
848
849 /**
850 * Calculates the value of the highest visible tick on the axis.
851 *
852 * @param unit date unit to use.
853 *
854 * @return The value of the highest visible tick on the axis.
855 */
856 public Date calculateHighestVisibleTickValue(DateTickUnit unit) {
857 return previousStandardDate(getMaximumDate(), unit);
858 }
859
860 /**
861 * Returns the previous "standard" date, for a given date and tick unit.
862 *
863 * @param date the reference date.
864 * @param unit the tick unit.
865 *
866 * @return The previous "standard" date.
867 */
868 protected Date previousStandardDate(Date date, DateTickUnit unit) {
869
870 int milliseconds;
871 int seconds;
872 int minutes;
873 int hours;
874 int days;
875 int months;
876 int years;
877
878 Calendar calendar = Calendar.getInstance(this.timeZone, this.locale);
879 calendar.setTime(date);
880 int count = unit.getCount();
881 int current = calendar.get(unit.getCalendarField());
882 int value = count * (current / count);
883
884 switch (unit.getUnit()) {
885
886 case (DateTickUnit.MILLISECOND) :
887 years = calendar.get(Calendar.YEAR);
888 months = calendar.get(Calendar.MONTH);
889 days = calendar.get(Calendar.DATE);
890 hours = calendar.get(Calendar.HOUR_OF_DAY);
891 minutes = calendar.get(Calendar.MINUTE);
892 seconds = calendar.get(Calendar.SECOND);
893 calendar.set(years, months, days, hours, minutes, seconds);
894 calendar.set(Calendar.MILLISECOND, value);
895 Date mm = calendar.getTime();
896 if (mm.getTime() >= date.getTime()) {
897 calendar.set(Calendar.MILLISECOND, value - 1);
898 mm = calendar.getTime();
899 }
900 return mm;
901
902 case (DateTickUnit.SECOND) :
903 years = calendar.get(Calendar.YEAR);
904 months = calendar.get(Calendar.MONTH);
905 days = calendar.get(Calendar.DATE);
906 hours = calendar.get(Calendar.HOUR_OF_DAY);
907 minutes = calendar.get(Calendar.MINUTE);
908 if (this.tickMarkPosition == DateTickMarkPosition.START) {
909 milliseconds = 0;
910 }
911 else if (this.tickMarkPosition == DateTickMarkPosition.MIDDLE) {
912 milliseconds = 500;
913 }
914 else {
915 milliseconds = 999;
916 }
917 calendar.set(Calendar.MILLISECOND, milliseconds);
918 calendar.set(years, months, days, hours, minutes, value);
919 Date dd = calendar.getTime();
920 if (dd.getTime() >= date.getTime()) {
921 calendar.set(Calendar.SECOND, value - 1);
922 dd = calendar.getTime();
923 }
924 return dd;
925
926 case (DateTickUnit.MINUTE) :
927 years = calendar.get(Calendar.YEAR);
928 months = calendar.get(Calendar.MONTH);
929 days = calendar.get(Calendar.DATE);
930 hours = calendar.get(Calendar.HOUR_OF_DAY);
931 if (this.tickMarkPosition == DateTickMarkPosition.START) {
932 seconds = 0;
933 }
934 else if (this.tickMarkPosition == DateTickMarkPosition.MIDDLE) {
935 seconds = 30;
936 }
937 else {
938 seconds = 59;
939 }
940 calendar.clear(Calendar.MILLISECOND);
941 calendar.set(years, months, days, hours, value, seconds);
942 Date d0 = calendar.getTime();
943 if (d0.getTime() >= date.getTime()) {
944 calendar.set(Calendar.MINUTE, value - 1);
945 d0 = calendar.getTime();
946 }
947 return d0;
948
949 case (DateTickUnit.HOUR) :
950 years = calendar.get(Calendar.YEAR);
951 months = calendar.get(Calendar.MONTH);
952 days = calendar.get(Calendar.DATE);
953 if (this.tickMarkPosition == DateTickMarkPosition.START) {
954 minutes = 0;
955 seconds = 0;
956 }
957 else if (this.tickMarkPosition == DateTickMarkPosition.MIDDLE) {
958 minutes = 30;
959 seconds = 0;
960 }
961 else {
962 minutes = 59;
963 seconds = 59;
964 }
965 calendar.clear(Calendar.MILLISECOND);
966 calendar.set(years, months, days, value, minutes, seconds);
967 Date d1 = calendar.getTime();
968 if (d1.getTime() >= date.getTime()) {
969 calendar.set(Calendar.HOUR_OF_DAY, value - 1);
970 d1 = calendar.getTime();
971 }
972 return d1;
973
974 case (DateTickUnit.DAY) :
975 years = calendar.get(Calendar.YEAR);
976 months = calendar.get(Calendar.MONTH);
977 if (this.tickMarkPosition == DateTickMarkPosition.START) {
978 hours = 0;
979 minutes = 0;
980 seconds = 0;
981 }
982 else if (this.tickMarkPosition == DateTickMarkPosition.MIDDLE) {
983 hours = 12;
984 minutes = 0;
985 seconds = 0;
986 }
987 else {
988 hours = 23;
989 minutes = 59;
990 seconds = 59;
991 }
992 calendar.clear(Calendar.MILLISECOND);
993 calendar.set(years, months, value, hours, 0, 0);
994 // long result = calendar.getTimeInMillis();
995 // won't work with JDK 1.3
996 Date d2 = calendar.getTime();
997 if (d2.getTime() >= date.getTime()) {
998 calendar.set(Calendar.DATE, value - 1);
999 d2 = calendar.getTime();
1000 }
1001 return d2;
1002
1003 case (DateTickUnit.MONTH) :
1004 years = calendar.get(Calendar.YEAR);
1005 calendar.clear(Calendar.MILLISECOND);
1006 calendar.set(years, value, 1, 0, 0, 0);
1007 Month month = new Month(calendar.getTime(), this.timeZone,
1008 this.locale);
1009 Date standardDate = calculateDateForPosition(
1010 month, this.tickMarkPosition);
1011 long millis = standardDate.getTime();
1012 if (millis >= date.getTime()) {
1013 month = (Month) month.previous();
1014 // need to peg the month in case the time zone isn't the
1015 // default - see bug 2078057
1016 month.peg(Calendar.getInstance(this.timeZone));
1017 standardDate = calculateDateForPosition(
1018 month, this.tickMarkPosition);
1019 }
1020 return standardDate;
1021
1022 case(DateTickUnit.YEAR) :
1023 if (this.tickMarkPosition == DateTickMarkPosition.START) {
1024 months = 0;
1025 days = 1;
1026 }
1027 else if (this.tickMarkPosition == DateTickMarkPosition.MIDDLE) {
1028 months = 6;
1029 days = 1;
1030 }
1031 else {
1032 months = 11;
1033 days = 31;
1034 }
1035 calendar.clear(Calendar.MILLISECOND);
1036 calendar.set(value, months, days, 0, 0, 0);
1037 Date d3 = calendar.getTime();
1038 if (d3.getTime() >= date.getTime()) {
1039 calendar.set(Calendar.YEAR, value - 1);
1040 d3 = calendar.getTime();
1041 }
1042 return d3;
1043
1044 default: return null;
1045
1046 }
1047
1048 }
1049
1050 /**
1051 * Returns a {@link java.util.Date} corresponding to the specified position
1052 * within a {@link RegularTimePeriod}.
1053 *
1054 * @param period the period.
1055 * @param position the position (<code>null</code> not permitted).
1056 *
1057 * @return A date.
1058 */
1059 private Date calculateDateForPosition(RegularTimePeriod period,
1060 DateTickMarkPosition position) {
1061
1062 if (position == null) {
1063 throw new IllegalArgumentException("Null 'position' argument.");
1064 }
1065 Date result = null;
1066 if (position == DateTickMarkPosition.START) {
1067 result = new Date(period.getFirstMillisecond());
1068 }
1069 else if (position == DateTickMarkPosition.MIDDLE) {
1070 result = new Date(period.getMiddleMillisecond());
1071 }
1072 else if (position == DateTickMarkPosition.END) {
1073 result = new Date(period.getLastMillisecond());
1074 }
1075 return result;
1076
1077 }
1078
1079 /**
1080 * Returns the first "standard" date (based on the specified field and
1081 * units).
1082 *
1083 * @param date the reference date.
1084 * @param unit the date tick unit.
1085 *
1086 * @return The next "standard" date.
1087 */
1088 protected Date nextStandardDate(Date date, DateTickUnit unit) {
1089 Date previous = previousStandardDate(date, unit);
1090 Calendar calendar = Calendar.getInstance(this.timeZone, this.locale);
1091 calendar.setTime(previous);
1092 calendar.add(unit.getCalendarField(), unit.getCount());
1093 return calendar.getTime();
1094 }
1095
1096 /**
1097 * Returns a collection of standard date tick units that uses the default
1098 * time zone. This collection will be used by default, but you are free
1099 * to create your own collection if you want to (see the
1100 * {@link ValueAxis#setStandardTickUnits(TickUnitSource)} method inherited
1101 * from the {@link ValueAxis} class).
1102 *
1103 * @return A collection of standard date tick units.
1104 */
1105 public static TickUnitSource createStandardDateTickUnits() {
1106 return createStandardDateTickUnits(TimeZone.getDefault(),
1107 Locale.getDefault());
1108 }
1109
1110 /**
1111 * Returns a collection of standard date tick units. This collection will
1112 * be used by default, but you are free to create your own collection if
1113 * you want to (see the
1114 * {@link ValueAxis#setStandardTickUnits(TickUnitSource)} method inherited
1115 * from the {@link ValueAxis} class).
1116 *
1117 * @param zone the time zone (<code>null</code> not permitted).
1118 *
1119 * @return A collection of standard date tick units.
1120 *
1121 * @deprecated Since 1.0.11, use {@link #createStandardDateTickUnits(
1122 * TimeZone, Locale)} to explicitly set the locale as well as the
1123 * time zone.
1124 */
1125 public static TickUnitSource createStandardDateTickUnits(TimeZone zone) {
1126 return createStandardDateTickUnits(zone, Locale.getDefault());
1127 }
1128
1129 /**
1130 * Returns a collection of standard date tick units. This collection will
1131 * be used by default, but you are free to create your own collection if
1132 * you want to (see the
1133 * {@link ValueAxis#setStandardTickUnits(TickUnitSource)} method inherited
1134 * from the {@link ValueAxis} class).
1135 *
1136 * @param zone the time zone (<code>null</code> not permitted).
1137 * @param locale the locale (<code>null</code> not permitted).
1138 *
1139 * @return A collection of standard date tick units.
1140 *
1141 * @since 1.0.11
1142 */
1143 public static TickUnitSource createStandardDateTickUnits(TimeZone zone,
1144 Locale locale) {
1145
1146 if (zone == null) {
1147 throw new IllegalArgumentException("Null 'zone' argument.");
1148 }
1149 if (locale == null) {
1150 throw new IllegalArgumentException("Null 'locale' argument.");
1151 }
1152 TickUnits units = new TickUnits();
1153
1154 // date formatters
1155 DateFormat f1 = new SimpleDateFormat("HH:mm:ss.SSS", locale);
1156 DateFormat f2 = new SimpleDateFormat("HH:mm:ss", locale);
1157 DateFormat f3 = new SimpleDateFormat("HH:mm", locale);
1158 DateFormat f4 = new SimpleDateFormat("d-MMM, HH:mm", locale);
1159 DateFormat f5 = new SimpleDateFormat("d-MMM", locale);
1160 DateFormat f6 = new SimpleDateFormat("MMM-yyyy", locale);
1161 DateFormat f7 = new SimpleDateFormat("yyyy", locale);
1162
1163 f1.setTimeZone(zone);
1164 f2.setTimeZone(zone);
1165 f3.setTimeZone(zone);
1166 f4.setTimeZone(zone);
1167 f5.setTimeZone(zone);
1168 f6.setTimeZone(zone);
1169 f7.setTimeZone(zone);
1170
1171 // milliseconds
1172 units.add(new DateTickUnit(DateTickUnit.MILLISECOND, 1, f1));
1173 units.add(new DateTickUnit(DateTickUnit.MILLISECOND, 5,
1174 DateTickUnit.MILLISECOND, 1, f1));
1175 units.add(new DateTickUnit(DateTickUnit.MILLISECOND, 10,
1176 DateTickUnit.MILLISECOND, 1, f1));
1177 units.add(new DateTickUnit(DateTickUnit.MILLISECOND, 25,
1178 DateTickUnit.MILLISECOND, 5, f1));
1179 units.add(new DateTickUnit(DateTickUnit.MILLISECOND, 50,
1180 DateTickUnit.MILLISECOND, 10, f1));
1181 units.add(new DateTickUnit(DateTickUnit.MILLISECOND, 100,
1182 DateTickUnit.MILLISECOND, 10, f1));
1183 units.add(new DateTickUnit(DateTickUnit.MILLISECOND, 250,
1184 DateTickUnit.MILLISECOND, 10, f1));
1185 units.add(new DateTickUnit(DateTickUnit.MILLISECOND, 500,
1186 DateTickUnit.MILLISECOND, 50, f1));
1187
1188 // seconds
1189 units.add(new DateTickUnit(DateTickUnit.SECOND, 1,
1190 DateTickUnit.MILLISECOND, 50, f2));
1191 units.add(new DateTickUnit(DateTickUnit.SECOND, 5,
1192 DateTickUnit.SECOND, 1, f2));
1193 units.add(new DateTickUnit(DateTickUnit.SECOND, 10,
1194 DateTickUnit.SECOND, 1, f2));
1195 units.add(new DateTickUnit(DateTickUnit.SECOND, 30,
1196 DateTickUnit.SECOND, 5, f2));
1197
1198 // minutes
1199 units.add(new DateTickUnit(DateTickUnit.MINUTE, 1,
1200 DateTickUnit.SECOND, 5, f3));
1201 units.add(new DateTickUnit(DateTickUnit.MINUTE, 2,
1202 DateTickUnit.SECOND, 10, f3));
1203 units.add(new DateTickUnit(DateTickUnit.MINUTE, 5,
1204 DateTickUnit.MINUTE, 1, f3));
1205 units.add(new DateTickUnit(DateTickUnit.MINUTE, 10,
1206 DateTickUnit.MINUTE, 1, f3));
1207 units.add(new DateTickUnit(DateTickUnit.MINUTE, 15,
1208 DateTickUnit.MINUTE, 5, f3));
1209 units.add(new DateTickUnit(DateTickUnit.MINUTE, 20,
1210 DateTickUnit.MINUTE, 5, f3));
1211 units.add(new DateTickUnit(DateTickUnit.MINUTE, 30,
1212 DateTickUnit.MINUTE, 5, f3));
1213
1214 // hours
1215 units.add(new DateTickUnit(DateTickUnit.HOUR, 1,
1216 DateTickUnit.MINUTE, 5, f3));
1217 units.add(new DateTickUnit(DateTickUnit.HOUR, 2,
1218 DateTickUnit.MINUTE, 10, f3));
1219 units.add(new DateTickUnit(DateTickUnit.HOUR, 4,
1220 DateTickUnit.MINUTE, 30, f3));
1221 units.add(new DateTickUnit(DateTickUnit.HOUR, 6,
1222 DateTickUnit.HOUR, 1, f3));
1223 units.add(new DateTickUnit(DateTickUnit.HOUR, 12,
1224 DateTickUnit.HOUR, 1, f4));
1225
1226 // days
1227 units.add(new DateTickUnit(DateTickUnit.DAY, 1,
1228 DateTickUnit.HOUR, 1, f5));
1229 units.add(new DateTickUnit(DateTickUnit.DAY, 2,
1230 DateTickUnit.HOUR, 1, f5));
1231 units.add(new DateTickUnit(DateTickUnit.DAY, 7,
1232 DateTickUnit.DAY, 1, f5));
1233 units.add(new DateTickUnit(DateTickUnit.DAY, 15,
1234 DateTickUnit.DAY, 1, f5));
1235
1236 // months
1237 units.add(new DateTickUnit(DateTickUnit.MONTH, 1,
1238 DateTickUnit.DAY, 1, f6));
1239 units.add(new DateTickUnit(DateTickUnit.MONTH, 2,
1240 DateTickUnit.DAY, 1, f6));
1241 units.add(new DateTickUnit(DateTickUnit.MONTH, 3,
1242 DateTickUnit.MONTH, 1, f6));
1243 units.add(new DateTickUnit(DateTickUnit.MONTH, 4,
1244 DateTickUnit.MONTH, 1, f6));
1245 units.add(new DateTickUnit(DateTickUnit.MONTH, 6,
1246 DateTickUnit.MONTH, 1, f6));
1247
1248 // years
1249 units.add(new DateTickUnit(DateTickUnit.YEAR, 1,
1250 DateTickUnit.MONTH, 1, f7));
1251 units.add(new DateTickUnit(DateTickUnit.YEAR, 2,
1252 DateTickUnit.MONTH, 3, f7));
1253 units.add(new DateTickUnit(DateTickUnit.YEAR, 5,
1254 DateTickUnit.YEAR, 1, f7));
1255 units.add(new DateTickUnit(DateTickUnit.YEAR, 10,
1256 DateTickUnit.YEAR, 1, f7));
1257 units.add(new DateTickUnit(DateTickUnit.YEAR, 25,
1258 DateTickUnit.YEAR, 5, f7));
1259 units.add(new DateTickUnit(DateTickUnit.YEAR, 50,
1260 DateTickUnit.YEAR, 10, f7));
1261 units.add(new DateTickUnit(DateTickUnit.YEAR, 100,
1262 DateTickUnit.YEAR, 20, f7));
1263
1264 return units;
1265
1266 }
1267
1268 /**
1269 * Rescales the axis to ensure that all data is visible.
1270 */
1271 protected void autoAdjustRange() {
1272
1273 Plot plot = getPlot();
1274
1275 if (plot == null) {
1276 return; // no plot, no data
1277 }
1278
1279 if (plot instanceof ValueAxisPlot) {
1280 ValueAxisPlot vap = (ValueAxisPlot) plot;
1281
1282 Range r = vap.getDataRange(this);
1283 if (r == null) {
1284 if (this.timeline instanceof SegmentedTimeline) {
1285 //Timeline hasn't method getStartTime()
1286 r = new DateRange((
1287 (SegmentedTimeline) this.timeline).getStartTime(),
1288 ((SegmentedTimeline) this.timeline).getStartTime()
1289 + 1);
1290 }
1291 else {
1292 r = new DateRange();
1293 }
1294 }
1295
1296 long upper = this.timeline.toTimelineValue(
1297 (long) r.getUpperBound());
1298 long lower;
1299 long fixedAutoRange = (long) getFixedAutoRange();
1300 if (fixedAutoRange > 0.0) {
1301 lower = upper - fixedAutoRange;
1302 }
1303 else {
1304 lower = this.timeline.toTimelineValue((long) r.getLowerBound());
1305 double range = upper - lower;
1306 long minRange = (long) getAutoRangeMinimumSize();
1307 if (range < minRange) {
1308 long expand = (long) (minRange - range) / 2;
1309 upper = upper + expand;
1310 lower = lower - expand;
1311 }
1312 upper = upper + (long) (range * getUpperMargin());
1313 lower = lower - (long) (range * getLowerMargin());
1314 }
1315
1316 upper = this.timeline.toMillisecond(upper);
1317 lower = this.timeline.toMillisecond(lower);
1318 DateRange dr = new DateRange(new Date(lower), new Date(upper));
1319 setRange(dr, false, false);
1320 }
1321
1322 }
1323
1324 /**
1325 * Selects an appropriate tick value for the axis. The strategy is to
1326 * display as many ticks as possible (selected from an array of 'standard'
1327 * tick units) without the labels overlapping.
1328 *
1329 * @param g2 the graphics device.
1330 * @param dataArea the area defined by the axes.
1331 * @param edge the axis location.
1332 */
1333 protected void selectAutoTickUnit(Graphics2D g2,
1334 Rectangle2D dataArea,
1335 RectangleEdge edge) {
1336
1337 if (RectangleEdge.isTopOrBottom(edge)) {
1338 selectHorizontalAutoTickUnit(g2, dataArea, edge);
1339 }
1340 else if (RectangleEdge.isLeftOrRight(edge)) {
1341 selectVerticalAutoTickUnit(g2, dataArea, edge);
1342 }
1343
1344 }
1345
1346 /**
1347 * Selects an appropriate tick size for the axis. The strategy is to
1348 * display as many ticks as possible (selected from a collection of
1349 * 'standard' tick units) without the labels overlapping.
1350 *
1351 * @param g2 the graphics device.
1352 * @param dataArea the area defined by the axes.
1353 * @param edge the axis location.
1354 */
1355 protected void selectHorizontalAutoTickUnit(Graphics2D g2,
1356 Rectangle2D dataArea, RectangleEdge edge) {
1357
1358 long shift = 0;
1359 if (this.timeline instanceof SegmentedTimeline) {
1360 shift = ((SegmentedTimeline) this.timeline).getStartTime();
1361 }
1362 double zero = valueToJava2D(shift + 0.0, dataArea, edge);
1363 double tickLabelWidth = estimateMaximumTickLabelWidth(g2,
1364 getTickUnit());
1365
1366 // start with the current tick unit...
1367 TickUnitSource tickUnits = getStandardTickUnits();
1368 TickUnit unit1 = tickUnits.getCeilingTickUnit(getTickUnit());
1369 double x1 = valueToJava2D(shift + unit1.getSize(), dataArea, edge);
1370 double unit1Width = Math.abs(x1 - zero);
1371
1372 // then extrapolate...
1373 double guess = (tickLabelWidth / unit1Width) * unit1.getSize();
1374 DateTickUnit unit2 = (DateTickUnit) tickUnits.getCeilingTickUnit(guess);
1375 double x2 = valueToJava2D(shift + unit2.getSize(), dataArea, edge);
1376 double unit2Width = Math.abs(x2 - zero);
1377 tickLabelWidth = estimateMaximumTickLabelWidth(g2, unit2);
1378 if (tickLabelWidth > unit2Width) {
1379 unit2 = (DateTickUnit) tickUnits.getLargerTickUnit(unit2);
1380 }
1381 setTickUnit(unit2, false, false);
1382 }
1383
1384 /**
1385 * Selects an appropriate tick size for the axis. The strategy is to
1386 * display as many ticks as possible (selected from a collection of
1387 * 'standard' tick units) without the labels overlapping.
1388 *
1389 * @param g2 the graphics device.
1390 * @param dataArea the area in which the plot should be drawn.
1391 * @param edge the axis location.
1392 */
1393 protected void selectVerticalAutoTickUnit(Graphics2D g2,
1394 Rectangle2D dataArea,
1395 RectangleEdge edge) {
1396
1397 // start with the current tick unit...
1398 TickUnitSource tickUnits = getStandardTickUnits();
1399 double zero = valueToJava2D(0.0, dataArea, edge);
1400
1401 // start with a unit that is at least 1/10th of the axis length
1402 double estimate1 = getRange().getLength() / 10.0;
1403 DateTickUnit candidate1
1404 = (DateTickUnit) tickUnits.getCeilingTickUnit(estimate1);
1405 double labelHeight1 = estimateMaximumTickLabelHeight(g2, candidate1);
1406 double y1 = valueToJava2D(candidate1.getSize(), dataArea, edge);
1407 double candidate1UnitHeight = Math.abs(y1 - zero);
1408
1409 // now extrapolate based on label height and unit height...
1410 double estimate2
1411 = (labelHeight1 / candidate1UnitHeight) * candidate1.getSize();
1412 DateTickUnit candidate2
1413 = (DateTickUnit) tickUnits.getCeilingTickUnit(estimate2);
1414 double labelHeight2 = estimateMaximumTickLabelHeight(g2, candidate2);
1415 double y2 = valueToJava2D(candidate2.getSize(), dataArea, edge);
1416 double unit2Height = Math.abs(y2 - zero);
1417
1418 // make final selection...
1419 DateTickUnit finalUnit;
1420 if (labelHeight2 < unit2Height) {
1421 finalUnit = candidate2;
1422 }
1423 else {
1424 finalUnit = (DateTickUnit) tickUnits.getLargerTickUnit(candidate2);
1425 }
1426 setTickUnit(finalUnit, false, false);
1427
1428 }
1429
1430 /**
1431 * Estimates the maximum width of the tick labels, assuming the specified
1432 * tick unit is used.
1433 * <P>
1434 * Rather than computing the string bounds of every tick on the axis, we
1435 * just look at two values: the lower bound and the upper bound for the
1436 * axis. These two values will usually be representative.
1437 *
1438 * @param g2 the graphics device.
1439 * @param unit the tick unit to use for calculation.
1440 *
1441 * @return The estimated maximum width of the tick labels.
1442 */
1443 private double estimateMaximumTickLabelWidth(Graphics2D g2,
1444 DateTickUnit unit) {
1445
1446 RectangleInsets tickLabelInsets = getTickLabelInsets();
1447 double result = tickLabelInsets.getLeft() + tickLabelInsets.getRight();
1448
1449 Font tickLabelFont = getTickLabelFont();
1450 FontRenderContext frc = g2.getFontRenderContext();
1451 LineMetrics lm = tickLabelFont.getLineMetrics("ABCxyz", frc);
1452 if (isVerticalTickLabels()) {
1453 // all tick labels have the same width (equal to the height of
1454 // the font)...
1455 result += lm.getHeight();
1456 }
1457 else {
1458 // look at lower and upper bounds...
1459 DateRange range = (DateRange) getRange();
1460 Date lower = range.getLowerDate();
1461 Date upper = range.getUpperDate();
1462 String lowerStr = null;
1463 String upperStr = null;
1464 DateFormat formatter = getDateFormatOverride();
1465 if (formatter != null) {
1466 lowerStr = formatter.format(lower);
1467 upperStr = formatter.format(upper);
1468 }
1469 else {
1470 lowerStr = unit.dateToString(lower);
1471 upperStr = unit.dateToString(upper);
1472 }
1473 FontMetrics fm = g2.getFontMetrics(tickLabelFont);
1474 double w1 = fm.stringWidth(lowerStr);
1475 double w2 = fm.stringWidth(upperStr);
1476 result += Math.max(w1, w2);
1477 }
1478
1479 return result;
1480
1481 }
1482
1483 /**
1484 * Estimates the maximum width of the tick labels, assuming the specified
1485 * tick unit is used.
1486 * <P>
1487 * Rather than computing the string bounds of every tick on the axis, we
1488 * just look at two values: the lower bound and the upper bound for the
1489 * axis. These two values will usually be representative.
1490 *
1491 * @param g2 the graphics device.
1492 * @param unit the tick unit to use for calculation.
1493 *
1494 * @return The estimated maximum width of the tick labels.
1495 */
1496 private double estimateMaximumTickLabelHeight(Graphics2D g2,
1497 DateTickUnit unit) {
1498
1499 RectangleInsets tickLabelInsets = getTickLabelInsets();
1500 double result = tickLabelInsets.getTop() + tickLabelInsets.getBottom();
1501
1502 Font tickLabelFont = getTickLabelFont();
1503 FontRenderContext frc = g2.getFontRenderContext();
1504 LineMetrics lm = tickLabelFont.getLineMetrics("ABCxyz", frc);
1505 if (!isVerticalTickLabels()) {
1506 // all tick labels have the same width (equal to the height of
1507 // the font)...
1508 result += lm.getHeight();
1509 }
1510 else {
1511 // look at lower and upper bounds...
1512 DateRange range = (DateRange) getRange();
1513 Date lower = range.getLowerDate();
1514 Date upper = range.getUpperDate();
1515 String lowerStr = null;
1516 String upperStr = null;
1517 DateFormat formatter = getDateFormatOverride();
1518 if (formatter != null) {
1519 lowerStr = formatter.format(lower);
1520 upperStr = formatter.format(upper);
1521 }
1522 else {
1523 lowerStr = unit.dateToString(lower);
1524 upperStr = unit.dateToString(upper);
1525 }
1526 FontMetrics fm = g2.getFontMetrics(tickLabelFont);
1527 double w1 = fm.stringWidth(lowerStr);
1528 double w2 = fm.stringWidth(upperStr);
1529 result += Math.max(w1, w2);
1530 }
1531
1532 return result;
1533
1534 }
1535
1536 /**
1537 * Calculates the positions of the tick labels for the axis, storing the
1538 * results in the tick label list (ready for drawing).
1539 *
1540 * @param g2 the graphics device.
1541 * @param state the axis state.
1542 * @param dataArea the area in which the plot should be drawn.
1543 * @param edge the location of the axis.
1544 *
1545 * @return A list of ticks.
1546 */
1547 public List refreshTicks(Graphics2D g2,
1548 AxisState state,
1549 Rectangle2D dataArea,
1550 RectangleEdge edge) {
1551
1552 List result = null;
1553 if (RectangleEdge.isTopOrBottom(edge)) {
1554 result = refreshTicksHorizontal(g2, dataArea, edge);
1555 }
1556 else if (RectangleEdge.isLeftOrRight(edge)) {
1557 result = refreshTicksVertical(g2, dataArea, edge);
1558 }
1559 return result;
1560
1561 }
1562
1563 /**
1564 * Corrects the given tick date for the position setting.
1565 *
1566 * @param time the tick date/time.
1567 * @param unit the tick unit.
1568 * @param position the tick position.
1569 *
1570 * @return The adjusted time.
1571 */
1572 private Date correctTickDateForPosition(Date time, DateTickUnit unit,
1573 DateTickMarkPosition position) {
1574 Date result = time;
1575 switch (unit.getUnit()) {
1576 case (DateTickUnit.MILLISECOND) :
1577 case (DateTickUnit.SECOND) :
1578 case (DateTickUnit.MINUTE) :
1579 case (DateTickUnit.HOUR) :
1580 case (DateTickUnit.DAY) :
1581 break;
1582 case (DateTickUnit.MONTH) :
1583 result = calculateDateForPosition(new Month(time,
1584 this.timeZone, this.locale), position);
1585 break;
1586 case(DateTickUnit.YEAR) :
1587 result = calculateDateForPosition(new Year(time,
1588 this.timeZone, this.locale), position);
1589 break;
1590
1591 default: break;
1592 }
1593 return result;
1594 }
1595
1596 /**
1597 * Recalculates the ticks for the date axis.
1598 *
1599 * @param g2 the graphics device.
1600 * @param dataArea the area in which the data is to be drawn.
1601 * @param edge the location of the axis.
1602 *
1603 * @return A list of ticks.
1604 */
1605 protected List refreshTicksHorizontal(Graphics2D g2,
1606 Rectangle2D dataArea, RectangleEdge edge) {
1607
1608 List result = new java.util.ArrayList();
1609
1610 Font tickLabelFont = getTickLabelFont();
1611 g2.setFont(tickLabelFont);
1612
1613 if (isAutoTickUnitSelection()) {
1614 selectAutoTickUnit(g2, dataArea, edge);
1615 }
1616
1617 DateTickUnit unit = getTickUnit();
1618 Date tickDate = calculateLowestVisibleTickValue(unit);
1619 Date upperDate = getMaximumDate();
1620
1621 while (tickDate.before(upperDate)) {
1622 // could add a flag to make the following correction optional...
1623 tickDate = correctTickDateForPosition(tickDate, unit,
1624 this.tickMarkPosition);
1625
1626 long lowestTickTime = tickDate.getTime();
1627 long distance = unit.addToDate(tickDate, this.timeZone).getTime()
1628 - lowestTickTime;
1629 for(int minorTick = 1; minorTick < getMinorTickCount();
1630 minorTick++) {
1631 long minorTickTime = lowestTickTime - distance
1632 * minorTick / getMinorTickCount();
1633 if (minorTickTime > 0 && getRange().contains(minorTickTime)
1634 && (!isHiddenValue(minorTickTime))) {
1635 result.add(new DateTick(TickType.MINOR,
1636 new Date(minorTickTime), "", TextAnchor.TOP_CENTER,
1637 TextAnchor.CENTER, 0.0));
1638 }
1639 }
1640
1641 if (!isHiddenValue(tickDate.getTime())) {
1642 // work out the value, label and position
1643 String tickLabel;
1644 DateFormat formatter = getDateFormatOverride();
1645 if (formatter != null) {
1646 tickLabel = formatter.format(tickDate);
1647 }
1648 else {
1649 tickLabel = this.tickUnit.dateToString(tickDate);
1650 }
1651 TextAnchor anchor = null;
1652 TextAnchor rotationAnchor = null;
1653 double angle = 0.0;
1654 if (isVerticalTickLabels()) {
1655 anchor = TextAnchor.CENTER_RIGHT;
1656 rotationAnchor = TextAnchor.CENTER_RIGHT;
1657 if (edge == RectangleEdge.TOP) {
1658 angle = Math.PI / 2.0;
1659 }
1660 else {
1661 angle = -Math.PI / 2.0;
1662 }
1663 }
1664 else {
1665 if (edge == RectangleEdge.TOP) {
1666 anchor = TextAnchor.BOTTOM_CENTER;
1667 rotationAnchor = TextAnchor.BOTTOM_CENTER;
1668 }
1669 else {
1670 anchor = TextAnchor.TOP_CENTER;
1671 rotationAnchor = TextAnchor.TOP_CENTER;
1672 }
1673 }
1674
1675 Tick tick = new DateTick(tickDate, tickLabel, anchor,
1676 rotationAnchor, angle);
1677 result.add(tick);
1678
1679 long currentTickTime = tickDate.getTime();
1680 tickDate = unit.addToDate(tickDate, this.timeZone);
1681 long nextTickTime = tickDate.getTime();
1682 for (int minorTick = 1; minorTick < getMinorTickCount();
1683 minorTick++){
1684 long minorTickTime = currentTickTime
1685 + (nextTickTime - currentTickTime)
1686 * minorTick / getMinorTickCount();
1687 if (getRange().contains(minorTickTime)
1688 && (!isHiddenValue(minorTickTime))) {
1689 result.add(new DateTick(TickType.MINOR,
1690 new Date(minorTickTime), "",
1691 TextAnchor.TOP_CENTER, TextAnchor.CENTER,
1692 0.0));
1693 }
1694 }
1695
1696 }
1697 else {
1698 tickDate = unit.rollDate(tickDate, this.timeZone);
1699 continue;
1700 }
1701
1702 }
1703 return result;
1704
1705 }
1706
1707 /**
1708 * Recalculates the ticks for the date axis.
1709 *
1710 * @param g2 the graphics device.
1711 * @param dataArea the area in which the plot should be drawn.
1712 * @param edge the location of the axis.
1713 *
1714 * @return A list of ticks.
1715 */
1716 protected List refreshTicksVertical(Graphics2D g2,
1717 Rectangle2D dataArea, RectangleEdge edge) {
1718
1719 List result = new java.util.ArrayList();
1720
1721 Font tickLabelFont = getTickLabelFont();
1722 g2.setFont(tickLabelFont);
1723
1724 if (isAutoTickUnitSelection()) {
1725 selectAutoTickUnit(g2, dataArea, edge);
1726 }
1727 DateTickUnit unit = getTickUnit();
1728 Date tickDate = calculateLowestVisibleTickValue(unit);
1729 Date upperDate = getMaximumDate();
1730
1731 while (tickDate.before(upperDate)) {
1732
1733 // could add a flag to make the following correction optional...
1734 tickDate = correctTickDateForPosition(tickDate, unit,
1735 this.tickMarkPosition);
1736
1737 long lowestTickTime = tickDate.getTime();
1738 long distance = unit.addToDate(tickDate, this.timeZone).getTime()
1739 - lowestTickTime;
1740 for(int minorTick = 1; minorTick < getMinorTickCount();
1741 minorTick++) {
1742 long minorTickTime = lowestTickTime - distance
1743 * minorTick / getMinorTickCount();
1744 if (minorTickTime > 0 && getRange().contains(minorTickTime)
1745 && (!isHiddenValue(minorTickTime))) {
1746 result.add(new DateTick(TickType.MINOR,
1747 new Date(minorTickTime), "", TextAnchor.TOP_CENTER,
1748 TextAnchor.CENTER, 0.0));
1749 }
1750 }
1751 if (!isHiddenValue(tickDate.getTime())) {
1752 // work out the value, label and position
1753 String tickLabel;
1754 DateFormat formatter = getDateFormatOverride();
1755 if (formatter != null) {
1756 tickLabel = formatter.format(tickDate);
1757 }
1758 else {
1759 tickLabel = this.tickUnit.dateToString(tickDate);
1760 }
1761 TextAnchor anchor = null;
1762 TextAnchor rotationAnchor = null;
1763 double angle = 0.0;
1764 if (isVerticalTickLabels()) {
1765 anchor = TextAnchor.BOTTOM_CENTER;
1766 rotationAnchor = TextAnchor.BOTTOM_CENTER;
1767 if (edge == RectangleEdge.LEFT) {
1768 angle = -Math.PI / 2.0;
1769 }
1770 else {
1771 angle = Math.PI / 2.0;
1772 }
1773 }
1774 else {
1775 if (edge == RectangleEdge.LEFT) {
1776 anchor = TextAnchor.CENTER_RIGHT;
1777 rotationAnchor = TextAnchor.CENTER_RIGHT;
1778 }
1779 else {
1780 anchor = TextAnchor.CENTER_LEFT;
1781 rotationAnchor = TextAnchor.CENTER_LEFT;
1782 }
1783 }
1784
1785 Tick tick = new DateTick(tickDate, tickLabel, anchor,
1786 rotationAnchor, angle);
1787 result.add(tick);
1788 long currentTickTime = tickDate.getTime();
1789 tickDate = unit.addToDate(tickDate, this.timeZone);
1790 long nextTickTime = tickDate.getTime();
1791 for(int minorTick = 1; minorTick < getMinorTickCount();
1792 minorTick++){
1793 long minorTickTime = currentTickTime
1794 + (nextTickTime - currentTickTime)
1795 * minorTick / getMinorTickCount();
1796 if (getRange().contains(minorTickTime)
1797 && (!isHiddenValue(minorTickTime))) {
1798 result.add(new DateTick(TickType.MINOR,
1799 new Date(minorTickTime), "",
1800 TextAnchor.TOP_CENTER, TextAnchor.CENTER,
1801 0.0));
1802 }
1803 }
1804 }
1805 else {
1806 tickDate = unit.rollDate(tickDate, this.timeZone);
1807 }
1808 }
1809 return result;
1810 }
1811
1812 /**
1813 * Draws the axis on a Java 2D graphics device (such as the screen or a
1814 * printer).
1815 *
1816 * @param g2 the graphics device (<code>null</code> not permitted).
1817 * @param cursor the cursor location.
1818 * @param plotArea the area within which the axes and data should be
1819 * drawn (<code>null</code> not permitted).
1820 * @param dataArea the area within which the data should be drawn
1821 * (<code>null</code> not permitted).
1822 * @param edge the location of the axis (<code>null</code> not permitted).
1823 * @param plotState collects information about the plot
1824 * (<code>null</code> permitted).
1825 *
1826 * @return The axis state (never <code>null</code>).
1827 */
1828 public AxisState draw(Graphics2D g2,
1829 double cursor,
1830 Rectangle2D plotArea,
1831 Rectangle2D dataArea,
1832 RectangleEdge edge,
1833 PlotRenderingInfo plotState) {
1834
1835 // if the axis is not visible, don't draw it...
1836 if (!isVisible()) {
1837 AxisState state = new AxisState(cursor);
1838 // even though the axis is not visible, we need to refresh ticks in
1839 // case the grid is being drawn...
1840 List ticks = refreshTicks(g2, state, dataArea, edge);
1841 state.setTicks(ticks);
1842 return state;
1843 }
1844
1845 // draw the tick marks and labels...
1846 AxisState state = drawTickMarksAndLabels(g2, cursor, plotArea,
1847 dataArea, edge);
1848
1849 // draw the axis label (note that 'state' is passed in *and*
1850 // returned)...
1851 state = drawLabel(getLabel(), g2, plotArea, dataArea, edge, state);
1852
1853 return state;
1854
1855 }
1856
1857 /**
1858 * Zooms in on the current range.
1859 *
1860 * @param lowerPercent the new lower bound.
1861 * @param upperPercent the new upper bound.
1862 */
1863 public void zoomRange(double lowerPercent, double upperPercent) {
1864 double start = this.timeline.toTimelineValue(
1865 (long) getRange().getLowerBound()
1866 );
1867 double length = (this.timeline.toTimelineValue(
1868 (long) getRange().getUpperBound())
1869 - this.timeline.toTimelineValue(
1870 (long) getRange().getLowerBound()));
1871 Range adjusted = null;
1872 if (isInverted()) {
1873 adjusted = new DateRange(this.timeline.toMillisecond((long) (start
1874 + (length * (1 - upperPercent)))),
1875 this.timeline.toMillisecond((long) (start + (length
1876 * (1 - lowerPercent)))));
1877 }
1878 else {
1879 adjusted = new DateRange(this.timeline.toMillisecond(
1880 (long) (start + length * lowerPercent)),
1881 this.timeline.toMillisecond((long) (start + length
1882 * upperPercent)));
1883 }
1884 setRange(adjusted);
1885 }
1886
1887 /**
1888 * Tests this axis for equality with an arbitrary object.
1889 *
1890 * @param obj the object (<code>null</code> permitted).
1891 *
1892 * @return A boolean.
1893 */
1894 public boolean equals(Object obj) {
1895 if (obj == this) {
1896 return true;
1897 }
1898 if (!(obj instanceof DateAxis)) {
1899 return false;
1900 }
1901 DateAxis that = (DateAxis) obj;
1902 if (!ObjectUtilities.equal(this.tickUnit, that.tickUnit)) {
1903 return false;
1904 }
1905 if (!ObjectUtilities.equal(this.dateFormatOverride,
1906 that.dateFormatOverride)) {
1907 return false;
1908 }
1909 if (!ObjectUtilities.equal(this.tickMarkPosition,
1910 that.tickMarkPosition)) {
1911 return false;
1912 }
1913 if (!ObjectUtilities.equal(this.timeline, that.timeline)) {
1914 return false;
1915 }
1916 return super.equals(obj);
1917 }
1918
1919 /**
1920 * Returns a hash code for this object.
1921 *
1922 * @return A hash code.
1923 */
1924 public int hashCode() {
1925 if (getLabel() != null) {
1926 return getLabel().hashCode();
1927 }
1928 else {
1929 return 0;
1930 }
1931 }
1932
1933 /**
1934 * Returns a clone of the object.
1935 *
1936 * @return A clone.
1937 *
1938 * @throws CloneNotSupportedException if some component of the axis does
1939 * not support cloning.
1940 */
1941 public Object clone() throws CloneNotSupportedException {
1942
1943 DateAxis clone = (DateAxis) super.clone();
1944
1945 // 'dateTickUnit' is immutable : no need to clone
1946 if (this.dateFormatOverride != null) {
1947 clone.dateFormatOverride
1948 = (DateFormat) this.dateFormatOverride.clone();
1949 }
1950 // 'tickMarkPosition' is immutable : no need to clone
1951
1952 return clone;
1953
1954 }
1955
1956 }