001/* =========================================================== 002 * JFreeChart : a free chart library for the Java(tm) platform 003 * =========================================================== 004 * 005 * (C) Copyright 2000-2017, 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 * StackedXYAreaRenderer.java 029 * -------------------------- 030 * (C) Copyright 2003-2017, by Richard Atkinson and Contributors. 031 * 032 * Original Author: Richard Atkinson; 033 * Contributor(s): Christian W. Zuckschwerdt; 034 * David Gilbert (for Object Refinery Limited); 035 * Ulrich Voigt (patch #312); 036 * 037 * Changes: 038 * -------- 039 * 27-Jul-2003 : Initial version (RA); 040 * 30-Jul-2003 : Modified entity constructor (CZ); 041 * 18-Aug-2003 : Now handles null values (RA); 042 * 20-Aug-2003 : Implemented Cloneable, PublicCloneable and Serializable (DG); 043 * 22-Sep-2003 : Changed to be a two pass renderer with optional shape Paint 044 * and Stroke (RA); 045 * 07-Oct-2003 : Added renderer state (DG); 046 * 10-Feb-2004 : Updated state object and changed drawItem() method to make 047 * overriding easier (DG); 048 * 25-Feb-2004 : Replaced CrosshairInfo with CrosshairState. Renamed 049 * XYToolTipGenerator --> XYItemLabelGenerator (DG); 050 * 15-Jul-2004 : Switched getX() with getXValue() and getY() with 051 * getYValue() (DG); 052 * 10-Sep-2004 : Removed getRangeType() method (DG); 053 * 11-Nov-2004 : Now uses ShapeUtilities to translate shapes (DG); 054 * 06-Jan-2005 : Override equals() (DG); 055 * 07-Jan-2005 : Update for method name changes in DatasetUtilities (DG); 056 * 28-Mar-2005 : Use getXValue() and getYValue() from dataset (DG); 057 * 06-Jun-2005 : Fixed null pointer exception, plus problems with equals() and 058 * serialization (DG); 059 * ------------- JFREECHART 1.0.x --------------------------------------------- 060 * 10-Nov-2006 : Fixed bug 1593156, NullPointerException with line 061 * plotting (DG); 062 * 02-Feb-2007 : Fixed bug 1649686, crosshairs don't stack y-values (DG); 063 * 06-Feb-2007 : Fixed bug 1086307, crosshairs with multiple axes (DG); 064 * 22-Mar-2007 : Fire change events in setShapePaint() and setShapeStroke() 065 * methods (DG); 066 * 20-Apr-2007 : Updated getLegendItem() for renderer change (DG); 067 * 04-Aug-2014 : Fix entity hotspot (patch #312) (UV); 068 * 18-Feb-2017 : Updates for crosshairs (bug #36) (DG); 069 * 070 */ 071 072package org.jfree.chart.renderer.xy; 073 074import java.awt.Graphics2D; 075import java.awt.Paint; 076import java.awt.Point; 077import java.awt.Polygon; 078import java.awt.Shape; 079import java.awt.Stroke; 080import java.awt.geom.Area; 081import java.awt.geom.Line2D; 082import java.awt.geom.Rectangle2D; 083import java.io.IOException; 084import java.io.ObjectInputStream; 085import java.io.ObjectOutputStream; 086import java.io.Serializable; 087import java.util.Stack; 088 089import org.jfree.chart.axis.ValueAxis; 090import org.jfree.chart.entity.EntityCollection; 091import org.jfree.chart.entity.XYItemEntity; 092import org.jfree.chart.event.RendererChangeEvent; 093import org.jfree.chart.labels.XYToolTipGenerator; 094import org.jfree.chart.plot.CrosshairState; 095import org.jfree.chart.plot.PlotOrientation; 096import org.jfree.chart.plot.PlotRenderingInfo; 097import org.jfree.chart.plot.XYPlot; 098import org.jfree.chart.urls.XYURLGenerator; 099import org.jfree.chart.util.ObjectUtils; 100import org.jfree.chart.util.PaintUtils; 101import org.jfree.chart.util.PublicCloneable; 102import org.jfree.chart.util.SerialUtils; 103import org.jfree.chart.util.ShapeUtils; 104import org.jfree.data.Range; 105import org.jfree.data.general.DatasetUtils; 106import org.jfree.data.xy.TableXYDataset; 107import org.jfree.data.xy.XYDataset; 108 109/** 110 * A stacked area renderer for the {@link XYPlot} class. 111 * <br><br> 112 * The example shown here is generated by the 113 * {@code StackedXYAreaRendererDemo1.java} program included in the 114 * JFreeChart demo collection: 115 * <br><br> 116 * <img src="../../../../../images/StackedXYAreaRendererSample.png" 117 * alt="StackedXYAreaRendererSample.png"> 118 * <br><br> 119 * SPECIAL NOTE: This renderer does not currently handle negative data values 120 * correctly. This should get fixed at some point, but the current workaround 121 * is to use the {@link StackedXYAreaRenderer2} class instead. 122 */ 123public class StackedXYAreaRenderer extends XYAreaRenderer 124 implements Cloneable, PublicCloneable, Serializable { 125 126 /** For serialization. */ 127 private static final long serialVersionUID = 5217394318178570889L; 128 129 /** 130 * A state object for use by this renderer. 131 */ 132 static class StackedXYAreaRendererState extends XYItemRendererState { 133 134 /** The area for the current series. */ 135 private Polygon seriesArea; 136 137 /** The line. */ 138 private Line2D line; 139 140 /** The points from the last series. */ 141 private Stack lastSeriesPoints; 142 143 /** The points for the current series. */ 144 private Stack currentSeriesPoints; 145 146 /** 147 * Creates a new state for the renderer. 148 * 149 * @param info the plot rendering info. 150 */ 151 public StackedXYAreaRendererState(PlotRenderingInfo info) { 152 super(info); 153 this.seriesArea = null; 154 this.line = new Line2D.Double(); 155 this.lastSeriesPoints = new Stack(); 156 this.currentSeriesPoints = new Stack(); 157 } 158 159 /** 160 * Returns the series area. 161 * 162 * @return The series area. 163 */ 164 public Polygon getSeriesArea() { 165 return this.seriesArea; 166 } 167 168 /** 169 * Sets the series area. 170 * 171 * @param area the area. 172 */ 173 public void setSeriesArea(Polygon area) { 174 this.seriesArea = area; 175 } 176 177 /** 178 * Returns the working line. 179 * 180 * @return The working line. 181 */ 182 public Line2D getLine() { 183 return this.line; 184 } 185 186 /** 187 * Returns the current series points. 188 * 189 * @return The current series points. 190 */ 191 public Stack getCurrentSeriesPoints() { 192 return this.currentSeriesPoints; 193 } 194 195 /** 196 * Sets the current series points. 197 * 198 * @param points the points. 199 */ 200 public void setCurrentSeriesPoints(Stack points) { 201 this.currentSeriesPoints = points; 202 } 203 204 /** 205 * Returns the last series points. 206 * 207 * @return The last series points. 208 */ 209 public Stack getLastSeriesPoints() { 210 return this.lastSeriesPoints; 211 } 212 213 /** 214 * Sets the last series points. 215 * 216 * @param points the points. 217 */ 218 public void setLastSeriesPoints(Stack points) { 219 this.lastSeriesPoints = points; 220 } 221 222 } 223 224 /** 225 * Custom Paint for drawing all shapes, if null defaults to series shapes 226 */ 227 private transient Paint shapePaint = null; 228 229 /** 230 * Custom Stroke for drawing all shapes, if null defaults to series 231 * strokes. 232 */ 233 private transient Stroke shapeStroke = null; 234 235 /** 236 * Creates a new renderer. 237 */ 238 public StackedXYAreaRenderer() { 239 this(AREA); 240 } 241 242 /** 243 * Constructs a new renderer. 244 * 245 * @param type the type of the renderer. 246 */ 247 public StackedXYAreaRenderer(int type) { 248 this(type, null, null); 249 } 250 251 /** 252 * Constructs a new renderer. To specify the type of renderer, use one of 253 * the constants: {@code SHAPES}, {@code LINES}, {@code SHAPES_AND_LINES}, 254 * {@code AREA} or {@code AREA_AND_SHAPES}. 255 * 256 * @param type the type of renderer. 257 * @param labelGenerator the tool tip generator ({@code null} permitted). 258 * @param urlGenerator the URL generator ({@code null} permitted). 259 */ 260 public StackedXYAreaRenderer(int type, XYToolTipGenerator labelGenerator, 261 XYURLGenerator urlGenerator) { 262 super(type, labelGenerator, urlGenerator); 263 } 264 265 /** 266 * Returns the paint used for rendering shapes, or {@code null} if 267 * using series paints. 268 * 269 * @return The paint (possibly {@code null}). 270 * 271 * @see #setShapePaint(Paint) 272 */ 273 public Paint getShapePaint() { 274 return this.shapePaint; 275 } 276 277 /** 278 * Sets the paint for rendering shapes and sends a 279 * {@link RendererChangeEvent} to all registered listeners. 280 * 281 * @param shapePaint the paint ({@code null} permitted). 282 * 283 * @see #getShapePaint() 284 */ 285 public void setShapePaint(Paint shapePaint) { 286 this.shapePaint = shapePaint; 287 fireChangeEvent(); 288 } 289 290 /** 291 * Returns the stroke used for rendering shapes, or {@code null} if 292 * using series strokes. 293 * 294 * @return The stroke (possibly {@code null}). 295 * 296 * @see #setShapeStroke(Stroke) 297 */ 298 public Stroke getShapeStroke() { 299 return this.shapeStroke; 300 } 301 302 /** 303 * Sets the stroke for rendering shapes and sends a 304 * {@link RendererChangeEvent} to all registered listeners. 305 * 306 * @param shapeStroke the stroke ({@code null} permitted). 307 * 308 * @see #getShapeStroke() 309 */ 310 public void setShapeStroke(Stroke shapeStroke) { 311 this.shapeStroke = shapeStroke; 312 fireChangeEvent(); 313 } 314 315 /** 316 * Initialises the renderer. This method will be called before the first 317 * item is rendered, giving the renderer an opportunity to initialise any 318 * state information it wants to maintain. 319 * 320 * @param g2 the graphics device. 321 * @param dataArea the area inside the axes. 322 * @param plot the plot. 323 * @param data the data. 324 * @param info an optional info collection object to return data back to 325 * the caller. 326 * 327 * @return A state object that should be passed to subsequent calls to the 328 * drawItem() method. 329 */ 330 @Override 331 public XYItemRendererState initialise(Graphics2D g2, Rectangle2D dataArea, 332 XYPlot plot, XYDataset data, PlotRenderingInfo info) { 333 334 XYItemRendererState state = new StackedXYAreaRendererState(info); 335 // in the rendering process, there is special handling for item 336 // zero, so we can't support processing of visible data items only 337 state.setProcessVisibleItemsOnly(false); 338 return state; 339 } 340 341 /** 342 * Returns the number of passes required by the renderer. 343 * 344 * @return 2. 345 */ 346 @Override 347 public int getPassCount() { 348 return 2; 349 } 350 351 /** 352 * Returns the range of values the renderer requires to display all the 353 * items from the specified dataset. 354 * 355 * @param dataset the dataset ({@code null} permitted). 356 * 357 * @return The range ([0.0, 0.0] if the dataset contains no values, and 358 * {@code null} if the dataset is {@code null}). 359 * 360 * @throws ClassCastException if {@code dataset} is not an instance 361 * of {@link TableXYDataset}. 362 */ 363 @Override 364 public Range findRangeBounds(XYDataset dataset) { 365 if (dataset != null) { 366 return DatasetUtils.findStackedRangeBounds( 367 (TableXYDataset) dataset); 368 } 369 else { 370 return null; 371 } 372 } 373 374 /** 375 * Draws the visual representation of a single data item. 376 * 377 * @param g2 the graphics device. 378 * @param state the renderer state. 379 * @param dataArea the area within which the data is being drawn. 380 * @param info collects information about the drawing. 381 * @param plot the plot (can be used to obtain standard color information 382 * etc). 383 * @param domainAxis the domain axis. 384 * @param rangeAxis the range axis. 385 * @param dataset the dataset. 386 * @param series the series index (zero-based). 387 * @param item the item index (zero-based). 388 * @param crosshairState information about crosshairs on a plot. 389 * @param pass the pass index. 390 * 391 * @throws ClassCastException if {@code state} is not an instance of 392 * {@code StackedXYAreaRendererState} or {@code dataset} 393 * is not an instance of {@link TableXYDataset}. 394 */ 395 @Override 396 public void drawItem(Graphics2D g2, XYItemRendererState state, 397 Rectangle2D dataArea, PlotRenderingInfo info, XYPlot plot, 398 ValueAxis domainAxis, ValueAxis rangeAxis, XYDataset dataset, 399 int series, int item, CrosshairState crosshairState, int pass) { 400 401 PlotOrientation orientation = plot.getOrientation(); 402 StackedXYAreaRendererState areaState 403 = (StackedXYAreaRendererState) state; 404 // Get the item count for the series, so that we can know which is the 405 // end of the series. 406 TableXYDataset tdataset = (TableXYDataset) dataset; 407 int itemCount = tdataset.getItemCount(); 408 409 // get the data point... 410 double x1 = dataset.getXValue(series, item); 411 double y1 = dataset.getYValue(series, item); 412 boolean nullPoint = false; 413 if (Double.isNaN(y1)) { 414 y1 = 0.0; 415 nullPoint = true; 416 } 417 418 // Get height adjustment based on stack and translate to Java2D values 419 double ph1 = getPreviousHeight(tdataset, series, item); 420 double transX1 = domainAxis.valueToJava2D(x1, dataArea, 421 plot.getDomainAxisEdge()); 422 double transY1 = rangeAxis.valueToJava2D(y1 + ph1, dataArea, 423 plot.getRangeAxisEdge()); 424 425 // Get series Paint and Stroke 426 Paint seriesPaint = getItemPaint(series, item); 427 Paint seriesFillPaint = seriesPaint; 428 if (getUseFillPaint()) { 429 seriesFillPaint = getItemFillPaint(series, item); 430 } 431 Stroke seriesStroke = getItemStroke(series, item); 432 433 if (pass == 0) { 434 // On first pass render the areas, line and outlines 435 436 if (item == 0) { 437 // Create a new Area for the series 438 areaState.setSeriesArea(new Polygon()); 439 areaState.setLastSeriesPoints( 440 areaState.getCurrentSeriesPoints()); 441 areaState.setCurrentSeriesPoints(new Stack()); 442 443 // start from previous height (ph1) 444 double transY2 = rangeAxis.valueToJava2D(ph1, dataArea, 445 plot.getRangeAxisEdge()); 446 447 // The first point is (x, 0) 448 if (orientation == PlotOrientation.VERTICAL) { 449 areaState.getSeriesArea().addPoint((int) transX1, 450 (int) transY2); 451 } 452 else if (orientation == PlotOrientation.HORIZONTAL) { 453 areaState.getSeriesArea().addPoint((int) transY2, 454 (int) transX1); 455 } 456 } 457 458 // Add each point to Area (x, y) 459 if (orientation == PlotOrientation.VERTICAL) { 460 Point point = new Point((int) transX1, (int) transY1); 461 areaState.getSeriesArea().addPoint((int) point.getX(), 462 (int) point.getY()); 463 areaState.getCurrentSeriesPoints().push(point); 464 } 465 else if (orientation == PlotOrientation.HORIZONTAL) { 466 areaState.getSeriesArea().addPoint((int) transY1, 467 (int) transX1); 468 } 469 470 if (getPlotLines()) { 471 if (item > 0) { 472 // get the previous data point... 473 double x0 = dataset.getXValue(series, item - 1); 474 double y0 = dataset.getYValue(series, item - 1); 475 double ph0 = getPreviousHeight(tdataset, series, item - 1); 476 double transX0 = domainAxis.valueToJava2D(x0, dataArea, 477 plot.getDomainAxisEdge()); 478 double transY0 = rangeAxis.valueToJava2D(y0 + ph0, 479 dataArea, plot.getRangeAxisEdge()); 480 481 if (orientation == PlotOrientation.VERTICAL) { 482 areaState.getLine().setLine(transX0, transY0, transX1, 483 transY1); 484 } 485 else if (orientation == PlotOrientation.HORIZONTAL) { 486 areaState.getLine().setLine(transY0, transX0, transY1, 487 transX1); 488 } 489 g2.setPaint(seriesPaint); 490 g2.setStroke(seriesStroke); 491 g2.draw(areaState.getLine()); 492 } 493 } 494 495 // Check if the item is the last item for the series and number of 496 // items > 0. We can't draw an area for a single point. 497 if (getPlotArea() && item > 0 && item == (itemCount - 1)) { 498 499 double transY2 = rangeAxis.valueToJava2D(ph1, dataArea, 500 plot.getRangeAxisEdge()); 501 502 if (orientation == PlotOrientation.VERTICAL) { 503 // Add the last point (x,0) 504 areaState.getSeriesArea().addPoint((int) transX1, 505 (int) transY2); 506 } 507 else if (orientation == PlotOrientation.HORIZONTAL) { 508 // Add the last point (x,0) 509 areaState.getSeriesArea().addPoint((int) transY2, 510 (int) transX1); 511 } 512 513 // Add points from last series to complete the base of the 514 // polygon 515 if (series != 0) { 516 Stack points = areaState.getLastSeriesPoints(); 517 while (!points.empty()) { 518 Point point = (Point) points.pop(); 519 areaState.getSeriesArea().addPoint((int) point.getX(), 520 (int) point.getY()); 521 } 522 } 523 524 // Fill the polygon 525 g2.setPaint(seriesFillPaint); 526 g2.setStroke(seriesStroke); 527 g2.fill(areaState.getSeriesArea()); 528 529 // Draw an outline around the Area. 530 if (isOutline()) { 531 g2.setStroke(lookupSeriesOutlineStroke(series)); 532 g2.setPaint(lookupSeriesOutlinePaint(series)); 533 g2.draw(areaState.getSeriesArea()); 534 } 535 } 536 537 int datasetIndex = plot.indexOf(dataset); 538 updateCrosshairValues(crosshairState, x1, ph1 + y1, datasetIndex, 539 transX1, transY1, orientation); 540 541 } 542 else if (pass == 1) { 543 // On second pass render shapes and collect entity and tooltip 544 // information 545 546 Shape shape = null; 547 if (getPlotShapes()) { 548 shape = getItemShape(series, item); 549 if (plot.getOrientation() == PlotOrientation.VERTICAL) { 550 shape = ShapeUtils.createTranslatedShape(shape, 551 transX1, transY1); 552 } 553 else if (plot.getOrientation() == PlotOrientation.HORIZONTAL) { 554 shape = ShapeUtils.createTranslatedShape(shape, 555 transY1, transX1); 556 } 557 if (!nullPoint) { 558 if (getShapePaint() != null) { 559 g2.setPaint(getShapePaint()); 560 } 561 else { 562 g2.setPaint(seriesPaint); 563 } 564 if (getShapeStroke() != null) { 565 g2.setStroke(getShapeStroke()); 566 } 567 else { 568 g2.setStroke(seriesStroke); 569 } 570 g2.draw(shape); 571 } 572 } 573 else { 574 if (plot.getOrientation() == PlotOrientation.VERTICAL) { 575 shape = new Rectangle2D.Double(transX1 - 3, transY1 - 3, 576 6.0, 6.0); 577 } 578 else if (plot.getOrientation() == PlotOrientation.HORIZONTAL) { 579 shape = new Rectangle2D.Double(transY1 - 3, transX1 - 3, 580 6.0, 6.0); 581 } 582 } 583 584 // collect entity and tool tip information... 585 if (state.getInfo() != null) { 586 EntityCollection entities = state.getEntityCollection(); 587 if (entities != null && shape != null && !nullPoint) { 588 // limit the entity hotspot area to the data area 589 Area dataAreaHotspot = new Area(shape); 590 dataAreaHotspot.intersect(new Area(dataArea)); 591 if (!dataAreaHotspot.isEmpty()) { 592 String tip = null; 593 XYToolTipGenerator generator = getToolTipGenerator( 594 series, item); 595 if (generator != null) { 596 tip = generator.generateToolTip(dataset, series, 597 item); 598 } 599 String url = null; 600 if (getURLGenerator() != null) { 601 url = getURLGenerator().generateURL(dataset, series, 602 item); 603 } 604 XYItemEntity entity = new XYItemEntity(dataAreaHotspot, 605 dataset, series, item, tip, url); 606 entities.add(entity); 607 } 608 } 609 } 610 611 } 612 } 613 614 /** 615 * Calculates the stacked value of the all series up to, but not including 616 * {@code series} for the specified item. It returns 0.0 if 617 * {@code series} is the first series, i.e. 0. 618 * 619 * @param dataset the dataset. 620 * @param series the series. 621 * @param index the index. 622 * 623 * @return The cumulative value for all series' values up to but excluding 624 * {@code series} for {@code index}. 625 */ 626 protected double getPreviousHeight(TableXYDataset dataset, 627 int series, int index) { 628 double result = 0.0; 629 for (int i = 0; i < series; i++) { 630 double value = dataset.getYValue(i, index); 631 if (!Double.isNaN(value)) { 632 result += value; 633 } 634 } 635 return result; 636 } 637 638 /** 639 * Tests the renderer for equality with an arbitrary object. 640 * 641 * @param obj the object ({@code null} permitted). 642 * 643 * @return A boolean. 644 */ 645 @Override 646 public boolean equals(Object obj) { 647 if (obj == this) { 648 return true; 649 } 650 if (!(obj instanceof StackedXYAreaRenderer) || !super.equals(obj)) { 651 return false; 652 } 653 StackedXYAreaRenderer that = (StackedXYAreaRenderer) obj; 654 if (!PaintUtils.equal(this.shapePaint, that.shapePaint)) { 655 return false; 656 } 657 if (!ObjectUtils.equal(this.shapeStroke, that.shapeStroke)) { 658 return false; 659 } 660 return true; 661 } 662 663 /** 664 * Returns a clone of the renderer. 665 * 666 * @return A clone. 667 * 668 * @throws CloneNotSupportedException if the renderer cannot be cloned. 669 */ 670 @Override 671 public Object clone() throws CloneNotSupportedException { 672 return super.clone(); 673 } 674 675 /** 676 * Provides serialization support. 677 * 678 * @param stream the input stream. 679 * 680 * @throws IOException if there is an I/O error. 681 * @throws ClassNotFoundException if there is a classpath problem. 682 */ 683 private void readObject(ObjectInputStream stream) 684 throws IOException, ClassNotFoundException { 685 stream.defaultReadObject(); 686 this.shapePaint = SerialUtils.readPaint(stream); 687 this.shapeStroke = SerialUtils.readStroke(stream); 688 } 689 690 /** 691 * Provides serialization support. 692 * 693 * @param stream the output stream. 694 * 695 * @throws IOException if there is an I/O error. 696 */ 697 private void writeObject(ObjectOutputStream stream) throws IOException { 698 stream.defaultWriteObject(); 699 SerialUtils.writePaint(this.shapePaint, stream); 700 SerialUtils.writeStroke(this.shapeStroke, stream); 701 } 702 703}