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 * ScatterRenderer.java
029 * --------------------
030 * (C) Copyright 2007-2016, by Object Refinery Limited and Contributors.
031 *
032 * Original Author:  David Gilbert (for Object Refinery Limited);
033 * Contributor(s):   David Forslund;
034 *                   Peter Kolb (patches 2497611, 2791407);
035 *
036 * Changes
037 * -------
038 * 08-Oct-2007 : Version 1, based on patch 1780779 by David Forslund (DG);
039 * 11-Oct-2007 : Renamed ScatterRenderer (DG);
040 * 17-Jun-2008 : Apply legend shape, font and paint attributes (DG);
041 * 14-Jan-2009 : Added support for seriesVisible flags (PK);
042 * 16-May-2009 : Patch 2791407 - findRangeBounds() override (PK);
043 *
044 */
045
046package org.jfree.chart.renderer.category;
047
048import java.awt.Graphics2D;
049import java.awt.Paint;
050import java.awt.Shape;
051import java.awt.Stroke;
052import java.awt.geom.Line2D;
053import java.awt.geom.Rectangle2D;
054import java.io.IOException;
055import java.io.ObjectInputStream;
056import java.io.ObjectOutputStream;
057import java.io.Serializable;
058import java.util.List;
059
060import org.jfree.chart.LegendItem;
061import org.jfree.chart.axis.CategoryAxis;
062import org.jfree.chart.axis.ValueAxis;
063import org.jfree.chart.event.RendererChangeEvent;
064import org.jfree.chart.plot.CategoryPlot;
065import org.jfree.chart.plot.PlotOrientation;
066import org.jfree.chart.util.BooleanList;
067import org.jfree.chart.util.ObjectUtils;
068import org.jfree.chart.util.PublicCloneable;
069import org.jfree.chart.util.ShapeUtils;
070import org.jfree.data.Range;
071import org.jfree.data.category.CategoryDataset;
072import org.jfree.data.statistics.MultiValueCategoryDataset;
073
074/**
075 * A renderer that handles the multiple values from a
076 * {@link MultiValueCategoryDataset} by plotting a shape for each value for
077 * each given item in the dataset. The example shown here is generated by
078 * the {@code ScatterRendererDemo1.java} program included in the
079 * JFreeChart Demo Collection:
080 * <br><br>
081 * <img src="../../../../../images/ScatterRendererSample.png"
082 * alt="ScatterRendererSample.png">
083 *
084 * @since 1.0.7
085 */
086public class ScatterRenderer extends AbstractCategoryItemRenderer
087        implements Cloneable, PublicCloneable, Serializable {
088
089    /**
090     * A table of flags that control (per series) whether or not shapes are
091     * filled.
092     */
093    private BooleanList seriesShapesFilled;
094
095    /**
096     * The default value returned by the getShapeFilled() method.
097     */
098    private boolean baseShapesFilled;
099
100    /**
101     * A flag that controls whether the fill paint is used for filling
102     * shapes.
103     */
104    private boolean useFillPaint;
105
106    /**
107     * A flag that controls whether outlines are drawn for shapes.
108     */
109    private boolean drawOutlines;
110
111    /**
112     * A flag that controls whether the outline paint is used for drawing shape
113     * outlines - if not, the regular series paint is used.
114     */
115    private boolean useOutlinePaint;
116
117    /**
118     * A flag that controls whether or not the x-position for each item is
119     * offset within the category according to the series.
120     */
121    private boolean useSeriesOffset;
122
123    /**
124     * The item margin used for series offsetting - this allows the positioning
125     * to match the bar positions of the {@link BarRenderer} class.
126     */
127    private double itemMargin;
128
129    /**
130     * Constructs a new renderer.
131     */
132    public ScatterRenderer() {
133        this.seriesShapesFilled = new BooleanList();
134        this.baseShapesFilled = true;
135        this.useFillPaint = false;
136        this.drawOutlines = false;
137        this.useOutlinePaint = false;
138        this.useSeriesOffset = true;
139        this.itemMargin = 0.20;
140    }
141
142    /**
143     * Returns the flag that controls whether or not the x-position for each
144     * data item is offset within the category according to the series.
145     *
146     * @return A boolean.
147     *
148     * @see #setUseSeriesOffset(boolean)
149     */
150    public boolean getUseSeriesOffset() {
151        return this.useSeriesOffset;
152    }
153
154    /**
155     * Sets the flag that controls whether or not the x-position for each
156     * data item is offset within its category according to the series, and
157     * sends a {@link RendererChangeEvent} to all registered listeners.
158     *
159     * @param offset  the offset.
160     *
161     * @see #getUseSeriesOffset()
162     */
163    public void setUseSeriesOffset(boolean offset) {
164        this.useSeriesOffset = offset;
165        fireChangeEvent();
166    }
167
168    /**
169     * Returns the item margin, which is the gap between items within a
170     * category (expressed as a percentage of the overall category width).
171     * This can be used to match the offset alignment with the bars drawn by
172     * a {@link BarRenderer}).
173     *
174     * @return The item margin.
175     *
176     * @see #setItemMargin(double)
177     * @see #getUseSeriesOffset()
178     */
179    public double getItemMargin() {
180        return this.itemMargin;
181    }
182
183    /**
184     * Sets the item margin, which is the gap between items within a category
185     * (expressed as a percentage of the overall category width), and sends
186     * a {@link RendererChangeEvent} to all registered listeners.
187     *
188     * @param margin  the margin (0.0 &lt;= margin &lt; 1.0).
189     *
190     * @see #getItemMargin()
191     * @see #getUseSeriesOffset()
192     */
193    public void setItemMargin(double margin) {
194        if (margin < 0.0 || margin >= 1.0) {
195            throw new IllegalArgumentException("Requires 0.0 <= margin < 1.0.");
196        }
197        this.itemMargin = margin;
198        fireChangeEvent();
199    }
200
201    /**
202     * Returns {@code true} if outlines should be drawn for shapes, and
203     * {@code false} otherwise.
204     *
205     * @return A boolean.
206     *
207     * @see #setDrawOutlines(boolean)
208     */
209    public boolean getDrawOutlines() {
210        return this.drawOutlines;
211    }
212
213    /**
214     * Sets the flag that controls whether outlines are drawn for
215     * shapes, and sends a {@link RendererChangeEvent} to all registered
216     * listeners.
217     * <p>In some cases, shapes look better if they do NOT have an outline, but
218     * this flag allows you to set your own preference.</p>
219     *
220     * @param flag the flag.
221     *
222     * @see #getDrawOutlines()
223     */
224    public void setDrawOutlines(boolean flag) {
225        this.drawOutlines = flag;
226        fireChangeEvent();
227    }
228
229    /**
230     * Returns the flag that controls whether the outline paint is used for
231     * shape outlines.  If not, the regular series paint is used.
232     *
233     * @return A boolean.
234     *
235     * @see #setUseOutlinePaint(boolean)
236     */
237    public boolean getUseOutlinePaint() {
238        return this.useOutlinePaint;
239    }
240
241    /**
242     * Sets the flag that controls whether the outline paint is used for shape
243     * outlines, and sends a {@link RendererChangeEvent} to all registered
244     * listeners.
245     *
246     * @param use the flag.
247     *
248     * @see #getUseOutlinePaint()
249     */
250    public void setUseOutlinePaint(boolean use) {
251        this.useOutlinePaint = use;
252        fireChangeEvent();
253    }
254
255    // SHAPES FILLED
256
257    /**
258     * Returns the flag used to control whether or not the shape for an item
259     * is filled. The default implementation passes control to the
260     * {@code getSeriesShapesFilled} method. You can override this method
261     * if you require different behaviour.
262     *
263     * @param series the series index (zero-based).
264     * @param item   the item index (zero-based).
265     * @return A boolean.
266     */
267    public boolean getItemShapeFilled(int series, int item) {
268        return getSeriesShapesFilled(series);
269    }
270
271    /**
272     * Returns the flag used to control whether or not the shapes for a series
273     * are filled.
274     *
275     * @param series the series index (zero-based).
276     * @return A boolean.
277     */
278    public boolean getSeriesShapesFilled(int series) {
279        Boolean flag = this.seriesShapesFilled.getBoolean(series);
280        if (flag != null) {
281            return flag;
282        }
283        else {
284            return this.baseShapesFilled;
285        }
286
287    }
288
289    /**
290     * Sets the 'shapes filled' flag for a series and sends a
291     * {@link RendererChangeEvent} to all registered listeners.
292     *
293     * @param series the series index (zero-based).
294     * @param filled the flag.
295     */
296    public void setSeriesShapesFilled(int series, Boolean filled) {
297        this.seriesShapesFilled.setBoolean(series, filled);
298        fireChangeEvent();
299    }
300
301    /**
302     * Sets the 'shapes filled' flag for a series and sends a
303     * {@link RendererChangeEvent} to all registered listeners.
304     *
305     * @param series the series index (zero-based).
306     * @param filled the flag.
307     */
308    public void setSeriesShapesFilled(int series, boolean filled) {
309        this.seriesShapesFilled.setBoolean(series, filled);
310        fireChangeEvent();
311    }
312
313    /**
314     * Returns the base 'shape filled' attribute.
315     *
316     * @return The base flag.
317     */
318    public boolean getBaseShapesFilled() {
319        return this.baseShapesFilled;
320    }
321
322    /**
323     * Sets the base 'shapes filled' flag and sends a
324     * {@link RendererChangeEvent} to all registered listeners.
325     *
326     * @param flag the flag.
327     */
328    public void setBaseShapesFilled(boolean flag) {
329        this.baseShapesFilled = flag;
330        fireChangeEvent();
331    }
332
333    /**
334     * Returns {@code true} if the renderer should use the fill paint
335     * setting to fill shapes, and {@code false} if it should just
336     * use the regular paint.
337     *
338     * @return A boolean.
339     */
340    public boolean getUseFillPaint() {
341        return this.useFillPaint;
342    }
343
344    /**
345     * Sets the flag that controls whether the fill paint is used to fill
346     * shapes, and sends a {@link RendererChangeEvent} to all
347     * registered listeners.
348     *
349     * @param flag the flag.
350     */
351    public void setUseFillPaint(boolean flag) {
352        this.useFillPaint = flag;
353        fireChangeEvent();
354    }
355
356    /**
357     * Returns the range of values the renderer requires to display all the
358     * items from the specified dataset. This takes into account the range
359     * between the min/max values, possibly ignoring invisible series.
360     *
361     * @param dataset  the dataset ({@code null} permitted).
362     *
363     * @return The range (or {@code null} if the dataset is
364     *         {@code null} or empty).
365     */
366    @Override
367    public Range findRangeBounds(CategoryDataset dataset) {
368         return findRangeBounds(dataset, true);
369    }
370
371    /**
372     * Draw a single data item.
373     *
374     * @param g2  the graphics device.
375     * @param state  the renderer state.
376     * @param dataArea  the area in which the data is drawn.
377     * @param plot  the plot.
378     * @param domainAxis  the domain axis.
379     * @param rangeAxis  the range axis.
380     * @param dataset  the dataset.
381     * @param row  the row index (zero-based).
382     * @param column  the column index (zero-based).
383     * @param pass  the pass index.
384     */
385    @Override
386    public void drawItem(Graphics2D g2, CategoryItemRendererState state,
387            Rectangle2D dataArea, CategoryPlot plot, CategoryAxis domainAxis,
388            ValueAxis rangeAxis, CategoryDataset dataset, int row, int column,
389            int pass) {
390
391        // do nothing if item is not visible
392        if (!getItemVisible(row, column)) {
393            return;
394        }
395        int visibleRow = state.getVisibleSeriesIndex(row);
396        if (visibleRow < 0) {
397            return;
398        }
399        int visibleRowCount = state.getVisibleSeriesCount();
400
401        PlotOrientation orientation = plot.getOrientation();
402
403        MultiValueCategoryDataset d = (MultiValueCategoryDataset) dataset;
404        List values = d.getValues(row, column);
405        if (values == null) {
406            return;
407        }
408        int valueCount = values.size();
409        for (int i = 0; i < valueCount; i++) {
410            // current data point...
411            double x1;
412            if (this.useSeriesOffset) {
413                x1 = domainAxis.getCategorySeriesMiddle(column, 
414                        dataset.getColumnCount(), visibleRow, visibleRowCount,
415                        this.itemMargin, dataArea, plot.getDomainAxisEdge());
416            }
417            else {
418                x1 = domainAxis.getCategoryMiddle(column, getColumnCount(),
419                        dataArea, plot.getDomainAxisEdge());
420            }
421            Number n = (Number) values.get(i);
422            double value = n.doubleValue();
423            double y1 = rangeAxis.valueToJava2D(value, dataArea,
424                    plot.getRangeAxisEdge());
425
426            Shape shape = getItemShape(row, column);
427            if (orientation == PlotOrientation.HORIZONTAL) {
428                shape = ShapeUtils.createTranslatedShape(shape, y1, x1);
429            }
430            else if (orientation == PlotOrientation.VERTICAL) {
431                shape = ShapeUtils.createTranslatedShape(shape, x1, y1);
432            }
433            if (getItemShapeFilled(row, column)) {
434                if (this.useFillPaint) {
435                    g2.setPaint(getItemFillPaint(row, column));
436                }
437                else {
438                    g2.setPaint(getItemPaint(row, column));
439                }
440                g2.fill(shape);
441            }
442            if (this.drawOutlines) {
443                if (this.useOutlinePaint) {
444                    g2.setPaint(getItemOutlinePaint(row, column));
445                }
446                else {
447                    g2.setPaint(getItemPaint(row, column));
448                }
449                g2.setStroke(getItemOutlineStroke(row, column));
450                g2.draw(shape);
451            }
452        }
453
454    }
455
456    /**
457     * Returns a legend item for a series.
458     *
459     * @param datasetIndex  the dataset index (zero-based).
460     * @param series  the series index (zero-based).
461     *
462     * @return The legend item.
463     */
464    @Override
465    public LegendItem getLegendItem(int datasetIndex, int series) {
466
467        CategoryPlot cp = getPlot();
468        if (cp == null) {
469            return null;
470        }
471
472        if (isSeriesVisible(series) && isSeriesVisibleInLegend(series)) {
473            CategoryDataset dataset = cp.getDataset(datasetIndex);
474            String label = getLegendItemLabelGenerator().generateLabel(
475                    dataset, series);
476            String description = label;
477            String toolTipText = null;
478            if (getLegendItemToolTipGenerator() != null) {
479                toolTipText = getLegendItemToolTipGenerator().generateLabel(
480                        dataset, series);
481            }
482            String urlText = null;
483            if (getLegendItemURLGenerator() != null) {
484                urlText = getLegendItemURLGenerator().generateLabel(
485                        dataset, series);
486            }
487            Shape shape = lookupLegendShape(series);
488            Paint paint = lookupSeriesPaint(series);
489            Paint fillPaint = (this.useFillPaint
490                    ? getItemFillPaint(series, 0) : paint);
491            boolean shapeOutlineVisible = this.drawOutlines;
492            Paint outlinePaint = (this.useOutlinePaint
493                    ? getItemOutlinePaint(series, 0) : paint);
494            Stroke outlineStroke = lookupSeriesOutlineStroke(series);
495            LegendItem result = new LegendItem(label, description, toolTipText,
496                    urlText, true, shape, getItemShapeFilled(series, 0),
497                    fillPaint, shapeOutlineVisible, outlinePaint, outlineStroke,
498                    false, new Line2D.Double(-7.0, 0.0, 7.0, 0.0),
499                    getItemStroke(series, 0), getItemPaint(series, 0));
500            result.setLabelFont(lookupLegendTextFont(series));
501            Paint labelPaint = lookupLegendTextPaint(series);
502            if (labelPaint != null) {
503                result.setLabelPaint(labelPaint);
504            }
505            result.setDataset(dataset);
506            result.setDatasetIndex(datasetIndex);
507            result.setSeriesKey(dataset.getRowKey(series));
508            result.setSeriesIndex(series);
509            return result;
510        }
511        return null;
512
513    }
514
515    /**
516     * Tests this renderer for equality with an arbitrary object.
517     *
518     * @param obj the object ({@code null} permitted).
519     * @return A boolean.
520     */
521    @Override
522    public boolean equals(Object obj) {
523        if (obj == this) {
524            return true;
525        }
526        if (!(obj instanceof ScatterRenderer)) {
527            return false;
528        }
529        ScatterRenderer that = (ScatterRenderer) obj;
530        if (!ObjectUtils.equal(this.seriesShapesFilled,
531                that.seriesShapesFilled)) {
532            return false;
533        }
534        if (this.baseShapesFilled != that.baseShapesFilled) {
535            return false;
536        }
537        if (this.useFillPaint != that.useFillPaint) {
538            return false;
539        }
540        if (this.drawOutlines != that.drawOutlines) {
541            return false;
542        }
543        if (this.useOutlinePaint != that.useOutlinePaint) {
544            return false;
545        }
546        if (this.useSeriesOffset != that.useSeriesOffset) {
547            return false;
548        }
549        if (this.itemMargin != that.itemMargin) {
550            return false;
551        }
552        return super.equals(obj);
553    }
554
555    /**
556     * Returns an independent copy of the renderer.
557     *
558     * @return A clone.
559     *
560     * @throws CloneNotSupportedException  should not happen.
561     */
562    @Override
563    public Object clone() throws CloneNotSupportedException {
564        ScatterRenderer clone = (ScatterRenderer) super.clone();
565        clone.seriesShapesFilled
566                = (BooleanList) this.seriesShapesFilled.clone();
567        return clone;
568    }
569
570    /**
571     * Provides serialization support.
572     *
573     * @param stream the output stream.
574     * @throws java.io.IOException if there is an I/O error.
575     */
576    private void writeObject(ObjectOutputStream stream) throws IOException {
577        stream.defaultWriteObject();
578
579    }
580
581    /**
582     * Provides serialization support.
583     *
584     * @param stream the input stream.
585     * @throws java.io.IOException    if there is an I/O error.
586     * @throws ClassNotFoundException if there is a classpath problem.
587     */
588    private void readObject(ObjectInputStream stream)
589            throws IOException, ClassNotFoundException {
590        stream.defaultReadObject();
591
592    }
593
594}