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