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     * LevelRenderer.java
029     * ------------------
030     * (C) Copyright 2004-2008, by Object Refinery Limited.
031     *
032     * Original Author:  David Gilbert (for Object Refinery Limited);
033     * Contributor(s):   -;
034     *
035     * Changes
036     * -------
037     * 09-Jan-2004 : Version 1 (DG);
038     * 05-Nov-2004 : Modified drawItem() signature (DG);
039     * 20-Apr-2005 : Renamed CategoryLabelGenerator
040     *               --> CategoryItemLabelGenerator (DG);
041     * ------------- JFREECHART 1.0.x ---------------------------------------------
042     * 23-Jan-2006 : Renamed getMaxItemWidth() --> getMaximumItemWidth() (DG);
043     * 13-May-2008 : Code clean-up (DG);
044     * 26-Jun-2008 : Added crosshair support (DG);
045     *
046     */
047    
048    package org.jfree.chart.renderer.category;
049    
050    import java.awt.Graphics2D;
051    import java.awt.Paint;
052    import java.awt.Stroke;
053    import java.awt.geom.Line2D;
054    import java.awt.geom.Rectangle2D;
055    import java.io.Serializable;
056    
057    import org.jfree.chart.axis.CategoryAxis;
058    import org.jfree.chart.axis.ValueAxis;
059    import org.jfree.chart.entity.EntityCollection;
060    import org.jfree.chart.event.RendererChangeEvent;
061    import org.jfree.chart.labels.CategoryItemLabelGenerator;
062    import org.jfree.chart.plot.CategoryPlot;
063    import org.jfree.chart.plot.PlotOrientation;
064    import org.jfree.chart.plot.PlotRenderingInfo;
065    import org.jfree.data.category.CategoryDataset;
066    import org.jfree.ui.RectangleEdge;
067    import org.jfree.util.PublicCloneable;
068    
069    /**
070     * A {@link CategoryItemRenderer} that draws individual data items as
071     * horizontal lines, spaced in the same way as bars in a bar chart.  The
072     * example shown here is generated by the
073     * <code>OverlaidBarChartDemo2.java</code> program included in the JFreeChart
074     * Demo Collection:
075     * <br><br>
076     * <img src="../../../../../images/LevelRendererSample.png"
077     * alt="LevelRendererSample.png" />
078     */
079    public class LevelRenderer extends AbstractCategoryItemRenderer
080            implements Cloneable, PublicCloneable, Serializable {
081    
082        /** For serialization. */
083        private static final long serialVersionUID = -8204856624355025117L;
084    
085        /** The default item margin percentage. */
086        public static final double DEFAULT_ITEM_MARGIN = 0.20;
087    
088        /** The margin between items within a category. */
089        private double itemMargin;
090    
091        /** The maximum item width as a percentage of the available space. */
092        private double maxItemWidth;
093    
094        /**
095         * Creates a new renderer with default settings.
096         */
097        public LevelRenderer() {
098            super();
099            this.itemMargin = DEFAULT_ITEM_MARGIN;
100            this.maxItemWidth = 1.0;  // 100 percent, so it will not apply unless
101                                      // changed
102        }
103    
104        /**
105         * Returns the item margin.
106         *
107         * @return The margin.
108         *
109         * @see #setItemMargin(double)
110         */
111        public double getItemMargin() {
112            return this.itemMargin;
113        }
114    
115        /**
116         * Sets the item margin and sends a {@link RendererChangeEvent} to all
117         * registered listeners.  The value is expressed as a percentage of the
118         * available width for plotting all the bars, with the resulting amount to
119         * be distributed between all the bars evenly.
120         *
121         * @param percent  the new margin.
122         *
123         * @see #getItemMargin()
124         */
125        public void setItemMargin(double percent) {
126            this.itemMargin = percent;
127            fireChangeEvent();
128        }
129    
130        /**
131         * Returns the maximum width, as a percentage of the available drawing
132         * space.
133         *
134         * @return The maximum width.
135         *
136         * @see #setMaximumItemWidth(double)
137         */
138        public double getMaximumItemWidth() {
139            return getMaxItemWidth();
140        }
141    
142        /**
143         * Sets the maximum item width, which is specified as a percentage of the
144         * available space for all items, and sends a {@link RendererChangeEvent}
145         * to all registered listeners.
146         *
147         * @param percent  the percent.
148         *
149         * @see #getMaximumItemWidth()
150         */
151        public void setMaximumItemWidth(double percent) {
152            setMaxItemWidth(percent);
153        }
154    
155        /**
156         * Initialises the renderer and returns a state object that will be passed
157         * to subsequent calls to the drawItem method.
158         * <p>
159         * This method gets called once at the start of the process of drawing a
160         * chart.
161         *
162         * @param g2  the graphics device.
163         * @param dataArea  the area in which the data is to be plotted.
164         * @param plot  the plot.
165         * @param rendererIndex  the renderer index.
166         * @param info  collects chart rendering information for return to caller.
167         *
168         * @return The renderer state.
169         */
170        public CategoryItemRendererState initialise(Graphics2D g2,
171                Rectangle2D dataArea, CategoryPlot plot, int rendererIndex,
172                PlotRenderingInfo info) {
173    
174            CategoryItemRendererState state = super.initialise(g2, dataArea, plot,
175                    rendererIndex, info);
176            calculateItemWidth(plot, dataArea, rendererIndex, state);
177            return state;
178    
179        }
180    
181        /**
182         * Calculates the bar width and stores it in the renderer state.
183         *
184         * @param plot  the plot.
185         * @param dataArea  the data area.
186         * @param rendererIndex  the renderer index.
187         * @param state  the renderer state.
188         */
189        protected void calculateItemWidth(CategoryPlot plot,
190                Rectangle2D dataArea, int rendererIndex,
191                CategoryItemRendererState state) {
192    
193            CategoryAxis domainAxis = getDomainAxis(plot, rendererIndex);
194            CategoryDataset dataset = plot.getDataset(rendererIndex);
195            if (dataset != null) {
196                int columns = dataset.getColumnCount();
197                int rows = dataset.getRowCount();
198                double space = 0.0;
199                PlotOrientation orientation = plot.getOrientation();
200                if (orientation == PlotOrientation.HORIZONTAL) {
201                    space = dataArea.getHeight();
202                }
203                else if (orientation == PlotOrientation.VERTICAL) {
204                    space = dataArea.getWidth();
205                }
206                double maxWidth = space * getMaximumItemWidth();
207                double categoryMargin = 0.0;
208                double currentItemMargin = 0.0;
209                if (columns > 1) {
210                    categoryMargin = domainAxis.getCategoryMargin();
211                }
212                if (rows > 1) {
213                    currentItemMargin = getItemMargin();
214                }
215                double used = space * (1 - domainAxis.getLowerMargin()
216                                         - domainAxis.getUpperMargin()
217                                         - categoryMargin - currentItemMargin);
218                if ((rows * columns) > 0) {
219                    state.setBarWidth(Math.min(used / (rows * columns), maxWidth));
220                }
221                else {
222                    state.setBarWidth(Math.min(used, maxWidth));
223                }
224            }
225        }
226    
227        /**
228         * Calculates the coordinate of the first "side" of a bar.  This will be
229         * the minimum x-coordinate for a vertical bar, and the minimum
230         * y-coordinate for a horizontal bar.
231         *
232         * @param plot  the plot.
233         * @param orientation  the plot orientation.
234         * @param dataArea  the data area.
235         * @param domainAxis  the domain axis.
236         * @param state  the renderer state (has the bar width precalculated).
237         * @param row  the row index.
238         * @param column  the column index.
239         *
240         * @return The coordinate.
241         */
242        protected double calculateBarW0(CategoryPlot plot,
243                                        PlotOrientation orientation,
244                                        Rectangle2D dataArea,
245                                        CategoryAxis domainAxis,
246                                        CategoryItemRendererState state,
247                                        int row,
248                                        int column) {
249            // calculate bar width...
250            double space = 0.0;
251            if (orientation == PlotOrientation.HORIZONTAL) {
252                space = dataArea.getHeight();
253            }
254            else {
255                space = dataArea.getWidth();
256            }
257            double barW0 = domainAxis.getCategoryStart(column, getColumnCount(),
258                    dataArea, plot.getDomainAxisEdge());
259            int seriesCount = getRowCount();
260            int categoryCount = getColumnCount();
261            if (seriesCount > 1) {
262                double seriesGap = space * getItemMargin()
263                        / (categoryCount * (seriesCount - 1));
264                double seriesW = calculateSeriesWidth(space, domainAxis,
265                        categoryCount, seriesCount);
266                barW0 = barW0 + row * (seriesW + seriesGap)
267                              + (seriesW / 2.0) - (state.getBarWidth() / 2.0);
268            }
269            else {
270                barW0 = domainAxis.getCategoryMiddle(column, getColumnCount(),
271                        dataArea, plot.getDomainAxisEdge()) - state.getBarWidth()
272                        / 2.0;
273            }
274            return barW0;
275        }
276    
277        /**
278         * Draws the bar for a single (series, category) data item.
279         *
280         * @param g2  the graphics device.
281         * @param state  the renderer state.
282         * @param dataArea  the data area.
283         * @param plot  the plot.
284         * @param domainAxis  the domain axis.
285         * @param rangeAxis  the range axis.
286         * @param dataset  the dataset.
287         * @param row  the row index (zero-based).
288         * @param column  the column index (zero-based).
289         * @param pass  the pass index.
290         */
291        public void drawItem(Graphics2D g2, CategoryItemRendererState state,
292                Rectangle2D dataArea, CategoryPlot plot, CategoryAxis domainAxis,
293                ValueAxis rangeAxis, CategoryDataset dataset, int row, int column,
294                int pass) {
295    
296            // nothing is drawn for null values...
297            Number dataValue = dataset.getValue(row, column);
298            if (dataValue == null) {
299                return;
300            }
301    
302            double value = dataValue.doubleValue();
303    
304            PlotOrientation orientation = plot.getOrientation();
305            double barW0 = calculateBarW0(plot, orientation, dataArea, domainAxis,
306                    state, row, column);
307            RectangleEdge edge = plot.getRangeAxisEdge();
308            double barL = rangeAxis.valueToJava2D(value, dataArea, edge);
309    
310            // draw the bar...
311            Line2D line = null;
312            double x = 0.0;
313            double y = 0.0;
314            if (orientation == PlotOrientation.HORIZONTAL) {
315                x = barL;
316                y = barW0 + state.getBarWidth() / 2.0;
317                line = new Line2D.Double(barL, barW0, barL,
318                        barW0 + state.getBarWidth());
319            }
320            else {
321                x = barW0 + state.getBarWidth() / 2.0;
322                y = barL;
323                line = new Line2D.Double(barW0, barL, barW0 + state.getBarWidth(),
324                        barL);
325            }
326            Stroke itemStroke = getItemStroke(row, column);
327            Paint itemPaint = getItemPaint(row, column);
328            g2.setStroke(itemStroke);
329            g2.setPaint(itemPaint);
330            g2.draw(line);
331    
332            CategoryItemLabelGenerator generator = getItemLabelGenerator(row,
333                    column);
334            if (generator != null && isItemLabelVisible(row, column)) {
335                drawItemLabel(g2, orientation, dataset, row, column, x, y,
336                        (value < 0.0));
337            }
338    
339            // submit the current data point as a crosshair candidate
340            int datasetIndex = plot.indexOf(dataset);
341            updateCrosshairValues(state.getCrosshairState(),
342                    dataset.getRowKey(row), dataset.getColumnKey(column), value,
343                    datasetIndex, barW0, barL, orientation);
344    
345            // collect entity and tool tip information...
346            EntityCollection entities = state.getEntityCollection();
347            if (entities != null) {
348                addItemEntity(entities, dataset, row, column, line.getBounds());
349            }
350    
351        }
352    
353        /**
354         * Calculates the available space for each series.
355         *
356         * @param space  the space along the entire axis (in Java2D units).
357         * @param axis  the category axis.
358         * @param categories  the number of categories.
359         * @param series  the number of series.
360         *
361         * @return The width of one series.
362         */
363        protected double calculateSeriesWidth(double space, CategoryAxis axis,
364                                              int categories, int series) {
365            double factor = 1.0 - getItemMargin() - axis.getLowerMargin()
366                            - axis.getUpperMargin();
367            if (categories > 1) {
368                factor = factor - axis.getCategoryMargin();
369            }
370            return (space * factor) / (categories * series);
371        }
372    
373        /**
374         * Returns the Java2D coordinate for the middle of the specified data item.
375         *
376         * @param rowKey  the row key.
377         * @param columnKey  the column key.
378         * @param dataset  the dataset.
379         * @param axis  the axis.
380         * @param area  the drawing area.
381         * @param edge  the edge along which the axis lies.
382         *
383         * @return The Java2D coordinate.
384         *
385         * @since 1.0.11
386         */
387        public double getItemMiddle(Comparable rowKey, Comparable columnKey,
388                CategoryDataset dataset, CategoryAxis axis, Rectangle2D area,
389                RectangleEdge edge) {
390            return axis.getCategorySeriesMiddle(columnKey, rowKey, dataset,
391                    this.itemMargin, area, edge);
392        }
393    
394        /**
395         * Tests an object for equality with this instance.
396         *
397         * @param obj  the object (<code>null</code> permitted).
398         *
399         * @return A boolean.
400         */
401        public boolean equals(Object obj) {
402            if (obj == this) {
403                return true;
404            }
405            if (!(obj instanceof LevelRenderer)) {
406                return false;
407            }
408            LevelRenderer that = (LevelRenderer) obj;
409            if (this.itemMargin != that.itemMargin) {
410                return false;
411            }
412            if (this.maxItemWidth != that.maxItemWidth) {
413                return false;
414            }
415            return super.equals(obj);
416        }
417    
418        /**
419         * Returns the maximum width, as a percentage of the available drawing
420         * space.
421         *
422         * @return The maximum width.
423         *
424         * @deprecated Use {@link #getMaximumItemWidth()} instead.
425         */
426        public double getMaxItemWidth() {
427            return this.maxItemWidth;
428        }
429    
430        /**
431         * Sets the maximum item width, which is specified as a percentage of the
432         * available space for all items, and sends a {@link RendererChangeEvent}
433         * to all registered listeners.
434         *
435         * @param percent  the percent.
436         *
437         * @deprecated Use {@link #setMaximumItemWidth(double)} instead.
438         */
439        public void setMaxItemWidth(double percent) {
440            this.maxItemWidth = percent;
441            fireChangeEvent();
442        }
443    
444    }