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