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