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 * XYBlockRenderer.java
029 * --------------------
030 * (C) Copyright 2006-2017, by Object Refinery Limited.
031 *
032 * Original Author:  David Gilbert (for Object Refinery Limited);
033 * Contributor(s):   -;
034 *
035 * Changes
036 * -------
037 * 05-Jul-2006 : Version 1 (DG);
038 * 02-Feb-2007 : Added getPaintScale() method (DG);
039 * 09-Mar-2007 : Fixed cloning (DG);
040 * 03-Aug-2007 : Fix for bug 1766646 (DG);
041 * 07-Apr-2008 : Added entity collection code (DG);
042 * 22-Apr-2008 : Implemented PublicCloneable (DG);
043 * 03-Jul-2013 : Use ParamChecks (DG);
044 * 20-Feb-2017 : Add update for crosshairs (DG);
045 *
046 */
047
048package org.jfree.chart.renderer.xy;
049
050import java.awt.BasicStroke;
051import java.awt.Graphics2D;
052import java.awt.Paint;
053import java.awt.geom.Rectangle2D;
054import java.io.Serializable;
055
056import org.jfree.chart.axis.ValueAxis;
057import org.jfree.chart.entity.EntityCollection;
058import org.jfree.chart.event.RendererChangeEvent;
059import org.jfree.chart.plot.CrosshairState;
060import org.jfree.chart.plot.PlotOrientation;
061import org.jfree.chart.plot.PlotRenderingInfo;
062import org.jfree.chart.plot.XYPlot;
063import org.jfree.chart.renderer.LookupPaintScale;
064import org.jfree.chart.renderer.PaintScale;
065import org.jfree.chart.ui.RectangleAnchor;
066import org.jfree.chart.util.Args;
067import org.jfree.chart.util.PublicCloneable;
068import org.jfree.data.Range;
069import org.jfree.data.general.DatasetUtils;
070import org.jfree.data.xy.XYDataset;
071import org.jfree.data.xy.XYZDataset;
072
073/**
074 * A renderer that represents data from an {@link XYZDataset} by drawing a
075 * color block at each (x, y) point, where the color is a function of the
076 * z-value from the dataset.  The example shown here is generated by the
077 * {@code XYBlockChartDemo1.java} program included in the JFreeChart
078 * demo collection:
079 * <br><br>
080 * <img src="../../../../../images/XYBlockRendererSample.png"
081 * alt="XYBlockRendererSample.png">
082 *
083 * @since 1.0.4
084 */
085public class XYBlockRenderer extends AbstractXYItemRenderer
086        implements XYItemRenderer, Cloneable, PublicCloneable, Serializable {
087
088    /**
089     * The block width (defaults to 1.0).
090     */
091    private double blockWidth = 1.0;
092
093    /**
094     * The block height (defaults to 1.0).
095     */
096    private double blockHeight = 1.0;
097
098    /**
099     * The anchor point used to align each block to its (x, y) location.  The
100     * default value is {@code RectangleAnchor.CENTER}.
101     */
102    private RectangleAnchor blockAnchor = RectangleAnchor.CENTER;
103
104    /** Temporary storage for the x-offset used to align the block anchor. */
105    private double xOffset;
106
107    /** Temporary storage for the y-offset used to align the block anchor. */
108    private double yOffset;
109
110    /** The paint scale. */
111    private PaintScale paintScale;
112
113    /**
114     * Creates a new {@code XYBlockRenderer} instance with default
115     * attributes.
116     */
117    public XYBlockRenderer() {
118        updateOffsets();
119        this.paintScale = new LookupPaintScale();
120    }
121
122    /**
123     * Returns the block width, in data/axis units.
124     *
125     * @return The block width.
126     *
127     * @see #setBlockWidth(double)
128     */
129    public double getBlockWidth() {
130        return this.blockWidth;
131    }
132
133    /**
134     * Sets the width of the blocks used to represent each data item and
135     * sends a {@link RendererChangeEvent} to all registered listeners.
136     *
137     * @param width  the new width, in data/axis units (must be &gt; 0.0).
138     *
139     * @see #getBlockWidth()
140     */
141    public void setBlockWidth(double width) {
142        if (width <= 0.0) {
143            throw new IllegalArgumentException(
144                    "The 'width' argument must be > 0.0");
145        }
146        this.blockWidth = width;
147        updateOffsets();
148        fireChangeEvent();
149    }
150
151    /**
152     * Returns the block height, in data/axis units.
153     *
154     * @return The block height.
155     *
156     * @see #setBlockHeight(double)
157     */
158    public double getBlockHeight() {
159        return this.blockHeight;
160    }
161
162    /**
163     * Sets the height of the blocks used to represent each data item and
164     * sends a {@link RendererChangeEvent} to all registered listeners.
165     *
166     * @param height  the new height, in data/axis units (must be &gt; 0.0).
167     *
168     * @see #getBlockHeight()
169     */
170    public void setBlockHeight(double height) {
171        if (height <= 0.0) {
172            throw new IllegalArgumentException(
173                    "The 'height' argument must be > 0.0");
174        }
175        this.blockHeight = height;
176        updateOffsets();
177        fireChangeEvent();
178    }
179
180    /**
181     * Returns the anchor point used to align a block at its (x, y) location.
182     * The default values is {@link RectangleAnchor#CENTER}.
183     *
184     * @return The anchor point (never {@code null}).
185     *
186     * @see #setBlockAnchor(RectangleAnchor)
187     */
188    public RectangleAnchor getBlockAnchor() {
189        return this.blockAnchor;
190    }
191
192    /**
193     * Sets the anchor point used to align a block at its (x, y) location and
194     * sends a {@link RendererChangeEvent} to all registered listeners.
195     *
196     * @param anchor  the anchor.
197     *
198     * @see #getBlockAnchor()
199     */
200    public void setBlockAnchor(RectangleAnchor anchor) {
201        Args.nullNotPermitted(anchor, "anchor");
202        if (this.blockAnchor.equals(anchor)) {
203            return;  // no change
204        }
205        this.blockAnchor = anchor;
206        updateOffsets();
207        fireChangeEvent();
208    }
209
210    /**
211     * Returns the paint scale used by the renderer.
212     *
213     * @return The paint scale (never {@code null}).
214     *
215     * @see #setPaintScale(PaintScale)
216     * @since 1.0.4
217     */
218    public PaintScale getPaintScale() {
219        return this.paintScale;
220    }
221
222    /**
223     * Sets the paint scale used by the renderer and sends a
224     * {@link RendererChangeEvent} to all registered listeners.
225     *
226     * @param scale  the scale ({@code null} not permitted).
227     *
228     * @see #getPaintScale()
229     * @since 1.0.4
230     */
231    public void setPaintScale(PaintScale scale) {
232        Args.nullNotPermitted(scale, "scale");
233        this.paintScale = scale;
234        fireChangeEvent();
235    }
236
237    /**
238     * Updates the offsets to take into account the block width, height and
239     * anchor.
240     */
241    private void updateOffsets() {
242        if (this.blockAnchor.equals(RectangleAnchor.BOTTOM_LEFT)) {
243            this.xOffset = 0.0;
244            this.yOffset = 0.0;
245        }
246        else if (this.blockAnchor.equals(RectangleAnchor.BOTTOM)) {
247            this.xOffset = -this.blockWidth / 2.0;
248            this.yOffset = 0.0;
249        }
250        else if (this.blockAnchor.equals(RectangleAnchor.BOTTOM_RIGHT)) {
251            this.xOffset = -this.blockWidth;
252            this.yOffset = 0.0;
253        }
254        else if (this.blockAnchor.equals(RectangleAnchor.LEFT)) {
255            this.xOffset = 0.0;
256            this.yOffset = -this.blockHeight / 2.0;
257        }
258        else if (this.blockAnchor.equals(RectangleAnchor.CENTER)) {
259            this.xOffset = -this.blockWidth / 2.0;
260            this.yOffset = -this.blockHeight / 2.0;
261        }
262        else if (this.blockAnchor.equals(RectangleAnchor.RIGHT)) {
263            this.xOffset = -this.blockWidth;
264            this.yOffset = -this.blockHeight / 2.0;
265        }
266        else if (this.blockAnchor.equals(RectangleAnchor.TOP_LEFT)) {
267            this.xOffset = 0.0;
268            this.yOffset = -this.blockHeight;
269        }
270        else if (this.blockAnchor.equals(RectangleAnchor.TOP)) {
271            this.xOffset = -this.blockWidth / 2.0;
272            this.yOffset = -this.blockHeight;
273        }
274        else if (this.blockAnchor.equals(RectangleAnchor.TOP_RIGHT)) {
275            this.xOffset = -this.blockWidth;
276            this.yOffset = -this.blockHeight;
277        }
278    }
279
280    /**
281     * Returns the lower and upper bounds (range) of the x-values in the
282     * specified dataset.
283     *
284     * @param dataset  the dataset ({@code null} permitted).
285     *
286     * @return The range ({@code null} if the dataset is {@code null}
287     *         or empty).
288     *
289     * @see #findRangeBounds(XYDataset)
290     */
291    @Override
292    public Range findDomainBounds(XYDataset dataset) {
293        if (dataset == null) {
294            return null;
295        }
296        Range r = DatasetUtils.findDomainBounds(dataset, false);
297        if (r == null) {
298            return null;
299        }
300        return new Range(r.getLowerBound() + this.xOffset,
301                         r.getUpperBound() + this.blockWidth + this.xOffset);
302    }
303
304    /**
305     * Returns the range of values the renderer requires to display all the
306     * items from the specified dataset.
307     *
308     * @param dataset  the dataset ({@code null} permitted).
309     *
310     * @return The range ({@code null} if the dataset is {@code null}
311     *         or empty).
312     *
313     * @see #findDomainBounds(XYDataset)
314     */
315    @Override
316    public Range findRangeBounds(XYDataset dataset) {
317        if (dataset != null) {
318            Range r = DatasetUtils.findRangeBounds(dataset, false);
319            if (r == null) {
320                return null;
321            }
322            else {
323                return new Range(r.getLowerBound() + this.yOffset,
324                        r.getUpperBound() + this.blockHeight + this.yOffset);
325            }
326        }
327        else {
328            return null;
329        }
330    }
331
332    /**
333     * Draws the block representing the specified item.
334     *
335     * @param g2  the graphics device.
336     * @param state  the state.
337     * @param dataArea  the data area.
338     * @param info  the plot rendering info.
339     * @param plot  the plot.
340     * @param domainAxis  the x-axis.
341     * @param rangeAxis  the y-axis.
342     * @param dataset  the dataset.
343     * @param series  the series index.
344     * @param item  the item index.
345     * @param crosshairState  the crosshair state.
346     * @param pass  the pass index.
347     */
348    @Override
349    public void drawItem(Graphics2D g2, XYItemRendererState state,
350            Rectangle2D dataArea, PlotRenderingInfo info, XYPlot plot,
351            ValueAxis domainAxis, ValueAxis rangeAxis, XYDataset dataset,
352            int series, int item, CrosshairState crosshairState, int pass) {
353
354        double x = dataset.getXValue(series, item);
355        double y = dataset.getYValue(series, item);
356        double z = 0.0;
357        if (dataset instanceof XYZDataset) {
358            z = ((XYZDataset) dataset).getZValue(series, item);
359        }
360
361        Paint p = this.paintScale.getPaint(z);
362        double xx0 = domainAxis.valueToJava2D(x + this.xOffset, dataArea,
363                plot.getDomainAxisEdge());
364        double yy0 = rangeAxis.valueToJava2D(y + this.yOffset, dataArea,
365                plot.getRangeAxisEdge());
366        double xx1 = domainAxis.valueToJava2D(x + this.blockWidth
367                + this.xOffset, dataArea, plot.getDomainAxisEdge());
368        double yy1 = rangeAxis.valueToJava2D(y + this.blockHeight
369                + this.yOffset, dataArea, plot.getRangeAxisEdge());
370        Rectangle2D block;
371        PlotOrientation orientation = plot.getOrientation();
372        if (orientation.equals(PlotOrientation.HORIZONTAL)) {
373            block = new Rectangle2D.Double(Math.min(yy0, yy1),
374                    Math.min(xx0, xx1), Math.abs(yy1 - yy0),
375                    Math.abs(xx0 - xx1));
376        }
377        else {
378            block = new Rectangle2D.Double(Math.min(xx0, xx1),
379                    Math.min(yy0, yy1), Math.abs(xx1 - xx0),
380                    Math.abs(yy1 - yy0));
381        }
382        g2.setPaint(p);
383        g2.fill(block);
384        g2.setStroke(new BasicStroke(1.0f));
385        g2.draw(block);
386
387        if (isItemLabelVisible(series, item)) {
388            drawItemLabel(g2, orientation, dataset, series, item, 
389                    block.getCenterX(), block.getCenterY(), y < 0.0);
390        }
391
392        int datasetIndex = plot.indexOf(dataset);
393        double transX = domainAxis.valueToJava2D(x, dataArea,
394                plot.getDomainAxisEdge());
395        double transY = rangeAxis.valueToJava2D(y, dataArea,
396                plot.getRangeAxisEdge());        
397        updateCrosshairValues(crosshairState, x, y, datasetIndex,
398                transX, transY, orientation);
399
400        EntityCollection entities = state.getEntityCollection();
401        if (entities != null) {
402            addEntity(entities, block, dataset, series, item, 
403                    block.getCenterX(), block.getCenterY());
404        }
405
406    }
407
408    /**
409     * Tests this {@code XYBlockRenderer} for equality with an arbitrary
410     * object.  This method returns {@code true} if and only if:
411     * <ul>
412     * <li>{@code obj} is an instance of {@code XYBlockRenderer} (not
413     *     {@code null});</li>
414     * <li>{@code obj} has the same field values as this
415     *     {@code XYBlockRenderer};</li>
416     * </ul>
417     *
418     * @param obj  the object ({@code null} permitted).
419     *
420     * @return A boolean.
421     */
422    @Override
423    public boolean equals(Object obj) {
424        if (obj == this) {
425            return true;
426        }
427        if (!(obj instanceof XYBlockRenderer)) {
428            return false;
429        }
430        XYBlockRenderer that = (XYBlockRenderer) obj;
431        if (this.blockHeight != that.blockHeight) {
432            return false;
433        }
434        if (this.blockWidth != that.blockWidth) {
435            return false;
436        }
437        if (!this.blockAnchor.equals(that.blockAnchor)) {
438            return false;
439        }
440        if (!this.paintScale.equals(that.paintScale)) {
441            return false;
442        }
443        return super.equals(obj);
444    }
445
446    /**
447     * Returns a clone of this renderer.
448     *
449     * @return A clone of this renderer.
450     *
451     * @throws CloneNotSupportedException if there is a problem creating the
452     *     clone.
453     */
454    @Override
455    public Object clone() throws CloneNotSupportedException {
456        XYBlockRenderer clone = (XYBlockRenderer) super.clone();
457        if (this.paintScale instanceof PublicCloneable) {
458            PublicCloneable pc = (PublicCloneable) this.paintScale;
459            clone.paintScale = (PaintScale) pc.clone();
460        }
461        return clone;
462    }
463
464}