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 * XYBubbleRenderer.java
029 * ---------------------
030 * (C) Copyright 2003-2017, by Object Refinery Limited.
031 *
032 * Original Author:  David Gilbert (for Object Refinery Limited);
033 * Contributor(s):   Christian W. Zuckschwerdt;
034 *
035 * Changes
036 * -------
037 * 28-Jan-2003 : Version 1 (DG);
038 * 25-Mar-2003 : Implemented Serializable (DG);
039 * 01-May-2003 : Modified drawItem() method signature (DG);
040 * 30-Jul-2003 : Modified entity constructor (CZ);
041 * 20-Aug-2003 : Implemented Cloneable and PublicCloneable (DG);
042 * 16-Sep-2003 : Changed ChartRenderingInfo --> PlotRenderingInfo (DG);
043 * 10-Feb-2004 : Small change to drawItem() method to make cut-and-paste
044 *               overriding easier (DG);
045 * 15-Jul-2004 : Switched getZ() and getZValue() methods (DG);
046 * 19-Jan-2005 : Now accesses only primitives from dataset (DG);
047 * 28-Feb-2005 : Modify renderer to use circles in legend (DG);
048 * 17-Mar-2005 : Fixed bug in bubble bounds calculation (DG);
049 * 20-Apr-2005 : Use generators for legend tooltips and URLs (DG);
050 * ------------- JFREECHART 1.0.x ---------------------------------------------
051 * 13-Dec-2005 : Added support for item labels (bug 1373371) (DG);
052 * 20-Jan-2006 : Check flag for drawing item labels (DG);
053 * 21-Sep-2006 : Respect the outline paint and stroke settings (DG);
054 * 24-Jan-2007 : Added new equals() override (DG);
055 * 06-Feb-2007 : Fixed bug 1086307, crosshairs with multiple axes (DG);
056 * 20-Apr-2007 : Updated getLegendItem() for renderer change (DG);
057 * 17-May-2007 : Set datasetIndex and seriesIndex in getLegendItem() (DG);
058 * 18-May-2007 : Set dataset and seriesKey for LegendItem (DG);
059 * 13-Jun-2007 : Fixed seriesVisibility bug (DG);
060 * 17-Jun-2008 : Apply legend shape, font and paint attributes (DG);
061 * 18-Feb-2017 : Updates for crosshairs (bug #36) (DG);
062 *
063 */
064
065package org.jfree.chart.renderer.xy;
066
067import java.awt.Graphics2D;
068import java.awt.Paint;
069import java.awt.Shape;
070import java.awt.Stroke;
071import java.awt.geom.Ellipse2D;
072import java.awt.geom.Rectangle2D;
073
074import org.jfree.chart.LegendItem;
075import org.jfree.chart.axis.ValueAxis;
076import org.jfree.chart.entity.EntityCollection;
077import org.jfree.chart.plot.CrosshairState;
078import org.jfree.chart.plot.PlotOrientation;
079import org.jfree.chart.plot.PlotRenderingInfo;
080import org.jfree.chart.plot.XYPlot;
081import org.jfree.chart.ui.RectangleEdge;
082import org.jfree.chart.util.PublicCloneable;
083import org.jfree.data.xy.XYDataset;
084import org.jfree.data.xy.XYZDataset;
085
086/**
087 * A renderer that draws a circle at each data point with a diameter that is
088 * determined by the z-value in the dataset (the renderer requires the dataset
089 * to be an instance of {@link XYZDataset}.  The example shown here
090 * is generated by the {@code XYBubbleChartDemo1.java} program
091 * included in the JFreeChart demo collection:
092 * <br><br>
093 * <img src="../../../../../images/XYBubbleRendererSample.png"
094 * alt="XYBubbleRendererSample.png">
095 */
096public class XYBubbleRenderer extends AbstractXYItemRenderer
097        implements XYItemRenderer, PublicCloneable {
098
099    /** For serialization. */
100    public static final long serialVersionUID = -5221991598674249125L;
101
102    /**
103     * A constant to specify that the bubbles drawn by this renderer should be
104     * scaled on both axes (see {@link #XYBubbleRenderer(int)}).
105     */
106    public static final int SCALE_ON_BOTH_AXES = 0;
107
108    /**
109     * A constant to specify that the bubbles drawn by this renderer should be
110     * scaled on the domain axis (see {@link #XYBubbleRenderer(int)}).
111     */
112    public static final int SCALE_ON_DOMAIN_AXIS = 1;
113
114    /**
115     * A constant to specify that the bubbles drawn by this renderer should be
116     * scaled on the range axis (see {@link #XYBubbleRenderer(int)}).
117     */
118    public static final int SCALE_ON_RANGE_AXIS = 2;
119
120    /** Controls how the width and height of the bubble are scaled. */
121    private int scaleType;
122
123    /**
124     * Constructs a new renderer.
125     */
126    public XYBubbleRenderer() {
127        this(SCALE_ON_BOTH_AXES);
128    }
129
130    /**
131     * Constructs a new renderer with the specified type of scaling.
132     *
133     * @param scaleType  the type of scaling (must be one of:
134     *        {@link #SCALE_ON_BOTH_AXES}, {@link #SCALE_ON_DOMAIN_AXIS},
135     *        {@link #SCALE_ON_RANGE_AXIS}).
136     */
137    public XYBubbleRenderer(int scaleType) {
138        super();
139        if (scaleType < 0 || scaleType > 2) {
140            throw new IllegalArgumentException("Invalid 'scaleType'.");
141        }
142        this.scaleType = scaleType;
143        setDefaultLegendShape(new Ellipse2D.Double(-4.0, -4.0, 8.0, 8.0));
144    }
145
146    /**
147     * Returns the scale type that was set when the renderer was constructed.
148     *
149     * @return The scale type (one of: {@link #SCALE_ON_BOTH_AXES},
150     *         {@link #SCALE_ON_DOMAIN_AXIS}, {@link #SCALE_ON_RANGE_AXIS}).
151     */
152    public int getScaleType() {
153        return this.scaleType;
154    }
155
156    /**
157     * Draws the visual representation of a single data item.
158     *
159     * @param g2  the graphics device.
160     * @param state  the renderer state.
161     * @param dataArea  the area within which the data is being drawn.
162     * @param info  collects information about the drawing.
163     * @param plot  the plot (can be used to obtain standard color
164     *              information etc).
165     * @param domainAxis  the domain (horizontal) axis.
166     * @param rangeAxis  the range (vertical) axis.
167     * @param dataset  the dataset (an {@link XYZDataset} is expected).
168     * @param series  the series index (zero-based).
169     * @param item  the item index (zero-based).
170     * @param crosshairState  crosshair information for the plot
171     *                        ({@code null} permitted).
172     * @param pass  the pass index.
173     */
174    @Override
175    public void drawItem(Graphics2D g2, XYItemRendererState state,
176            Rectangle2D dataArea, PlotRenderingInfo info, XYPlot plot,
177            ValueAxis domainAxis, ValueAxis rangeAxis, XYDataset dataset,
178            int series, int item, CrosshairState crosshairState, int pass) {
179
180        // return straight away if the item is not visible
181        if (!getItemVisible(series, item)) {
182            return;
183        }
184
185        PlotOrientation orientation = plot.getOrientation();
186
187        // get the data point...
188        double x = dataset.getXValue(series, item);
189        double y = dataset.getYValue(series, item);
190        double z = Double.NaN;
191        if (dataset instanceof XYZDataset) {
192            XYZDataset xyzData = (XYZDataset) dataset;
193            z = xyzData.getZValue(series, item);
194        }
195        if (!Double.isNaN(z)) {
196            RectangleEdge domainAxisLocation = plot.getDomainAxisEdge();
197            RectangleEdge rangeAxisLocation = plot.getRangeAxisEdge();
198            double transX = domainAxis.valueToJava2D(x, dataArea,
199                    domainAxisLocation);
200            double transY = rangeAxis.valueToJava2D(y, dataArea,
201                    rangeAxisLocation);
202
203            double transDomain;
204            double transRange;
205            double zero;
206
207            switch(getScaleType()) {
208                case SCALE_ON_DOMAIN_AXIS:
209                    zero = domainAxis.valueToJava2D(0.0, dataArea,
210                            domainAxisLocation);
211                    transDomain = domainAxis.valueToJava2D(z, dataArea,
212                            domainAxisLocation) - zero;
213                    transRange = transDomain;
214                    break;
215                case SCALE_ON_RANGE_AXIS:
216                    zero = rangeAxis.valueToJava2D(0.0, dataArea,
217                            rangeAxisLocation);
218                    transRange = zero - rangeAxis.valueToJava2D(z, dataArea,
219                            rangeAxisLocation);
220                    transDomain = transRange;
221                    break;
222                default:
223                    double zero1 = domainAxis.valueToJava2D(0.0, dataArea,
224                            domainAxisLocation);
225                    double zero2 = rangeAxis.valueToJava2D(0.0, dataArea,
226                            rangeAxisLocation);
227                    transDomain = domainAxis.valueToJava2D(z, dataArea,
228                            domainAxisLocation) - zero1;
229                    transRange = zero2 - rangeAxis.valueToJava2D(z, dataArea,
230                            rangeAxisLocation);
231            }
232            transDomain = Math.abs(transDomain);
233            transRange = Math.abs(transRange);
234            Ellipse2D circle = null;
235            if (orientation == PlotOrientation.VERTICAL) {
236                circle = new Ellipse2D.Double(transX - transDomain / 2.0,
237                        transY - transRange / 2.0, transDomain, transRange);
238            }
239            else if (orientation == PlotOrientation.HORIZONTAL) {
240                circle = new Ellipse2D.Double(transY - transRange / 2.0,
241                        transX - transDomain / 2.0, transRange, transDomain);
242            } else {
243                throw new IllegalStateException();
244            }
245            g2.setPaint(getItemPaint(series, item));
246            g2.fill(circle);
247            g2.setStroke(getItemOutlineStroke(series, item));
248            g2.setPaint(getItemOutlinePaint(series, item));
249            g2.draw(circle);
250
251            if (isItemLabelVisible(series, item)) {
252                if (orientation == PlotOrientation.VERTICAL) {
253                    drawItemLabel(g2, orientation, dataset, series, item,
254                            transX, transY, false);
255                }
256                else if (orientation == PlotOrientation.HORIZONTAL) {
257                    drawItemLabel(g2, orientation, dataset, series, item,
258                            transY, transX, false);
259                }
260            }
261
262            // add an entity if this info is being collected
263            if (info != null) {
264                EntityCollection entities 
265                        = info.getOwner().getEntityCollection();
266                if (entities != null && circle.intersects(dataArea)) {
267                    addEntity(entities, circle, dataset, series, item,
268                            circle.getCenterX(), circle.getCenterY());
269                }
270            }
271
272            int datasetIndex = plot.indexOf(dataset);
273            updateCrosshairValues(crosshairState, x, y, datasetIndex,
274                    transX, transY, orientation);
275        }
276
277    }
278
279    /**
280     * Returns a legend item for the specified series.  The default method
281     * is overridden so that the legend displays circles for all series.
282     *
283     * @param datasetIndex  the dataset index (zero-based).
284     * @param series  the series index (zero-based).
285     *
286     * @return A legend item for the series.
287     */
288    @Override
289    public LegendItem getLegendItem(int datasetIndex, int series) {
290        LegendItem result = null;
291        XYPlot plot = getPlot();
292        if (plot == null) {
293            return null;
294        }
295
296        XYDataset dataset = plot.getDataset(datasetIndex);
297        if (dataset != null) {
298            if (getItemVisible(series, 0)) {
299                String label = getLegendItemLabelGenerator().generateLabel(
300                        dataset, series);
301                String description = label;
302                String toolTipText = null;
303                if (getLegendItemToolTipGenerator() != null) {
304                    toolTipText = getLegendItemToolTipGenerator().generateLabel(
305                            dataset, series);
306                }
307                String urlText = null;
308                if (getLegendItemURLGenerator() != null) {
309                    urlText = getLegendItemURLGenerator().generateLabel(
310                            dataset, series);
311                }
312                Shape shape = lookupLegendShape(series);
313                Paint paint = lookupSeriesPaint(series);
314                Paint outlinePaint = lookupSeriesOutlinePaint(series);
315                Stroke outlineStroke = lookupSeriesOutlineStroke(series);
316                result = new LegendItem(label, description, toolTipText,
317                        urlText, shape, paint, outlineStroke, outlinePaint);
318                result.setLabelFont(lookupLegendTextFont(series));
319                Paint labelPaint = lookupLegendTextPaint(series);
320                if (labelPaint != null) {
321                    result.setLabelPaint(labelPaint);
322                }
323                result.setDataset(dataset);
324                result.setDatasetIndex(datasetIndex);
325                result.setSeriesKey(dataset.getSeriesKey(series));
326                result.setSeriesIndex(series);
327            }
328        }
329        return result;
330    }
331
332    /**
333     * Tests this renderer for equality with an arbitrary object.
334     *
335     * @param obj  the object ({@code null} permitted).
336     *
337     * @return A boolean.
338     */
339    @Override
340    public boolean equals(Object obj) {
341        if (obj == this) {
342            return true;
343        }
344        if (!(obj instanceof XYBubbleRenderer)) {
345            return false;
346        }
347        XYBubbleRenderer that = (XYBubbleRenderer) obj;
348        if (this.scaleType != that.scaleType) {
349            return false;
350        }
351        return super.equals(obj);
352    }
353
354    /**
355     * Returns a clone of the renderer.
356     *
357     * @return A clone.
358     *
359     * @throws CloneNotSupportedException  if the renderer cannot be cloned.
360     */
361    @Override
362    public Object clone() throws CloneNotSupportedException {
363        return super.clone();
364    }
365
366}