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