file_name
stringlengths
6
86
file_path
stringlengths
45
249
content
stringlengths
47
6.26M
file_size
int64
47
6.26M
language
stringclasses
1 value
extension
stringclasses
1 value
repo_name
stringclasses
767 values
repo_stars
int64
8
14.4k
repo_forks
int64
0
1.17k
repo_open_issues
int64
0
788
repo_created_at
stringclasses
767 values
repo_pushed_at
stringclasses
767 values
XYBarPainter.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/renderer/xy/XYBarPainter.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ----------------- * XYBarPainter.java * ----------------- * (C) Copyright 2008-2012, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes: * -------- * 19-Jun-2008 : Version 1 (DG); * 17-Jun-2012 : Removed JCommon dependencies (DG); * */ package org.jfree.chart.renderer.xy; import java.awt.Graphics2D; import java.awt.geom.RectangularShape; import org.jfree.chart.ui.RectangleEdge; /** * The interface for plugin painter for the {@link XYBarRenderer} class. When * developing a class that implements this interface, bear in mind the * following: * <ul> * <li>the <code>equals(Object)</code> method should be overridden;</li> * <li>instances of the class should be immutable OR implement the * <code>PublicCloneable</code> interface, so that a renderer using the * painter can be cloned reliably; * <li>the class should be <code>Serializable</code>, otherwise chart * serialization will not be supported.</li> * </ul> * * @since 1.0.11 */ public interface XYBarPainter { /** * Paints a single bar on behalf of a renderer. * * @param g2 the graphics target. * @param renderer the renderer. * @param row the row index for the item. * @param column the column index for the item. * @param bar the bounds for the bar. * @param base the base of the bar. */ public void paintBar(Graphics2D g2, XYBarRenderer renderer, int row, int column, RectangularShape bar, RectangleEdge base); /** * Paints the shadow for a single bar on behalf of a renderer. * * @param g2 the graphics target. * @param renderer the renderer. * @param row the row index for the item. * @param column the column index for the item. * @param bar the bounds for the bar. * @param base the base of the bar. * @param pegShadow peg the shadow to the base of the bar? */ public void paintBarShadow(Graphics2D g2, XYBarRenderer renderer, int row, int column, RectangularShape bar, RectangleEdge base, boolean pegShadow); }
3,392
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
ClusteredXYBarRenderer.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/renderer/xy/ClusteredXYBarRenderer.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * --------------------------- * ClusteredXYBarRenderer.java * --------------------------- * (C) Copyright 2003-2012, by Paolo Cova and Contributors. * * Original Author: Paolo Cova; * Contributor(s): David Gilbert (for Object Refinery Limited); * Christian W. Zuckschwerdt; * Matthias Rose; * * Changes * ------- * 24-Jan-2003 : Version 1, contributed by Paolo Cova (DG); * 25-Mar-2003 : Implemented Serializable (DG); * 01-May-2003 : Modified drawItem() method signature (DG); * 30-Jul-2003 : Modified entity constructor (CZ); * 20-Aug-2003 : Implemented Cloneable and PublicCloneable (DG); * 16-Sep-2003 : Changed ChartRenderingInfo --> PlotRenderingInfo (DG); * 07-Oct-2003 : Added renderer state (DG); * 03-Nov-2003 : In draw method added state parameter and y==null value * handling (MR); * 25-Feb-2004 : Replaced CrosshairInfo with CrosshairState (DG); * 15-Jul-2004 : Switched getX() with getXValue() and getY() with * getYValue() (DG); * 01-Oct-2004 : Fixed bug where 'drawBarOutline' flag is ignored (DG); * 16-May-2005 : Fixed to used outline stroke for bar outlines. Removed some * redundant code with the result that the renderer now respects * the 'base' setting from the super-class. Added an equals() * method (DG); * 19-May-2005 : Added minimal item label implementation - needs improving (DG); * ------------- JFREECHART 1.0.x --------------------------------------------- * 11-Dec-2006 : Added support for GradientPaint (DG); * 12-Jun-2007 : Added override to findDomainBounds() to handle cluster offset, * fixed rendering to handle inverted axes, and simplified * entity generation code (DG); * 24-Jun-2008 : Added new barPainter mechanism (DG); * 17-Jun-2012 : Removed JCommon dependencies (DG); * */ package org.jfree.chart.renderer.xy; import java.awt.Graphics2D; import java.awt.geom.Rectangle2D; import java.io.Serializable; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.ui.RectangleEdge; import org.jfree.chart.util.PublicCloneable; import org.jfree.chart.entity.EntityCollection; import org.jfree.chart.labels.XYItemLabelGenerator; import org.jfree.chart.plot.CrosshairState; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.PlotRenderingInfo; import org.jfree.chart.plot.XYPlot; import org.jfree.data.Range; import org.jfree.data.xy.IntervalXYDataset; import org.jfree.data.xy.XYDataset; /** * An extension of {@link XYBarRenderer} that displays bars for different * series values at the same x next to each other. The assumption here is * that for each x (time or else) there is a y value for each series. If * this is not the case, there will be spaces between bars for a given x. * The example shown here is generated by the * <code>ClusteredXYBarRendererDemo1.java</code> program included in the * JFreeChart demo collection: * <br><br> * <img src="../../../../../images/ClusteredXYBarRendererSample.png" * alt="ClusteredXYBarRendererSample.png" /> * <P> * This renderer does not include code to calculate the crosshair point for the * plot. */ public class ClusteredXYBarRenderer extends XYBarRenderer implements Cloneable, PublicCloneable, Serializable { /** For serialization. */ private static final long serialVersionUID = 5864462149177133147L; /** Determines whether bar center should be interval start. */ private boolean centerBarAtStartValue; /** * Default constructor. Bar margin is set to 0.0. */ public ClusteredXYBarRenderer() { this(0.0, false); } /** * Constructs a new XY clustered bar renderer. * * @param margin the percentage amount to trim from the width of each bar. * @param centerBarAtStartValue if true, bars will be centered on the * start of the time period. */ public ClusteredXYBarRenderer(double margin, boolean centerBarAtStartValue) { super(margin); this.centerBarAtStartValue = centerBarAtStartValue; } /** * Returns the number of passes through the dataset that this renderer * requires. In this case, two passes are required, the first for drawing * the shadows (if visible), and the second for drawing the bars. * * @return <code>2</code>. */ @Override public int getPassCount() { return 2; } /** * Returns the x-value bounds for the specified dataset. * * @param dataset the dataset (<code>null</code> permitted). * * @return The bounds (possibly <code>null</code>). */ @Override public Range findDomainBounds(XYDataset dataset) { if (dataset == null) { return null; } // need to handle cluster centering as a special case if (this.centerBarAtStartValue) { return findDomainBoundsWithOffset((IntervalXYDataset) dataset); } else { return super.findDomainBounds(dataset); } } /** * Iterates over the items in an {@link IntervalXYDataset} to find * the range of x-values including the interval OFFSET so that it centers * the interval around the start value. * * @param dataset the dataset (<code>null</code> not permitted). * * @return The range (possibly <code>null</code>). */ protected Range findDomainBoundsWithOffset(IntervalXYDataset dataset) { if (dataset == null) { throw new IllegalArgumentException("Null 'dataset' argument."); } double minimum = Double.POSITIVE_INFINITY; double maximum = Double.NEGATIVE_INFINITY; int seriesCount = dataset.getSeriesCount(); double lvalue; double uvalue; for (int series = 0; series < seriesCount; series++) { int itemCount = dataset.getItemCount(series); for (int item = 0; item < itemCount; item++) { lvalue = dataset.getStartXValue(series, item); uvalue = dataset.getEndXValue(series, item); double offset = (uvalue - lvalue) / 2.0; lvalue = lvalue - offset; uvalue = uvalue - offset; minimum = Math.min(minimum, lvalue); maximum = Math.max(maximum, uvalue); } } if (minimum > maximum) { return null; } else { return new Range(minimum, maximum); } } /** * Draws the visual representation of a single data item. This method * is mostly copied from the superclass, the change is that in the * calculated space for a singe bar we draw bars for each series next to * each other. The width of each bar is the available width divided by * the number of series. Bars for each series are drawn in order left to * right. * * @param g2 the graphics device. * @param state the renderer state. * @param dataArea the area within which the plot is being drawn. * @param info collects information about the drawing. * @param plot the plot (can be used to obtain standard color * information etc). * @param domainAxis the domain axis. * @param rangeAxis the range axis. * @param dataset the dataset. * @param series the series index. * @param item the item index. * @param crosshairState crosshair information for the plot * (<code>null</code> permitted). * @param pass the pass index. */ @Override public void drawItem(Graphics2D g2, XYItemRendererState state, Rectangle2D dataArea, PlotRenderingInfo info, XYPlot plot, ValueAxis domainAxis, ValueAxis rangeAxis, XYDataset dataset, int series, int item, CrosshairState crosshairState, int pass) { IntervalXYDataset intervalDataset = (IntervalXYDataset) dataset; double y0; double y1; if (getUseYInterval()) { y0 = intervalDataset.getStartYValue(series, item); y1 = intervalDataset.getEndYValue(series, item); } else { y0 = getBase(); y1 = intervalDataset.getYValue(series, item); } if (Double.isNaN(y0) || Double.isNaN(y1)) { return; } double yy0 = rangeAxis.valueToJava2D(y0, dataArea, plot.getRangeAxisEdge()); double yy1 = rangeAxis.valueToJava2D(y1, dataArea, plot.getRangeAxisEdge()); RectangleEdge xAxisLocation = plot.getDomainAxisEdge(); double x0 = intervalDataset.getStartXValue(series, item); double xx0 = domainAxis.valueToJava2D(x0, dataArea, xAxisLocation); double x1 = intervalDataset.getEndXValue(series, item); double xx1 = domainAxis.valueToJava2D(x1, dataArea, xAxisLocation); double intervalW = xx1 - xx0; // this may be negative double baseX = xx0; if (this.centerBarAtStartValue) { baseX = baseX - intervalW / 2.0; } double m = getMargin(); if (m > 0.0) { double cut = intervalW * getMargin(); intervalW = intervalW - cut; baseX = baseX + (cut / 2); } double intervalH = Math.abs(yy0 - yy1); // we don't need the sign PlotOrientation orientation = plot.getOrientation(); int numSeries = dataset.getSeriesCount(); double seriesBarWidth = intervalW / numSeries; // may be negative Rectangle2D bar = null; if (orientation == PlotOrientation.HORIZONTAL) { double barY0 = baseX + (seriesBarWidth * series); double barY1 = barY0 + seriesBarWidth; double rx = Math.min(yy0, yy1); double rw = intervalH; double ry = Math.min(barY0, barY1); double rh = Math.abs(barY1 - barY0); bar = new Rectangle2D.Double(rx, ry, rw, rh); } else if (orientation == PlotOrientation.VERTICAL) { double barX0 = baseX + (seriesBarWidth * series); double barX1 = barX0 + seriesBarWidth; double rx = Math.min(barX0, barX1); double rw = Math.abs(barX1 - barX0); double ry = Math.min(yy0, yy1); double rh = intervalH; bar = new Rectangle2D.Double(rx, ry, rw, rh); } boolean positive = (y1 > 0.0); boolean inverted = rangeAxis.isInverted(); RectangleEdge barBase; if (orientation == PlotOrientation.HORIZONTAL) { if (positive && inverted || !positive && !inverted) { barBase = RectangleEdge.RIGHT; } else { barBase = RectangleEdge.LEFT; } } else { if (positive && !inverted || !positive && inverted) { barBase = RectangleEdge.BOTTOM; } else { barBase = RectangleEdge.TOP; } } if (pass == 0 && getShadowsVisible()) { getBarPainter().paintBarShadow(g2, this, series, item, bar, barBase, !getUseYInterval()); } if (pass == 1) { getBarPainter().paintBar(g2, this, series, item, bar, barBase); if (isItemLabelVisible(series, item)) { XYItemLabelGenerator generator = getItemLabelGenerator(series, item); drawItemLabel(g2, dataset, series, item, plot, generator, bar, y1 < 0.0); } // add an entity for the item... if (info != null) { EntityCollection entities = info.getOwner().getEntityCollection(); if (entities != null) { addEntity(entities, bar, dataset, series, item, bar.getCenterX(), bar.getCenterY()); } } } } /** * Tests this renderer for equality with an arbitrary object, returning * <code>true</code> if <code>obj</code> is a * <code>ClusteredXYBarRenderer</code> with the same settings as this * renderer, and <code>false</code> otherwise. * * @param obj the object (<code>null</code> permitted). * * @return A boolean. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof ClusteredXYBarRenderer)) { return false; } ClusteredXYBarRenderer that = (ClusteredXYBarRenderer) obj; if (this.centerBarAtStartValue != that.centerBarAtStartValue) { return false; } return super.equals(obj); } /** * Returns a clone of the renderer. * * @return A clone. * * @throws CloneNotSupportedException if the renderer cannot be cloned. */ @Override public Object clone() throws CloneNotSupportedException { return super.clone(); } }
14,614
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
CyclicXYItemRenderer.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/renderer/xy/CyclicXYItemRenderer.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * --------------------------- * CyclicXYItemRenderer.java * --------------------------- * (C) Copyright 2003-2008, by Nicolas Brodu and Contributors. * * Original Author: Nicolas Brodu; * Contributor(s): David Gilbert (for Object Refinery Limited); * * Changes * ------- * 19-Nov-2003 : Initial import to JFreeChart from the JSynoptic project (NB); * 23-Dec-2003 : Added missing Javadocs (DG); * 25-Feb-2004 : Replaced CrosshairInfo with CrosshairState (DG); * 15-Jul-2004 : Switched getX() with getXValue() and getY() with * getYValue() (DG); * ------------- JFREECHART 1.0.0 --------------------------------------------- * 06-Jul-2006 : Modified to call only dataset methods that return double * primitives (DG); * */ package org.jfree.chart.renderer.xy; import java.awt.Graphics2D; import java.awt.geom.Rectangle2D; import java.io.Serializable; import org.jfree.chart.axis.CyclicNumberAxis; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.labels.XYToolTipGenerator; import org.jfree.chart.plot.CrosshairState; import org.jfree.chart.plot.PlotRenderingInfo; import org.jfree.chart.plot.XYPlot; import org.jfree.chart.urls.XYURLGenerator; import org.jfree.data.DomainOrder; import org.jfree.data.general.DatasetChangeListener; import org.jfree.data.general.DatasetGroup; import org.jfree.data.xy.XYDataset; /** * The Cyclic XY item renderer is specially designed to handle cyclic axis. * While the standard renderer would draw a line across the plot when a cycling * occurs, the cyclic renderer splits the line at each cycle end instead. This * is done by interpolating new points at cycle boundary. Thus, correct * appearance is restored. * * The Cyclic XY item renderer works exactly like a standard XY item renderer * with non-cyclic axis. */ public class CyclicXYItemRenderer extends StandardXYItemRenderer implements Serializable { /** For serialization. */ private static final long serialVersionUID = 4035912243303764892L; /** * Default constructor. */ public CyclicXYItemRenderer() { super(); } /** * Creates a new renderer. * * @param type the renderer type. */ public CyclicXYItemRenderer(int type) { super(type); } /** * Creates a new renderer. * * @param type the renderer type. * @param labelGenerator the tooltip generator. */ public CyclicXYItemRenderer(int type, XYToolTipGenerator labelGenerator) { super(type, labelGenerator); } /** * Creates a new renderer. * * @param type the renderer type. * @param labelGenerator the tooltip generator. * @param urlGenerator the url generator. */ public CyclicXYItemRenderer(int type, XYToolTipGenerator labelGenerator, XYURLGenerator urlGenerator) { super(type, labelGenerator, urlGenerator); } /** * Draws the visual representation of a single data item. * When using cyclic axis, do not draw a line from right to left when * cycling as would a standard XY item renderer, but instead draw a line * from the previous point to the cycle bound in the last cycle, and a line * from the cycle bound to current point in the current cycle. * * @param g2 the graphics device. * @param state the renderer state. * @param dataArea the data area. * @param info the plot rendering info. * @param plot the plot. * @param domainAxis the domain axis. * @param rangeAxis the range axis. * @param dataset the dataset. * @param series the series index. * @param item the item index. * @param crosshairState crosshair information for the plot * (<code>null</code> permitted). * @param pass the current pass index. */ @Override public void drawItem(Graphics2D g2, XYItemRendererState state, Rectangle2D dataArea, PlotRenderingInfo info, XYPlot plot, ValueAxis domainAxis, ValueAxis rangeAxis, XYDataset dataset, int series, int item, CrosshairState crosshairState, int pass) { if ((!getPlotLines()) || ((!(domainAxis instanceof CyclicNumberAxis)) && (!(rangeAxis instanceof CyclicNumberAxis))) || (item <= 0)) { super.drawItem(g2, state, dataArea, info, plot, domainAxis, rangeAxis, dataset, series, item, crosshairState, pass); return; } // get the previous data point... double xn = dataset.getXValue(series, item - 1); double yn = dataset.getYValue(series, item - 1); // If null, don't draw line => then delegate to parent if (Double.isNaN(yn)) { super.drawItem(g2, state, dataArea, info, plot, domainAxis, rangeAxis, dataset, series, item, crosshairState, pass); return; } double[] x = new double[2]; double[] y = new double[2]; x[0] = xn; y[0] = yn; // get the data point... xn = dataset.getXValue(series, item); yn = dataset.getYValue(series, item); // If null, don't draw line at all if (Double.isNaN(yn)) { return; } x[1] = xn; y[1] = yn; // Now split the segment as needed double xcycleBound = Double.NaN; double ycycleBound = Double.NaN; boolean xBoundMapping = false, yBoundMapping = false; CyclicNumberAxis cnax = null, cnay = null; if (domainAxis instanceof CyclicNumberAxis) { cnax = (CyclicNumberAxis) domainAxis; xcycleBound = cnax.getCycleBound(); xBoundMapping = cnax.isBoundMappedToLastCycle(); // If the segment must be splitted, insert a new point // Strict test forces to have real segments (not 2 equal points) // and avoids division by 0 if ((x[0] != x[1]) && ((xcycleBound >= x[0]) && (xcycleBound <= x[1]) || (xcycleBound >= x[1]) && (xcycleBound <= x[0]))) { double[] nx = new double[3]; double[] ny = new double[3]; nx[0] = x[0]; nx[2] = x[1]; ny[0] = y[0]; ny[2] = y[1]; nx[1] = xcycleBound; ny[1] = (y[1] - y[0]) * (xcycleBound - x[0]) / (x[1] - x[0]) + y[0]; x = nx; y = ny; } } if (rangeAxis instanceof CyclicNumberAxis) { cnay = (CyclicNumberAxis) rangeAxis; ycycleBound = cnay.getCycleBound(); yBoundMapping = cnay.isBoundMappedToLastCycle(); // The split may occur in either x splitted segments, if any, but // not in both if ((y[0] != y[1]) && ((ycycleBound >= y[0]) && (ycycleBound <= y[1]) || (ycycleBound >= y[1]) && (ycycleBound <= y[0]))) { double[] nx = new double[x.length + 1]; double[] ny = new double[y.length + 1]; nx[0] = x[0]; nx[2] = x[1]; ny[0] = y[0]; ny[2] = y[1]; ny[1] = ycycleBound; nx[1] = (x[1] - x[0]) * (ycycleBound - y[0]) / (y[1] - y[0]) + x[0]; if (x.length == 3) { nx[3] = x[2]; ny[3] = y[2]; } x = nx; y = ny; } else if ((x.length == 3) && (y[1] != y[2]) && ((ycycleBound >= y[1]) && (ycycleBound <= y[2]) || (ycycleBound >= y[2]) && (ycycleBound <= y[1]))) { double[] nx = new double[4]; double[] ny = new double[4]; nx[0] = x[0]; nx[1] = x[1]; nx[3] = x[2]; ny[0] = y[0]; ny[1] = y[1]; ny[3] = y[2]; ny[2] = ycycleBound; nx[2] = (x[2] - x[1]) * (ycycleBound - y[1]) / (y[2] - y[1]) + x[1]; x = nx; y = ny; } } // If the line is not wrapping, then parent is OK if (x.length == 2) { super.drawItem(g2, state, dataArea, info, plot, domainAxis, rangeAxis, dataset, series, item, crosshairState, pass); return; } OverwriteDataSet newset = new OverwriteDataSet(x, y, dataset); if (cnax != null) { if (xcycleBound == x[0]) { cnax.setBoundMappedToLastCycle(x[1] <= xcycleBound); } if (xcycleBound == x[1]) { cnax.setBoundMappedToLastCycle(x[0] <= xcycleBound); } } if (cnay != null) { if (ycycleBound == y[0]) { cnay.setBoundMappedToLastCycle(y[1] <= ycycleBound); } if (ycycleBound == y[1]) { cnay.setBoundMappedToLastCycle(y[0] <= ycycleBound); } } super.drawItem( g2, state, dataArea, info, plot, domainAxis, rangeAxis, newset, series, 1, crosshairState, pass ); if (cnax != null) { if (xcycleBound == x[1]) { cnax.setBoundMappedToLastCycle(x[2] <= xcycleBound); } if (xcycleBound == x[2]) { cnax.setBoundMappedToLastCycle(x[1] <= xcycleBound); } } if (cnay != null) { if (ycycleBound == y[1]) { cnay.setBoundMappedToLastCycle(y[2] <= ycycleBound); } if (ycycleBound == y[2]) { cnay.setBoundMappedToLastCycle(y[1] <= ycycleBound); } } super.drawItem(g2, state, dataArea, info, plot, domainAxis, rangeAxis, newset, series, 2, crosshairState, pass); if (x.length == 4) { if (cnax != null) { if (xcycleBound == x[2]) { cnax.setBoundMappedToLastCycle(x[3] <= xcycleBound); } if (xcycleBound == x[3]) { cnax.setBoundMappedToLastCycle(x[2] <= xcycleBound); } } if (cnay != null) { if (ycycleBound == y[2]) { cnay.setBoundMappedToLastCycle(y[3] <= ycycleBound); } if (ycycleBound == y[3]) { cnay.setBoundMappedToLastCycle(y[2] <= ycycleBound); } } super.drawItem(g2, state, dataArea, info, plot, domainAxis, rangeAxis, newset, series, 3, crosshairState, pass); } if (cnax != null) { cnax.setBoundMappedToLastCycle(xBoundMapping); } if (cnay != null) { cnay.setBoundMappedToLastCycle(yBoundMapping); } } /** * A dataset to hold the interpolated points when drawing new lines. */ protected static class OverwriteDataSet implements XYDataset { /** The delegate dataset. */ protected XYDataset delegateSet; /** Storage for the x and y values. */ Double[] x, y; /** * Creates a new dataset. * * @param x the x values. * @param y the y values. * @param delegateSet the dataset. */ public OverwriteDataSet(double [] x, double[] y, XYDataset delegateSet) { this.delegateSet = delegateSet; this.x = new Double[x.length]; this.y = new Double[y.length]; for (int i = 0; i < x.length; ++i) { this.x[i] = x[i]; this.y[i] = y[i]; } } /** * Returns the order of the domain (X) values. * * @return The domain order. */ @Override public DomainOrder getDomainOrder() { return DomainOrder.NONE; } /** * Returns the number of items for the given series. * * @param series the series index (zero-based). * * @return The item count. */ @Override public int getItemCount(int series) { return this.x.length; } /** * Returns the x-value. * * @param series the series index (zero-based). * @param item the item index (zero-based). * * @return The x-value. */ @Override public Number getX(int series, int item) { return this.x[item]; } /** * Returns the x-value (as a double primitive) for an item within a * series. * * @param series the series (zero-based index). * @param item the item (zero-based index). * * @return The x-value. */ @Override public double getXValue(int series, int item) { double result = Double.NaN; Number x = getX(series, item); if (x != null) { result = x.doubleValue(); } return result; } /** * Returns the y-value. * * @param series the series index (zero-based). * @param item the item index (zero-based). * * @return The y-value. */ @Override public Number getY(int series, int item) { return this.y[item]; } /** * Returns the y-value (as a double primitive) for an item within a * series. * * @param series the series (zero-based index). * @param item the item (zero-based index). * * @return The y-value. */ @Override public double getYValue(int series, int item) { double result = Double.NaN; Number y = getY(series, item); if (y != null) { result = y.doubleValue(); } return result; } /** * Returns the number of series in the dataset. * * @return The series count. */ @Override public int getSeriesCount() { return this.delegateSet.getSeriesCount(); } /** * Returns the name of the given series. * * @param series the series index (zero-based). * * @return The series name. */ @Override public Comparable getSeriesKey(int series) { return this.delegateSet.getSeriesKey(series); } /** * Returns the index of the named series, or -1. * * @param seriesName the series name. * * @return The index. */ @Override public int indexOf(Comparable seriesName) { return this.delegateSet.indexOf(seriesName); } /** * Does nothing. * * @param listener ignored. */ @Override public void addChangeListener(DatasetChangeListener listener) { // unused in parent } /** * Does nothing. * * @param listener ignored. */ @Override public void removeChangeListener(DatasetChangeListener listener) { // unused in parent } /** * Returns the dataset group. * * @return The dataset group. */ @Override public DatasetGroup getGroup() { // unused but must return something, so while we are at it... return this.delegateSet.getGroup(); } /** * Does nothing. * * @param group ignored. */ @Override public void setGroup(DatasetGroup group) { // unused in parent } } }
17,526
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
XYStepAreaRenderer.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/renderer/xy/XYStepAreaRenderer.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2013, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ----------------------- * XYStepAreaRenderer.java * ----------------------- * (C) Copyright 2003-2013, by Matthias Rose and Contributors. * * Original Author: Matthias Rose (based on XYAreaRenderer.java); * Contributor(s): David Gilbert (for Object Refinery Limited); * Lukasz Rzeszotarski; * * Changes: * -------- * 07-Oct-2003 : Version 1, contributed by Matthias Rose (DG); * 10-Feb-2004 : Added some getter and setter methods (DG); * 25-Feb-2004 : Replaced CrosshairInfo with CrosshairState. Renamed * XYToolTipGenerator --> XYItemLabelGenerator (DG); * 15-Jul-2004 : Switched getX() with getXValue() and getY() with * getYValue() (DG); * 11-Nov-2004 : Now uses ShapeUtilities to translate shapes (DG); * 06-Jul-2005 : Renamed get/setPlotShapes() --> get/setShapesVisible() (DG); * ------------- JFREECHART 1.0.x --------------------------------------------- * 06-Jul-2006 : Modified to call dataset methods that return double * primitives only (DG); * 06-Feb-2007 : Fixed bug 1086307, crosshairs with multiple axes (DG); * 14-Feb-2007 : Added equals() method override (DG); * 04-May-2007 : Set processVisibleItemsOnly flag to false (DG); * 14-May-2008 : Call addEntity() from within drawItem() (DG); * 19-May-2009 : Fixed FindBugs warnings, patch by Michal Wozniak (DG); * 17-Jun-2012 : Removed JCommon dependencies (DG); * 05-Dec-2013 : Added stepPoint attribute (LR); * */ package org.jfree.chart.renderer.xy; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.Polygon; import java.awt.Shape; import java.awt.Stroke; import java.awt.geom.Rectangle2D; import java.io.Serializable; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.util.PublicCloneable; import org.jfree.chart.util.ShapeUtilities; import org.jfree.chart.entity.EntityCollection; import org.jfree.chart.event.RendererChangeEvent; import org.jfree.chart.labels.XYToolTipGenerator; import org.jfree.chart.plot.CrosshairState; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.PlotRenderingInfo; import org.jfree.chart.plot.XYPlot; import org.jfree.chart.urls.XYURLGenerator; import org.jfree.data.xy.XYDataset; /** * A step chart renderer that fills the area between the step and the x-axis. * The example shown here is generated by the * <code>XYStepAreaRendererDemo1.java</code> program included in the JFreeChart * demo collection: * <br><br> * <img src="../../../../../images/XYStepAreaRendererSample.png" * alt="XYStepAreaRendererSample.png" /> */ public class XYStepAreaRenderer extends AbstractXYItemRenderer implements XYItemRenderer, Cloneable, PublicCloneable, Serializable { /** For serialization. */ private static final long serialVersionUID = -7311560779702649635L; /** Useful constant for specifying the type of rendering (shapes only). */ public static final int SHAPES = 1; /** Useful constant for specifying the type of rendering (area only). */ public static final int AREA = 2; /** * Useful constant for specifying the type of rendering (area and shapes). */ public static final int AREA_AND_SHAPES = 3; /** A flag indicating whether or not shapes are drawn at each XY point. */ private boolean shapesVisible; /** A flag that controls whether or not shapes are filled for ALL series. */ private boolean shapesFilled; /** A flag indicating whether or not Area are drawn at each XY point. */ private boolean plotArea; /** A flag that controls whether or not the outline is shown. */ private boolean showOutline; /** Area of the complete series */ protected transient Polygon pArea = null; /** * The value on the range axis which defines the 'lower' border of the * area. */ private double rangeBase; /** * The factor (from 0.0 to 1.0) that determines the position of the * step. * * @since 1.0.18. */ private double stepPoint; /** * Constructs a new renderer. */ public XYStepAreaRenderer() { this(AREA); } /** * Constructs a new renderer. * * @param type the type of the renderer. */ public XYStepAreaRenderer(int type) { this(type, null, null); } /** * Constructs a new renderer. * <p> * To specify the type of renderer, use one of the constants: * AREA, SHAPES or AREA_AND_SHAPES. * * @param type the type of renderer. * @param toolTipGenerator the tool tip generator to use * (<code>null</code> permitted). * @param urlGenerator the URL generator (<code>null</code> permitted). */ public XYStepAreaRenderer(int type, XYToolTipGenerator toolTipGenerator, XYURLGenerator urlGenerator) { super(); setDefaultToolTipGenerator(toolTipGenerator); setURLGenerator(urlGenerator); if (type == AREA) { this.plotArea = true; } else if (type == SHAPES) { this.shapesVisible = true; } else if (type == AREA_AND_SHAPES) { this.plotArea = true; this.shapesVisible = true; } this.showOutline = false; this.stepPoint = 1.0; } /** * Returns a flag that controls whether or not outlines of the areas are * drawn. * * @return The flag. * * @see #setOutline(boolean) */ public boolean isOutline() { return this.showOutline; } /** * Sets a flag that controls whether or not outlines of the areas are * drawn, and sends a {@link RendererChangeEvent} to all registered * listeners. * * @param show the flag. * * @see #isOutline() */ public void setOutline(boolean show) { this.showOutline = show; fireChangeEvent(); } /** * Returns true if shapes are being plotted by the renderer. * * @return <code>true</code> if shapes are being plotted by the renderer. * * @see #setShapesVisible(boolean) */ public boolean getShapesVisible() { return this.shapesVisible; } /** * Sets the flag that controls whether or not shapes are displayed for each * data item, and sends a {@link RendererChangeEvent} to all registered * listeners. * * @param flag the flag. * * @see #getShapesVisible() */ public void setShapesVisible(boolean flag) { this.shapesVisible = flag; fireChangeEvent(); } /** * Returns the flag that controls whether or not the shapes are filled. * * @return A boolean. * * @see #setShapesFilled(boolean) */ public boolean isShapesFilled() { return this.shapesFilled; } /** * Sets the 'shapes filled' for ALL series and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param filled the flag. * * @see #isShapesFilled() */ public void setShapesFilled(boolean filled) { this.shapesFilled = filled; fireChangeEvent(); } /** * Returns true if Area is being plotted by the renderer. * * @return <code>true</code> if Area is being plotted by the renderer. * * @see #setPlotArea(boolean) */ public boolean getPlotArea() { return this.plotArea; } /** * Sets a flag that controls whether or not areas are drawn for each data * item and sends a {@link RendererChangeEvent} to all registered * listeners. * * @param flag the flag. * * @see #getPlotArea() */ public void setPlotArea(boolean flag) { this.plotArea = flag; fireChangeEvent(); } /** * Returns the value on the range axis which defines the 'lower' border of * the area. * * @return <code>double</code> the value on the range axis which defines * the 'lower' border of the area. * * @see #setRangeBase(double) */ public double getRangeBase() { return this.rangeBase; } /** * Sets the value on the range axis which defines the default border of the * area, and sends a {@link RendererChangeEvent} to all registered * listeners. E.g. setRangeBase(Double.NEGATIVE_INFINITY) lets areas always * reach the lower border of the plotArea. * * @param val the value on the range axis which defines the default border * of the area. * * @see #getRangeBase() */ public void setRangeBase(double val) { this.rangeBase = val; fireChangeEvent(); } /** * Returns the fraction of the domain position between two points on which * the step is drawn. The default is 1.0d, which means the step is drawn * at the domain position of the second`point. If the stepPoint is 0.5d the * step is drawn at half between the two points. * * @return The fraction of the domain position between two points where the * step is drawn. * * @see #setStepPoint(double) * * @since 1.0.18 */ public double getStepPoint() { return stepPoint; } /** * Sets the step point and sends a {@link RendererChangeEvent} to all * registered listeners. * * @param stepPoint the step point (in the range 0.0 to 1.0) * * @see #getStepPoint() * * @since 1.0.18 */ public void setStepPoint(double stepPoint) { if (stepPoint < 0.0d || stepPoint > 1.0d) { throw new IllegalArgumentException( "Requires stepPoint in [0.0;1.0]"); } this.stepPoint = stepPoint; fireChangeEvent(); } /** * Initialises the renderer. Here we calculate the Java2D y-coordinate for * zero, since all the bars have their bases fixed at zero. * * @param g2 the graphics device. * @param dataArea the area inside the axes. * @param plot the plot. * @param data the data. * @param info an optional info collection object to return data back to * the caller. * * @return The number of passes required by the renderer. */ @Override public XYItemRendererState initialise(Graphics2D g2, Rectangle2D dataArea, XYPlot plot, XYDataset data, PlotRenderingInfo info) { XYItemRendererState state = super.initialise(g2, dataArea, plot, data, info); // disable visible items optimisation - it doesn't work for this // renderer... state.setProcessVisibleItemsOnly(false); return state; } /** * Draws the visual representation of a single data item. * * @param g2 the graphics device. * @param state the renderer state. * @param dataArea the area within which the data is being drawn. * @param info collects information about the drawing. * @param plot the plot (can be used to obtain standard color information * etc). * @param domainAxis the domain axis. * @param rangeAxis the range axis. * @param dataset the dataset. * @param series the series index (zero-based). * @param item the item index (zero-based). * @param crosshairState crosshair information for the plot * (<code>null</code> permitted). * @param pass the pass index. */ @Override public void drawItem(Graphics2D g2, XYItemRendererState state, Rectangle2D dataArea, PlotRenderingInfo info, XYPlot plot, ValueAxis domainAxis, ValueAxis rangeAxis, XYDataset dataset, int series, int item, CrosshairState crosshairState, int pass) { PlotOrientation orientation = plot.getOrientation(); // Get the item count for the series, so that we can know which is the // end of the series. int itemCount = dataset.getItemCount(series); Paint paint = getItemPaint(series, item); Stroke seriesStroke = getItemStroke(series, item); g2.setPaint(paint); g2.setStroke(seriesStroke); // get the data point... double x1 = dataset.getXValue(series, item); double y1 = dataset.getYValue(series, item); double x = x1; double y = Double.isNaN(y1) ? getRangeBase() : y1; double transX1 = domainAxis.valueToJava2D(x, dataArea, plot.getDomainAxisEdge()); double transY1 = rangeAxis.valueToJava2D(y, dataArea, plot.getRangeAxisEdge()); // avoid possible sun.dc.pr.PRException: endPath: bad path transY1 = restrictValueToDataArea(transY1, plot, dataArea); if (this.pArea == null && !Double.isNaN(y1)) { // Create a new Area for the series this.pArea = new Polygon(); // start from Y = rangeBase double transY2 = rangeAxis.valueToJava2D(getRangeBase(), dataArea, plot.getRangeAxisEdge()); // avoid possible sun.dc.pr.PRException: endPath: bad path transY2 = restrictValueToDataArea(transY2, plot, dataArea); // The first point is (x, this.baseYValue) if (orientation == PlotOrientation.VERTICAL) { this.pArea.addPoint((int) transX1, (int) transY2); } else if (orientation == PlotOrientation.HORIZONTAL) { this.pArea.addPoint((int) transY2, (int) transX1); } } double transX0; double transY0; double x0; double y0; if (item > 0) { // get the previous data point... x0 = dataset.getXValue(series, item - 1); y0 = Double.isNaN(y1) ? y1 : dataset.getYValue(series, item - 1); x = x0; y = Double.isNaN(y0) ? getRangeBase() : y0; transX0 = domainAxis.valueToJava2D(x, dataArea, plot.getDomainAxisEdge()); transY0 = rangeAxis.valueToJava2D(y, dataArea, plot.getRangeAxisEdge()); // avoid possible sun.dc.pr.PRException: endPath: bad path transY0 = restrictValueToDataArea(transY0, plot, dataArea); if (Double.isNaN(y1)) { // NULL value -> insert point on base line // instead of 'step point' transX1 = transX0; transY0 = transY1; } if (transY0 != transY1) { // not just a horizontal bar but need to perform a 'step'. double transXs = transX0 + (getStepPoint() * (transX1 - transX0)); if (orientation == PlotOrientation.VERTICAL) { this.pArea.addPoint((int) transXs, (int) transY0); this.pArea.addPoint((int) transXs, (int) transY1); } else if (orientation == PlotOrientation.HORIZONTAL) { this.pArea.addPoint((int) transY0, (int) transXs); this.pArea.addPoint((int) transY1, (int) transXs); } } } Shape shape = null; if (!Double.isNaN(y1)) { // Add each point to Area (x, y) if (orientation == PlotOrientation.VERTICAL) { this.pArea.addPoint((int) transX1, (int) transY1); } else if (orientation == PlotOrientation.HORIZONTAL) { this.pArea.addPoint((int) transY1, (int) transX1); } if (getShapesVisible()) { shape = getItemShape(series, item); if (orientation == PlotOrientation.VERTICAL) { shape = ShapeUtilities.createTranslatedShape(shape, transX1, transY1); } else if (orientation == PlotOrientation.HORIZONTAL) { shape = ShapeUtilities.createTranslatedShape(shape, transY1, transX1); } if (isShapesFilled()) { g2.fill(shape); } else { g2.draw(shape); } } else { if (orientation == PlotOrientation.VERTICAL) { shape = new Rectangle2D.Double(transX1 - 2, transY1 - 2, 4.0, 4.0); } else if (orientation == PlotOrientation.HORIZONTAL) { shape = new Rectangle2D.Double(transY1 - 2, transX1 - 2, 4.0, 4.0); } } } // Check if the item is the last item for the series or if it // is a NULL value and number of items > 0. We can't draw an area for // a single point. if (getPlotArea() && item > 0 && this.pArea != null && (item == (itemCount - 1) || Double.isNaN(y1))) { double transY2 = rangeAxis.valueToJava2D(getRangeBase(), dataArea, plot.getRangeAxisEdge()); // avoid possible sun.dc.pr.PRException: endPath: bad path transY2 = restrictValueToDataArea(transY2, plot, dataArea); if (orientation == PlotOrientation.VERTICAL) { // Add the last point (x,0) this.pArea.addPoint((int) transX1, (int) transY2); } else if (orientation == PlotOrientation.HORIZONTAL) { // Add the last point (x,0) this.pArea.addPoint((int) transY2, (int) transX1); } // fill the polygon g2.fill(this.pArea); // draw an outline around the Area. if (isOutline()) { g2.setStroke(plot.getOutlineStroke()); g2.setPaint(plot.getOutlinePaint()); g2.draw(this.pArea); } // start new area when needed (see above) this.pArea = null; } // do we need to update the crosshair values? if (!Double.isNaN(y1)) { int domainAxisIndex = plot.getDomainAxisIndex(domainAxis); int rangeAxisIndex = plot.getRangeAxisIndex(rangeAxis); updateCrosshairValues(crosshairState, x1, y1, domainAxisIndex, rangeAxisIndex, transX1, transY1, orientation); } // collect entity and tool tip information... EntityCollection entities = state.getEntityCollection(); if (entities != null) { addEntity(entities, shape, dataset, series, item, transX1, transY1); } } /** * Tests this renderer for equality with an arbitrary object. * * @param obj the object (<code>null</code> permitted). * * @return A boolean. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof XYStepAreaRenderer)) { return false; } XYStepAreaRenderer that = (XYStepAreaRenderer) obj; if (this.showOutline != that.showOutline) { return false; } if (this.shapesVisible != that.shapesVisible) { return false; } if (this.shapesFilled != that.shapesFilled) { return false; } if (this.plotArea != that.plotArea) { return false; } if (this.rangeBase != that.rangeBase) { return false; } if (this.stepPoint != that.stepPoint) { return false; } return super.equals(obj); } /** * Returns a clone of the renderer. * * @return A clone. * * @throws CloneNotSupportedException if the renderer cannot be cloned. */ @Override public Object clone() throws CloneNotSupportedException { return super.clone(); } /** * Helper method which returns a value if it lies * inside the visible dataArea and otherwise the corresponding * coordinate on the border of the dataArea. The PlotOrientation * is taken into account. * Useful to avoid possible sun.dc.pr.PRException: endPath: bad path * which occurs when trying to draw lines/shapes which in large part * lie outside of the visible dataArea. * * @param value the value which shall be * @param dataArea the area within which the data is being drawn. * @param plot the plot (can be used to obtain standard color * information etc). * @return <code>double</code> value inside the data area. */ protected static double restrictValueToDataArea(double value, XYPlot plot, Rectangle2D dataArea) { double min = 0; double max = 0; if (plot.getOrientation() == PlotOrientation.VERTICAL) { min = dataArea.getMinY(); max = dataArea.getMaxY(); } else if (plot.getOrientation() == PlotOrientation.HORIZONTAL) { min = dataArea.getMinX(); max = dataArea.getMaxX(); } if (value < min) { value = min; } else if (value > max) { value = max; } return value; } }
22,818
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
XYAreaRenderer.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/renderer/xy/XYAreaRenderer.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ------------------- * XYAreaRenderer.java * ------------------- * (C) Copyright 2002-2012, by Hari and Contributors. * * Original Author: Hari ([email protected]); * Contributor(s): David Gilbert (for Object Refinery Limited); * Richard Atkinson; * Christian W. Zuckschwerdt; * Martin Krauskopf; * * Changes: * -------- * 03-Apr-2002 : Version 1, contributed by Hari. This class is based on the * StandardXYItemRenderer class (DG); * 09-Apr-2002 : Removed the translated zero from the drawItem method - * overridden the initialise() method to calculate it (DG); * 30-May-2002 : Added tool tip generator to constructor to match super * class (DG); * 25-Jun-2002 : Removed unnecessary local variable (DG); * 05-Aug-2002 : Small modification to drawItem method to support URLs for HTML * image maps (RA); * 01-Oct-2002 : Fixed errors reported by Checkstyle (DG); * 07-Nov-2002 : Renamed AreaXYItemRenderer --> XYAreaRenderer (DG); * 25-Mar-2003 : Implemented Serializable (DG); * 01-May-2003 : Modified drawItem() method signature (DG); * 27-Jul-2003 : Made line and polygon properties protected rather than * private (RA); * 30-Jul-2003 : Modified entity constructor (CZ); * 20-Aug-2003 : Implemented Cloneable and PublicCloneable (DG); * 16-Sep-2003 : Changed ChartRenderingInfo --> PlotRenderingInfo (DG); * 07-Oct-2003 : Added renderer state (DG); * 08-Dec-2003 : Modified hotspot for chart entity (DG); * 10-Feb-2004 : Changed the drawItem() method to make cut-and-paste overriding * easier. Also moved state class into this class (DG); * 25-Feb-2004 : Replaced CrosshairInfo with CrosshairState. Renamed * XYToolTipGenerator --> XYItemLabelGenerator (DG); * 15-Jul-2004 : Switched getX() with getXValue() and getY() with * getYValue() (DG); * 11-Nov-2004 : Now uses ShapeUtilities to translate shapes (DG); * 19-Jan-2005 : Now accesses primitives only from dataset (DG); * 21-Mar-2005 : Override getLegendItem() and equals() methods (DG); * 20-Apr-2005 : Use generators for legend tooltips and URLs (DG); * ------------- JFREECHART 1.0.x --------------------------------------------- * 06-Feb-2007 : Fixed bug 1086307, crosshairs with multiple axes (DG); * 14-Feb-2007 : Fixed bug in clone() (DG); * 20-Apr-2007 : Updated getLegendItem() for renderer change (DG); * 04-May-2007 : Set processVisibleItemsOnly flag to false (DG); * 17-May-2007 : Set datasetIndex and seriesIndex in getLegendItem() (DG); * 18-May-2007 : Set dataset and seriesKey for LegendItem (DG); * 17-Jun-2008 : Apply legend font and paint attributes (DG); * 31-Dec-2008 : Fix for bug 2471906 - dashed outlines performance issue (DG); * 11-Jun-2009 : Added a useFillPaint flag and a GradientPaintTransformer for * the paint under the series (DG); * 06-Oct-2011 : Avoid GeneralPath methods requiring Java 1.5 (MK); * 16-Jun-2012 : Removed JCommon dependencies (DG); * */ package org.jfree.chart.renderer.xy; import java.awt.BasicStroke; import java.awt.GradientPaint; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.Shape; import java.awt.Stroke; import java.awt.geom.Area; import java.awt.geom.GeneralPath; import java.awt.geom.Line2D; import java.awt.geom.Rectangle2D; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import org.jfree.chart.HashUtilities; import org.jfree.chart.LegendItem; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.ui.GradientPaintTransformer; import org.jfree.chart.ui.StandardGradientPaintTransformer; import org.jfree.chart.util.PublicCloneable; import org.jfree.chart.util.ShapeUtilities; import org.jfree.chart.entity.EntityCollection; import org.jfree.chart.event.RendererChangeEvent; import org.jfree.chart.labels.XYSeriesLabelGenerator; import org.jfree.chart.labels.XYToolTipGenerator; import org.jfree.chart.plot.CrosshairState; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.PlotRenderingInfo; import org.jfree.chart.plot.XYPlot; import org.jfree.chart.urls.XYURLGenerator; import org.jfree.chart.util.SerialUtilities; import org.jfree.data.xy.XYDataset; /** * Area item renderer for an {@link XYPlot}. This class can draw (a) shapes at * each point, or (b) lines between points, or (c) both shapes and lines, * or (d) filled areas, or (e) filled areas and shapes. The example shown here * is generated by the <code>XYAreaRendererDemo1.java</code> program included * in the JFreeChart demo collection: * <br><br> * <img src="../../../../../images/XYAreaRendererSample.png" * alt="XYAreaRendererSample.png" /> */ public class XYAreaRenderer extends AbstractXYItemRenderer implements XYItemRenderer, PublicCloneable { /** For serialization. */ private static final long serialVersionUID = -4481971353973876747L; /** * A state object used by this renderer. */ static class XYAreaRendererState extends XYItemRendererState { /** Working storage for the area under one series. */ public GeneralPath area; /** Working line that can be recycled. */ public Line2D line; /** * Creates a new state. * * @param info the plot rendering info. */ public XYAreaRendererState(PlotRenderingInfo info) { super(info); this.area = new GeneralPath(); this.line = new Line2D.Double(); } } /** Useful constant for specifying the type of rendering (shapes only). */ public static final int SHAPES = 1; /** Useful constant for specifying the type of rendering (lines only). */ public static final int LINES = 2; /** * Useful constant for specifying the type of rendering (shapes and lines). */ public static final int SHAPES_AND_LINES = 3; /** Useful constant for specifying the type of rendering (area only). */ public static final int AREA = 4; /** * Useful constant for specifying the type of rendering (area and shapes). */ public static final int AREA_AND_SHAPES = 5; /** A flag indicating whether or not shapes are drawn at each XY point. */ private boolean plotShapes; /** A flag indicating whether or not lines are drawn between XY points. */ private boolean plotLines; /** A flag indicating whether or not Area are drawn at each XY point. */ private boolean plotArea; /** A flag that controls whether or not the outline is shown. */ private boolean showOutline; /** * The shape used to represent an area in each legend item (this should * never be <code>null</code>). */ private transient Shape legendArea; /** * A flag that can be set to specify that the fill paint should be used * to fill the area under the renderer. * * @since 1.0.14 */ private boolean useFillPaint; /** * A transformer that is applied to the paint used to fill under the * area *if* it is an instance of GradientPaint. * * @since 1.0.14 */ private GradientPaintTransformer gradientTransformer; /** * Constructs a new renderer. */ public XYAreaRenderer() { this(AREA); } /** * Constructs a new renderer. * * @param type the type of the renderer. */ public XYAreaRenderer(int type) { this(type, null, null); } /** * Constructs a new renderer. To specify the type of renderer, use one of * the constants: <code>SHAPES</code>, <code>LINES</code>, * <code>SHAPES_AND_LINES</code>, <code>AREA</code> or * <code>AREA_AND_SHAPES</code>. * * @param type the type of renderer. * @param toolTipGenerator the tool tip generator to use * (<code>null</code> permitted). * @param urlGenerator the URL generator (<code>null</code> permitted). */ public XYAreaRenderer(int type, XYToolTipGenerator toolTipGenerator, XYURLGenerator urlGenerator) { super(); setDefaultToolTipGenerator(toolTipGenerator); setURLGenerator(urlGenerator); if (type == SHAPES) { this.plotShapes = true; } if (type == LINES) { this.plotLines = true; } if (type == SHAPES_AND_LINES) { this.plotShapes = true; this.plotLines = true; } if (type == AREA) { this.plotArea = true; } if (type == AREA_AND_SHAPES) { this.plotArea = true; this.plotShapes = true; } this.showOutline = false; GeneralPath area = new GeneralPath(); area.moveTo(0.0f, -4.0f); area.lineTo(3.0f, -2.0f); area.lineTo(4.0f, 4.0f); area.lineTo(-4.0f, 4.0f); area.lineTo(-3.0f, -2.0f); area.closePath(); this.legendArea = area; this.useFillPaint = false; this.gradientTransformer = new StandardGradientPaintTransformer(); } /** * Returns true if shapes are being plotted by the renderer. * * @return <code>true</code> if shapes are being plotted by the renderer. */ public boolean getPlotShapes() { return this.plotShapes; } /** * Returns true if lines are being plotted by the renderer. * * @return <code>true</code> if lines are being plotted by the renderer. */ public boolean getPlotLines() { return this.plotLines; } /** * Returns true if Area is being plotted by the renderer. * * @return <code>true</code> if Area is being plotted by the renderer. */ public boolean getPlotArea() { return this.plotArea; } /** * Returns a flag that controls whether or not outlines of the areas are * drawn. * * @return The flag. * * @see #setOutline(boolean) */ public boolean isOutline() { return this.showOutline; } /** * Sets a flag that controls whether or not outlines of the areas are drawn * and sends a {@link RendererChangeEvent} to all registered listeners. * * @param show the flag. * * @see #isOutline() */ public void setOutline(boolean show) { this.showOutline = show; fireChangeEvent(); } /** * Returns the shape used to represent an area in the legend. * * @return The legend area (never <code>null</code>). */ public Shape getLegendArea() { return this.legendArea; } /** * Sets the shape used as an area in each legend item and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param area the area (<code>null</code> not permitted). */ public void setLegendArea(Shape area) { if (area == null) { throw new IllegalArgumentException("Null 'area' argument."); } this.legendArea = area; fireChangeEvent(); } /** * Returns the flag that controls whether the series fill paint is used to * fill the area under the line. * * @return A boolean. * * @since 1.0.14 */ public boolean getUseFillPaint() { return this.useFillPaint; } /** * Sets the flag that controls whether or not the series fill paint is * used to fill the area under the line and sends a * {@link RendererChangeEvent} to all listeners. * * @param use the new flag value. * * @since 1.0.14 */ public void setUseFillPaint(boolean use) { this.useFillPaint = use; fireChangeEvent(); } /** * Returns the gradient paint transformer. * * @return The gradient paint transformer (never <code>null</code>). * * @since 1.0.14 */ public GradientPaintTransformer getGradientTransformer() { return this.gradientTransformer; } /** * Sets the gradient paint transformer and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param transformer the transformer (<code>null</code> not permitted). * * @since 1.0.14 */ public void setGradientTransformer(GradientPaintTransformer transformer) { if (transformer == null) { throw new IllegalArgumentException("Null 'transformer' argument."); } this.gradientTransformer = transformer; fireChangeEvent(); } /** * Initialises the renderer and returns a state object that should be * passed to all subsequent calls to the drawItem() method. * * @param g2 the graphics device. * @param dataArea the area inside the axes. * @param plot the plot. * @param data the data. * @param info an optional info collection object to return data back to * the caller. * * @return A state object for use by the renderer. */ @Override public XYItemRendererState initialise(Graphics2D g2, Rectangle2D dataArea, XYPlot plot, XYDataset data, PlotRenderingInfo info) { XYAreaRendererState state = new XYAreaRendererState(info); // in the rendering process, there is special handling for item // zero, so we can't support processing of visible data items only state.setProcessVisibleItemsOnly(false); return state; } /** * Returns a default legend item for the specified series. Subclasses * should override this method to generate customised items. * * @param datasetIndex the dataset index (zero-based). * @param series the series index (zero-based). * * @return A legend item for the series. */ @Override public LegendItem getLegendItem(int datasetIndex, int series) { LegendItem result = null; XYPlot xyplot = getPlot(); if (xyplot != null) { XYDataset dataset = xyplot.getDataset(datasetIndex); if (dataset != null) { XYSeriesLabelGenerator lg = getLegendItemLabelGenerator(); String label = lg.generateLabel(dataset, series); String description = label; String toolTipText = null; if (getLegendItemToolTipGenerator() != null) { toolTipText = getLegendItemToolTipGenerator().generateLabel( dataset, series); } String urlText = null; if (getLegendItemURLGenerator() != null) { urlText = getLegendItemURLGenerator().generateLabel( dataset, series); } Paint paint = lookupSeriesPaint(series); result = new LegendItem(label, description, toolTipText, urlText, this.legendArea, paint); result.setLabelFont(lookupLegendTextFont(series)); Paint labelPaint = lookupLegendTextPaint(series); if (labelPaint != null) { result.setLabelPaint(labelPaint); } result.setDataset(dataset); result.setDatasetIndex(datasetIndex); result.setSeriesKey(dataset.getSeriesKey(series)); result.setSeriesIndex(series); } } return result; } /** * Draws the visual representation of a single data item. * * @param g2 the graphics device. * @param state the renderer state. * @param dataArea the area within which the data is being drawn. * @param info collects information about the drawing. * @param plot the plot (can be used to obtain standard color information * etc). * @param domainAxis the domain axis. * @param rangeAxis the range axis. * @param dataset the dataset. * @param series the series index (zero-based). * @param item the item index (zero-based). * @param crosshairState crosshair information for the plot * (<code>null</code> permitted). * @param pass the pass index. */ @Override public void drawItem(Graphics2D g2, XYItemRendererState state, Rectangle2D dataArea, PlotRenderingInfo info, XYPlot plot, ValueAxis domainAxis, ValueAxis rangeAxis, XYDataset dataset, int series, int item, CrosshairState crosshairState, int pass) { if (!getItemVisible(series, item)) { return; } XYAreaRendererState areaState = (XYAreaRendererState) state; // get the data point... double x1 = dataset.getXValue(series, item); double y1 = dataset.getYValue(series, item); if (Double.isNaN(y1)) { y1 = 0.0; } double transX1 = domainAxis.valueToJava2D(x1, dataArea, plot.getDomainAxisEdge()); double transY1 = rangeAxis.valueToJava2D(y1, dataArea, plot.getRangeAxisEdge()); // get the previous point and the next point so we can calculate a // "hot spot" for the area (used by the chart entity)... int itemCount = dataset.getItemCount(series); double x0 = dataset.getXValue(series, Math.max(item - 1, 0)); double y0 = dataset.getYValue(series, Math.max(item - 1, 0)); if (Double.isNaN(y0)) { y0 = 0.0; } double transX0 = domainAxis.valueToJava2D(x0, dataArea, plot.getDomainAxisEdge()); double transY0 = rangeAxis.valueToJava2D(y0, dataArea, plot.getRangeAxisEdge()); double x2 = dataset.getXValue(series, Math.min(item + 1, itemCount - 1)); double y2 = dataset.getYValue(series, Math.min(item + 1, itemCount - 1)); if (Double.isNaN(y2)) { y2 = 0.0; } double transX2 = domainAxis.valueToJava2D(x2, dataArea, plot.getDomainAxisEdge()); double transY2 = rangeAxis.valueToJava2D(y2, dataArea, plot.getRangeAxisEdge()); double transZero = rangeAxis.valueToJava2D(0.0, dataArea, plot.getRangeAxisEdge()); GeneralPath hotspot = new GeneralPath(); if (plot.getOrientation() == PlotOrientation.HORIZONTAL) { moveTo(hotspot, transZero, ((transX0 + transX1) / 2.0)); lineTo(hotspot, ((transY0 + transY1) / 2.0), ((transX0 + transX1) / 2.0)); lineTo(hotspot, transY1, transX1); lineTo(hotspot, ((transY1 + transY2) / 2.0), ((transX1 + transX2) / 2.0)); lineTo(hotspot, transZero, ((transX1 + transX2) / 2.0)); } else { // vertical orientation moveTo(hotspot, ((transX0 + transX1) / 2.0), transZero); lineTo(hotspot, ((transX0 + transX1) / 2.0), ((transY0 + transY1) / 2.0)); lineTo(hotspot, transX1, transY1); lineTo(hotspot, ((transX1 + transX2) / 2.0), ((transY1 + transY2) / 2.0)); lineTo(hotspot, ((transX1 + transX2) / 2.0), transZero); } hotspot.closePath(); if (item == 0) { // create a new area polygon for the series areaState.area = new GeneralPath(); // the first point is (x, 0) double zero = rangeAxis.valueToJava2D(0.0, dataArea, plot.getRangeAxisEdge()); if (plot.getOrientation() == PlotOrientation.VERTICAL) { moveTo(areaState.area, transX1, zero); } else if (plot.getOrientation() == PlotOrientation.HORIZONTAL) { moveTo(areaState.area, zero, transX1); } } // Add each point to Area (x, y) if (plot.getOrientation() == PlotOrientation.VERTICAL) { lineTo(areaState.area, transX1, transY1); } else if (plot.getOrientation() == PlotOrientation.HORIZONTAL) { lineTo(areaState.area, transY1, transX1); } PlotOrientation orientation = plot.getOrientation(); Paint paint = getItemPaint(series, item); Stroke stroke = getItemStroke(series, item); g2.setPaint(paint); g2.setStroke(stroke); Shape shape; if (getPlotShapes()) { shape = getItemShape(series, item); if (orientation == PlotOrientation.VERTICAL) { shape = ShapeUtilities.createTranslatedShape(shape, transX1, transY1); } else if (orientation == PlotOrientation.HORIZONTAL) { shape = ShapeUtilities.createTranslatedShape(shape, transY1, transX1); } g2.draw(shape); } if (getPlotLines()) { if (item > 0) { if (plot.getOrientation() == PlotOrientation.VERTICAL) { areaState.line.setLine(transX0, transY0, transX1, transY1); } else if (plot.getOrientation() == PlotOrientation.HORIZONTAL) { areaState.line.setLine(transY0, transX0, transY1, transX1); } g2.draw(areaState.line); } } // Check if the item is the last item for the series. // and number of items > 0. We can't draw an area for a single point. if (getPlotArea() && item > 0 && item == (itemCount - 1)) { if (orientation == PlotOrientation.VERTICAL) { // Add the last point (x,0) lineTo(areaState.area, transX1, transZero); areaState.area.closePath(); } else if (orientation == PlotOrientation.HORIZONTAL) { // Add the last point (x,0) lineTo(areaState.area, transZero, transX1); areaState.area.closePath(); } if (this.useFillPaint) { paint = lookupSeriesFillPaint(series); } if (paint instanceof GradientPaint) { GradientPaint gp = (GradientPaint) paint; GradientPaint adjGP = this.gradientTransformer.transform(gp, dataArea); g2.setPaint(adjGP); } g2.fill(areaState.area); // draw an outline around the Area. if (isOutline()) { Shape area = areaState.area; // Java2D has some issues drawing dashed lines around "large" // geometrical shapes - for example, see bug 6620013 in the // Java bug database. So, we'll check if the outline is // dashed and, if it is, do our own clipping before drawing // the outline... Stroke outlineStroke = lookupSeriesOutlineStroke(series); if (outlineStroke instanceof BasicStroke) { BasicStroke bs = (BasicStroke) outlineStroke; if (bs.getDashArray() != null) { Area poly = new Area(areaState.area); // we make the clip region slightly larger than the // dataArea so that the clipped edges don't show lines // on the chart Area clip = new Area(new Rectangle2D.Double( dataArea.getX() - 5.0, dataArea.getY() - 5.0, dataArea.getWidth() + 10.0, dataArea.getHeight() + 10.0)); poly.intersect(clip); area = poly; } } // end of workaround g2.setStroke(outlineStroke); g2.setPaint(lookupSeriesOutlinePaint(series)); g2.draw(area); } } int domainAxisIndex = plot.getDomainAxisIndex(domainAxis); int rangeAxisIndex = plot.getRangeAxisIndex(rangeAxis); updateCrosshairValues(crosshairState, x1, y1, domainAxisIndex, rangeAxisIndex, transX1, transY1, orientation); // collect entity and tool tip information... EntityCollection entities = state.getEntityCollection(); if (entities != null) { addEntity(entities, hotspot, dataset, series, item, 0.0, 0.0); } } /** * Returns a clone of the renderer. * * @return A clone. * * @throws CloneNotSupportedException if the renderer cannot be cloned. */ @Override public Object clone() throws CloneNotSupportedException { XYAreaRenderer clone = (XYAreaRenderer) super.clone(); clone.legendArea = ShapeUtilities.clone(this.legendArea); return clone; } /** * Tests this renderer for equality with an arbitrary object. * * @param obj the object (<code>null</code> permitted). * * @return A boolean. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof XYAreaRenderer)) { return false; } XYAreaRenderer that = (XYAreaRenderer) obj; if (this.plotArea != that.plotArea) { return false; } if (this.plotLines != that.plotLines) { return false; } if (this.plotShapes != that.plotShapes) { return false; } if (this.showOutline != that.showOutline) { return false; } if (this.useFillPaint != that.useFillPaint) { return false; } if (!this.gradientTransformer.equals(that.gradientTransformer)) { return false; } if (!ShapeUtilities.equal(this.legendArea, that.legendArea)) { return false; } return true; } /** * Returns a hash code for this instance. * * @return A hash code. */ @Override public int hashCode() { int result = super.hashCode(); result = HashUtilities.hashCode(result, this.plotArea); result = HashUtilities.hashCode(result, this.plotLines); result = HashUtilities.hashCode(result, this.plotShapes); result = HashUtilities.hashCode(result, this.useFillPaint); return result; } /** * Provides serialization support. * * @param stream the input stream. * * @throws IOException if there is an I/O error. * @throws ClassNotFoundException if there is a classpath problem. */ private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); this.legendArea = SerialUtilities.readShape(stream); } /** * Provides serialization support. * * @param stream the output stream. * * @throws IOException if there is an I/O error. */ private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); SerialUtilities.writeShape(this.legendArea, stream); } }
28,687
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
XYDifferenceRenderer.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/renderer/xy/XYDifferenceRenderer.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ------------------------- * XYDifferenceRenderer.java * ------------------------- * (C) Copyright 2003-2012, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): Richard West, Advanced Micro Devices, Inc. (major rewrite * of difference drawing algorithm); * Patrick Schlott * Christoph Schroeder * Martin Hoeller * * Changes: * -------- * 30-Apr-2003 : Version 1 (DG); * 30-Jul-2003 : Modified entity constructor (CZ); * 20-Aug-2003 : Implemented Cloneable and PublicCloneable (DG); * 16-Sep-2003 : Changed ChartRenderingInfo --> PlotRenderingInfo (DG); * 09-Feb-2004 : Updated to support horizontal plot orientation (DG); * 10-Feb-2004 : Added default constructor, setter methods and updated * Javadocs (DG); * 25-Feb-2004 : Replaced CrosshairInfo with CrosshairState (DG); * 30-Mar-2004 : Fixed bug in getNegativePaint() method (DG); * 15-Jul-2004 : Switched getX() with getXValue() and getY() with * getYValue() (DG); * 25-Aug-2004 : Fixed a bug preventing the use of crosshairs (DG); * 11-Nov-2004 : Now uses ShapeUtilities to translate shapes (DG); * 19-Jan-2005 : Now accesses only primitive values from dataset (DG); * 22-Feb-2005 : Override getLegendItem(int, int) to return "line" items (DG); * 13-Apr-2005 : Fixed shape positioning bug (id = 1182062) (DG); * 20-Apr-2005 : Use generators for legend tooltips and URLs (DG); * 04-May-2005 : Override equals() method, renamed get/setPlotShapes() --> * get/setShapesVisible (DG); * 09-Jun-2005 : Updated equals() to handle GradientPaint (DG); * 16-Jun-2005 : Fix bug (1221021) affecting stroke used for each series (DG); * ------------- JFREECHART 1.0.x --------------------------------------------- * 24-Jan-2007 : Added flag to allow rounding of x-coordinates, and fixed * bug in clone() (DG); * 05-Feb-2007 : Added an extra call to updateCrosshairValues() in * drawItemPass1(), to fix bug 1564967 (DG); * 06-Feb-2007 : Fixed bug 1086307, crosshairs with multiple axes (DG); * 08-Mar-2007 : Fixed entity generation (DG); * 20-Apr-2007 : Updated getLegendItem() for renderer change (DG); * 23-Apr-2007 : Rewrite of difference drawing algorithm to allow use of * series with disjoint x-values (RW); * 04-May-2007 : Set processVisibleItemsOnly flag to false (DG); * 17-May-2007 : Set datasetIndex and seriesIndex in getLegendItem() (DG); * 18-May-2007 : Set dataset and seriesKey for LegendItem (DG); * 05-Nov-2007 : Draw item labels if visible (RW); * 17-Jun-2008 : Apply legend shape, font and paint attributes (DG); * 13-Feb-2012 : Applied patch 3450234 for bug 3425881 by Patrick Schlott and * Christoph Schroeder (MH); * 16-Jun-2012 : Removed JCommon dependencies (DG); * */ package org.jfree.chart.renderer.xy; import java.awt.Color; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.Shape; import java.awt.Stroke; import java.awt.geom.GeneralPath; import java.awt.geom.Line2D; import java.awt.geom.Rectangle2D; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Collections; import java.util.LinkedList; import org.jfree.chart.LegendItem; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.ui.RectangleEdge; import org.jfree.chart.util.PaintUtilities; import org.jfree.chart.util.PublicCloneable; import org.jfree.chart.util.ShapeUtilities; import org.jfree.chart.entity.EntityCollection; import org.jfree.chart.entity.XYItemEntity; import org.jfree.chart.event.RendererChangeEvent; import org.jfree.chart.labels.XYToolTipGenerator; import org.jfree.chart.plot.CrosshairState; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.PlotRenderingInfo; import org.jfree.chart.plot.XYPlot; import org.jfree.chart.urls.XYURLGenerator; import org.jfree.chart.util.SerialUtilities; import org.jfree.data.xy.XYDataset; /** * A renderer for an {@link XYPlot} that highlights the differences between two * series. The example shown here is generated by the * <code>DifferenceChartDemo1.java</code> program included in the JFreeChart * demo collection: * <br><br> * <img src="../../../../../images/XYDifferenceRendererSample.png" * alt="XYDifferenceRendererSample.png" /> */ public class XYDifferenceRenderer extends AbstractXYItemRenderer implements XYItemRenderer, PublicCloneable { /** For serialization. */ private static final long serialVersionUID = -8447915602375584857L; /** The paint used to highlight positive differences (y(0) > y(1)). */ private transient Paint positivePaint; /** The paint used to highlight negative differences (y(0) < y(1)). */ private transient Paint negativePaint; /** Display shapes at each point? */ private boolean shapesVisible; /** The shape to display in the legend item. */ private transient Shape legendLine; /** * This flag controls whether or not the x-coordinates (in Java2D space) * are rounded to integers. When set to true, this can avoid the vertical * striping that anti-aliasing can generate. However, the rounding may not * be appropriate for output in high resolution formats (for example, * vector graphics formats such as SVG and PDF). * * @since 1.0.4 */ private boolean roundXCoordinates; /** * Creates a new renderer with default attributes. */ public XYDifferenceRenderer() { this(Color.GREEN, Color.RED, false); } /** * Creates a new renderer. * * @param positivePaint the highlight color for positive differences * (<code>null</code> not permitted). * @param negativePaint the highlight color for negative differences * (<code>null</code> not permitted). * @param shapes draw shapes? */ public XYDifferenceRenderer(Paint positivePaint, Paint negativePaint, boolean shapes) { if (positivePaint == null) { throw new IllegalArgumentException( "Null 'positivePaint' argument."); } if (negativePaint == null) { throw new IllegalArgumentException( "Null 'negativePaint' argument."); } this.positivePaint = positivePaint; this.negativePaint = negativePaint; this.shapesVisible = shapes; this.legendLine = new Line2D.Double(-7.0, 0.0, 7.0, 0.0); this.roundXCoordinates = false; } /** * Returns the paint used to highlight positive differences. * * @return The paint (never <code>null</code>). * * @see #setPositivePaint(Paint) */ public Paint getPositivePaint() { return this.positivePaint; } /** * Sets the paint used to highlight positive differences and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param paint the paint (<code>null</code> not permitted). * * @see #getPositivePaint() */ public void setPositivePaint(Paint paint) { if (paint == null) { throw new IllegalArgumentException("Null 'paint' argument."); } this.positivePaint = paint; fireChangeEvent(); } /** * Returns the paint used to highlight negative differences. * * @return The paint (never <code>null</code>). * * @see #setNegativePaint(Paint) */ public Paint getNegativePaint() { return this.negativePaint; } /** * Sets the paint used to highlight negative differences. * * @param paint the paint (<code>null</code> not permitted). * * @see #getNegativePaint() */ public void setNegativePaint(Paint paint) { if (paint == null) { throw new IllegalArgumentException("Null 'paint' argument."); } this.negativePaint = paint; notifyListeners(new RendererChangeEvent(this)); } /** * Returns a flag that controls whether or not shapes are drawn for each * data value. * * @return A boolean. * * @see #setShapesVisible(boolean) */ public boolean getShapesVisible() { return this.shapesVisible; } /** * Sets a flag that controls whether or not shapes are drawn for each * data value, and sends a {@link RendererChangeEvent} to all registered * listeners. * * @param flag the flag. * * @see #getShapesVisible() */ public void setShapesVisible(boolean flag) { this.shapesVisible = flag; fireChangeEvent(); } /** * Returns the shape used to represent a line in the legend. * * @return The legend line (never <code>null</code>). * * @see #setLegendLine(Shape) */ public Shape getLegendLine() { return this.legendLine; } /** * Sets the shape used as a line in each legend item and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param line the line (<code>null</code> not permitted). * * @see #getLegendLine() */ public void setLegendLine(Shape line) { if (line == null) { throw new IllegalArgumentException("Null 'line' argument."); } this.legendLine = line; fireChangeEvent(); } /** * Returns the flag that controls whether or not the x-coordinates (in * Java2D space) are rounded to integer values. * * @return The flag. * * @since 1.0.4 * * @see #setRoundXCoordinates(boolean) */ public boolean getRoundXCoordinates() { return this.roundXCoordinates; } /** * Sets the flag that controls whether or not the x-coordinates (in * Java2D space) are rounded to integer values, and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param round the new flag value. * * @since 1.0.4 * * @see #getRoundXCoordinates() */ public void setRoundXCoordinates(boolean round) { this.roundXCoordinates = round; fireChangeEvent(); } /** * Initialises the renderer and returns a state object that should be * passed to subsequent calls to the drawItem() method. This method will * be called before the first item is rendered, giving the renderer an * opportunity to initialise any state information it wants to maintain. * The renderer can do nothing if it chooses. * * @param g2 the graphics device. * @param dataArea the area inside the axes. * @param plot the plot. * @param data the data. * @param info an optional info collection object to return data back to * the caller. * * @return A state object. */ @Override public XYItemRendererState initialise(Graphics2D g2, Rectangle2D dataArea, XYPlot plot, XYDataset data, PlotRenderingInfo info) { XYItemRendererState state = super.initialise(g2, dataArea, plot, data, info); state.setProcessVisibleItemsOnly(false); return state; } /** * Returns <code>2</code>, the number of passes required by the renderer. * The {@link XYPlot} will run through the dataset this number of times. * * @return The number of passes required by the renderer. */ @Override public int getPassCount() { return 2; } /** * Draws the visual representation of a single data item. * * @param g2 the graphics device. * @param state the renderer state. * @param dataArea the area within which the data is being drawn. * @param info collects information about the drawing. * @param plot the plot (can be used to obtain standard color * information etc). * @param domainAxis the domain (horizontal) axis. * @param rangeAxis the range (vertical) axis. * @param dataset the dataset. * @param series the series index (zero-based). * @param item the item index (zero-based). * @param crosshairState crosshair information for the plot * (<code>null</code> permitted). * @param pass the pass index. */ @Override public void drawItem(Graphics2D g2, XYItemRendererState state, Rectangle2D dataArea, PlotRenderingInfo info, XYPlot plot, ValueAxis domainAxis, ValueAxis rangeAxis, XYDataset dataset, int series, int item, CrosshairState crosshairState, int pass) { if (pass == 0) { drawItemPass0(g2, dataArea, info, plot, domainAxis, rangeAxis, dataset, series, item, crosshairState); } else if (pass == 1) { drawItemPass1(g2, dataArea, info, plot, domainAxis, rangeAxis, dataset, series, item, crosshairState); } } /** * Draws the visual representation of a single data item, first pass. * * @param x_graphics the graphics device. * @param x_dataArea the area within which the data is being drawn. * @param x_info collects information about the drawing. * @param x_plot the plot (can be used to obtain standard color * information etc). * @param x_domainAxis the domain (horizontal) axis. * @param x_rangeAxis the range (vertical) axis. * @param x_dataset the dataset. * @param x_series the series index (zero-based). * @param x_item the item index (zero-based). * @param x_crosshairState crosshair information for the plot * (<code>null</code> permitted). */ protected void drawItemPass0(Graphics2D x_graphics, Rectangle2D x_dataArea, PlotRenderingInfo x_info, XYPlot x_plot, ValueAxis x_domainAxis, ValueAxis x_rangeAxis, XYDataset x_dataset, int x_series, int x_item, CrosshairState x_crosshairState) { if (!((0 == x_series) && (0 == x_item))) { return; } boolean b_impliedZeroSubtrahend = (1 == x_dataset.getSeriesCount()); // check if either series is a degenerate case (i.e. less than 2 points) if (isEitherSeriesDegenerate(x_dataset, b_impliedZeroSubtrahend)) { return; } // check if series are disjoint (i.e. domain-spans do not overlap) if (!b_impliedZeroSubtrahend && areSeriesDisjoint(x_dataset)) { return; } // polygon definitions LinkedList<Double> l_minuendXs = new LinkedList<Double>(); LinkedList<Double> l_minuendYs = new LinkedList<Double>(); LinkedList<Double> l_subtrahendXs = new LinkedList<Double>(); LinkedList<Double> l_subtrahendYs = new LinkedList<Double>(); LinkedList<Double> l_polygonXs = new LinkedList<Double>(); LinkedList<Double> l_polygonYs = new LinkedList<Double>(); // state int l_minuendItem = 0; int l_minuendItemCount = x_dataset.getItemCount(0); Double l_minuendCurX = null; Double l_minuendNextX = null; Double l_minuendCurY = null; Double l_minuendNextY = null; double l_minuendMaxY = Double.NEGATIVE_INFINITY; double l_minuendMinY = Double.POSITIVE_INFINITY; int l_subtrahendItem = 0; int l_subtrahendItemCount; // actual value set below Double l_subtrahendCurX = null; Double l_subtrahendNextX = null; Double l_subtrahendCurY = null; Double l_subtrahendNextY = null; double l_subtrahendMaxY = Double.NEGATIVE_INFINITY; double l_subtrahendMinY = Double.POSITIVE_INFINITY; // if a subtrahend is not specified, assume it is zero if (b_impliedZeroSubtrahend) { l_subtrahendItem = 0; l_subtrahendItemCount = 2; l_subtrahendCurX = x_dataset.getXValue(0, 0); l_subtrahendNextX = x_dataset.getXValue(0, (l_minuendItemCount - 1)); l_subtrahendCurY = 0.0; l_subtrahendNextY = 0.0; l_subtrahendMaxY = 0.0; l_subtrahendMinY = 0.0; l_subtrahendXs.add(l_subtrahendCurX); l_subtrahendYs.add(l_subtrahendCurY); } else { l_subtrahendItemCount = x_dataset.getItemCount(1); } boolean b_minuendDone = false; boolean b_minuendAdvanced = true; boolean b_minuendAtIntersect = false; boolean b_minuendFastForward = false; boolean b_subtrahendDone = false; boolean b_subtrahendAdvanced = true; boolean b_subtrahendAtIntersect = false; boolean b_subtrahendFastForward = false; boolean b_colinear = false; boolean b_positive; // coordinate pairs double l_x1 = 0.0, l_y1 = 0.0; // current minuend point double l_x2 = 0.0, l_y2 = 0.0; // next minuend point double l_x3 = 0.0, l_y3 = 0.0; // current subtrahend point double l_x4 = 0.0, l_y4 = 0.0; // next subtrahend point // fast-forward through leading tails boolean b_fastForwardDone = false; while (!b_fastForwardDone) { // get the x and y coordinates l_x1 = x_dataset.getXValue(0, l_minuendItem); l_y1 = x_dataset.getYValue(0, l_minuendItem); l_x2 = x_dataset.getXValue(0, l_minuendItem + 1); l_y2 = x_dataset.getYValue(0, l_minuendItem + 1); l_minuendCurX = l_x1; l_minuendCurY = l_y1; l_minuendNextX = l_x2; l_minuendNextY = l_y2; if (b_impliedZeroSubtrahend) { l_x3 = l_subtrahendCurX; l_y3 = l_subtrahendCurY; l_x4 = l_subtrahendNextX; l_y4 = l_subtrahendNextY; } else { l_x3 = x_dataset.getXValue(1, l_subtrahendItem); l_y3 = x_dataset.getYValue(1, l_subtrahendItem); l_x4 = x_dataset.getXValue(1, l_subtrahendItem + 1); l_y4 = x_dataset.getYValue(1, l_subtrahendItem + 1); l_subtrahendCurX = l_x3; l_subtrahendCurY = l_y3; l_subtrahendNextX = l_x4; l_subtrahendNextY = l_y4; } if (l_x2 <= l_x3) { // minuend needs to be fast forwarded l_minuendItem++; b_minuendFastForward = true; continue; } if (l_x4 <= l_x1) { // subtrahend needs to be fast forwarded l_subtrahendItem++; b_subtrahendFastForward = true; continue; } // check if initial polygon needs to be clipped if ((l_x3 < l_x1) && (l_x1 < l_x4)) { // project onto subtrahend double l_slope = (l_y4 - l_y3) / (l_x4 - l_x3); l_subtrahendCurX = l_minuendCurX; l_subtrahendCurY = (l_slope * l_x1) + (l_y3 - (l_slope * l_x3)); l_subtrahendXs.add(l_subtrahendCurX); l_subtrahendYs.add(l_subtrahendCurY); } if ((l_x1 < l_x3) && (l_x3 < l_x2)) { // project onto minuend double l_slope = (l_y2 - l_y1) / (l_x2 - l_x1); l_minuendCurX = l_subtrahendCurX; l_minuendCurY = (l_slope * l_x3) + (l_y1 - (l_slope * l_x1)); l_minuendXs.add(l_minuendCurX); l_minuendYs.add(l_minuendCurY); } l_minuendMaxY = l_minuendCurY; l_minuendMinY = l_minuendCurY; l_subtrahendMaxY = l_subtrahendCurY; l_subtrahendMinY = l_subtrahendCurY; b_fastForwardDone = true; } // start of algorithm while (!b_minuendDone && !b_subtrahendDone) { if (!b_minuendDone && !b_minuendFastForward && b_minuendAdvanced) { l_x1 = x_dataset.getXValue(0, l_minuendItem); l_y1 = x_dataset.getYValue(0, l_minuendItem); l_minuendCurX = l_x1; l_minuendCurY = l_y1; if (!b_minuendAtIntersect) { l_minuendXs.add(l_minuendCurX); l_minuendYs.add(l_minuendCurY); } l_minuendMaxY = Math.max(l_minuendMaxY, l_y1); l_minuendMinY = Math.min(l_minuendMinY, l_y1); l_x2 = x_dataset.getXValue(0, l_minuendItem + 1); l_y2 = x_dataset.getYValue(0, l_minuendItem + 1); l_minuendNextX = l_x2; l_minuendNextY = l_y2; } // never updated the subtrahend if it is implied to be zero if (!b_impliedZeroSubtrahend && !b_subtrahendDone && !b_subtrahendFastForward && b_subtrahendAdvanced) { l_x3 = x_dataset.getXValue(1, l_subtrahendItem); l_y3 = x_dataset.getYValue(1, l_subtrahendItem); l_subtrahendCurX = l_x3; l_subtrahendCurY = l_y3; if (!b_subtrahendAtIntersect) { l_subtrahendXs.add(l_subtrahendCurX); l_subtrahendYs.add(l_subtrahendCurY); } l_subtrahendMaxY = Math.max(l_subtrahendMaxY, l_y3); l_subtrahendMinY = Math.min(l_subtrahendMinY, l_y3); l_x4 = x_dataset.getXValue(1, l_subtrahendItem + 1); l_y4 = x_dataset.getYValue(1, l_subtrahendItem + 1); l_subtrahendNextX = l_x4; l_subtrahendNextY = l_y4; } // deassert b_*FastForward (only matters for 1st time through loop) b_minuendFastForward = false; b_subtrahendFastForward = false; Double l_intersectX = null; Double l_intersectY = null; boolean b_intersect = false; b_minuendAtIntersect = false; b_subtrahendAtIntersect = false; // check for intersect if ((l_x2 == l_x4) && (l_y2 == l_y4)) { // check if line segments are colinear if ((l_x1 == l_x3) && (l_y1 == l_y3)) { b_colinear = true; } else { // the intersect is at the next point for both the minuend // and subtrahend l_intersectX = l_x2; l_intersectY = l_y2; b_intersect = true; b_minuendAtIntersect = true; b_subtrahendAtIntersect = true; } } else { // compute common denominator double l_denominator = ((l_y4 - l_y3) * (l_x2 - l_x1)) - ((l_x4 - l_x3) * (l_y2 - l_y1)); // compute common deltas double l_deltaY = l_y1 - l_y3; double l_deltaX = l_x1 - l_x3; // compute numerators double l_numeratorA = ((l_x4 - l_x3) * l_deltaY) - ((l_y4 - l_y3) * l_deltaX); double l_numeratorB = ((l_x2 - l_x1) * l_deltaY) - ((l_y2 - l_y1) * l_deltaX); // check if line segments are colinear if ((0 == l_numeratorA) && (0 == l_numeratorB) && (0 == l_denominator)) { b_colinear = true; } else { // check if previously colinear if (b_colinear) { // clear colinear points and flag l_minuendXs.clear(); l_minuendYs.clear(); l_subtrahendXs.clear(); l_subtrahendYs.clear(); l_polygonXs.clear(); l_polygonYs.clear(); b_colinear = false; // set new starting point for the polygon boolean b_useMinuend = ((l_x3 <= l_x1) && (l_x1 <= l_x4)); l_polygonXs.add(b_useMinuend ? l_minuendCurX : l_subtrahendCurX); l_polygonYs.add(b_useMinuend ? l_minuendCurY : l_subtrahendCurY); } } // compute slope components double l_slopeA = l_numeratorA / l_denominator; double l_slopeB = l_numeratorB / l_denominator; // test if both grahphs have a vertical rise at the same x-value boolean b_vertical = (l_x1 == l_x2) && (l_x3 == l_x4) && (l_x2 == l_x4); // check if the line segments intersect if (((0 < l_slopeA) && (l_slopeA <= 1) && (0 < l_slopeB) && (l_slopeB <= 1))|| b_vertical) { // compute the point of intersection double l_xi; double l_yi; if(b_vertical){ b_colinear = false; l_xi = l_x2; l_yi = l_x4; } else{ l_xi = l_x1 + (l_slopeA * (l_x2 - l_x1)); l_yi = l_y1 + (l_slopeA * (l_y2 - l_y1)); } l_intersectX = l_xi; l_intersectY = l_yi; b_intersect = true; b_minuendAtIntersect = ((l_xi == l_x2) && (l_yi == l_y2)); b_subtrahendAtIntersect = ((l_xi == l_x4) && (l_yi == l_y4)); // advance minuend and subtrahend to intesect l_minuendCurX = l_intersectX; l_minuendCurY = l_intersectY; l_subtrahendCurX = l_intersectX; l_subtrahendCurY = l_intersectY; } } if (b_intersect) { // create the polygon // add the minuend's points to polygon l_polygonXs.addAll(l_minuendXs); l_polygonYs.addAll(l_minuendYs); // add intersection point to the polygon l_polygonXs.add(l_intersectX); l_polygonYs.add(l_intersectY); // add the subtrahend's points to the polygon in reverse Collections.reverse(l_subtrahendXs); Collections.reverse(l_subtrahendYs); l_polygonXs.addAll(l_subtrahendXs); l_polygonYs.addAll(l_subtrahendYs); // create an actual polygon b_positive = (l_subtrahendMaxY <= l_minuendMaxY) && (l_subtrahendMinY <= l_minuendMinY); createPolygon(x_graphics, x_dataArea, x_plot, x_domainAxis, x_rangeAxis, b_positive, l_polygonXs, l_polygonYs); // clear the point vectors l_minuendXs.clear(); l_minuendYs.clear(); l_subtrahendXs.clear(); l_subtrahendYs.clear(); l_polygonXs.clear(); l_polygonYs.clear(); // set the maxY and minY values to intersect y-value double l_y = l_intersectY; l_minuendMaxY = l_y; l_subtrahendMaxY = l_y; l_minuendMinY = l_y; l_subtrahendMinY = l_y; // add interection point to new polygon l_polygonXs.add(l_intersectX); l_polygonYs.add(l_intersectY); } // advance the minuend if needed if (l_x2 <= l_x4) { l_minuendItem++; b_minuendAdvanced = true; } else { b_minuendAdvanced = false; } // advance the subtrahend if needed if (l_x4 <= l_x2) { l_subtrahendItem++; b_subtrahendAdvanced = true; } else { b_subtrahendAdvanced = false; } b_minuendDone = (l_minuendItem == (l_minuendItemCount - 1)); b_subtrahendDone = (l_subtrahendItem == (l_subtrahendItemCount - 1)); } // check if the final polygon needs to be clipped if (b_minuendDone && (l_x3 < l_x2) && (l_x2 < l_x4)) { // project onto subtrahend double l_slope = (l_y4 - l_y3) / (l_x4 - l_x3); l_subtrahendNextX = l_minuendNextX; l_subtrahendNextY = (l_slope * l_x2) + (l_y3 - (l_slope * l_x3)); } if (b_subtrahendDone && (l_x1 < l_x4) && (l_x4 < l_x2)) { // project onto minuend double l_slope = (l_y2 - l_y1) / (l_x2 - l_x1); l_minuendNextX = l_subtrahendNextX; l_minuendNextY = (l_slope * l_x4) + (l_y1 - (l_slope * l_x1)); } // consider last point of minuend and subtrahend for determining // positivity l_minuendMaxY = Math.max(l_minuendMaxY, l_minuendNextY); l_subtrahendMaxY = Math.max(l_subtrahendMaxY, l_subtrahendNextY); l_minuendMinY = Math.min(l_minuendMinY, l_minuendNextY); l_subtrahendMinY = Math.min(l_subtrahendMinY, l_subtrahendNextY); // add the last point of the minuned and subtrahend l_minuendXs.add(l_minuendNextX); l_minuendYs.add(l_minuendNextY); l_subtrahendXs.add(l_subtrahendNextX); l_subtrahendYs.add(l_subtrahendNextY); // create the polygon // add the minuend's points to polygon l_polygonXs.addAll(l_minuendXs); l_polygonYs.addAll(l_minuendYs); // add the subtrahend's points to the polygon in reverse Collections.reverse(l_subtrahendXs); Collections.reverse(l_subtrahendYs); l_polygonXs.addAll(l_subtrahendXs); l_polygonYs.addAll(l_subtrahendYs); // create an actual polygon b_positive = (l_subtrahendMaxY <= l_minuendMaxY) && (l_subtrahendMinY <= l_minuendMinY); createPolygon(x_graphics, x_dataArea, x_plot, x_domainAxis, x_rangeAxis, b_positive, l_polygonXs, l_polygonYs); } /** * Draws the visual representation of a single data item, second pass. In * the second pass, the renderer draws the lines and shapes for the * individual points in the two series. * * @param x_graphics the graphics device. * @param x_dataArea the area within which the data is being drawn. * @param x_info collects information about the drawing. * @param x_plot the plot (can be used to obtain standard color * information etc). * @param x_domainAxis the domain (horizontal) axis. * @param x_rangeAxis the range (vertical) axis. * @param x_dataset the dataset. * @param x_series the series index (zero-based). * @param x_item the item index (zero-based). * @param x_crosshairState crosshair information for the plot * (<code>null</code> permitted). */ protected void drawItemPass1(Graphics2D x_graphics, Rectangle2D x_dataArea, PlotRenderingInfo x_info, XYPlot x_plot, ValueAxis x_domainAxis, ValueAxis x_rangeAxis, XYDataset x_dataset, int x_series, int x_item, CrosshairState x_crosshairState) { Shape l_entityArea = null; EntityCollection l_entities = null; if (null != x_info) { l_entities = x_info.getOwner().getEntityCollection(); } Paint l_seriesPaint = getItemPaint(x_series, x_item); Stroke l_seriesStroke = getItemStroke(x_series, x_item); x_graphics.setPaint(l_seriesPaint); x_graphics.setStroke(l_seriesStroke); PlotOrientation l_orientation = x_plot.getOrientation(); RectangleEdge l_domainAxisLocation = x_plot.getDomainAxisEdge(); RectangleEdge l_rangeAxisLocation = x_plot.getRangeAxisEdge(); double l_x0 = x_dataset.getXValue(x_series, x_item); double l_y0 = x_dataset.getYValue(x_series, x_item); double l_x1 = x_domainAxis.valueToJava2D(l_x0, x_dataArea, l_domainAxisLocation); double l_y1 = x_rangeAxis.valueToJava2D(l_y0, x_dataArea, l_rangeAxisLocation); if (getShapesVisible()) { Shape l_shape = getItemShape(x_series, x_item); if (l_orientation == PlotOrientation.HORIZONTAL) { l_shape = ShapeUtilities.createTranslatedShape(l_shape, l_y1, l_x1); } else { l_shape = ShapeUtilities.createTranslatedShape(l_shape, l_x1, l_y1); } if (l_shape.intersects(x_dataArea)) { x_graphics.setPaint(getItemPaint(x_series, x_item)); x_graphics.fill(l_shape); } l_entityArea = l_shape; } // add an entity for the item... if (null != l_entities) { if (null == l_entityArea) { l_entityArea = new Rectangle2D.Double((l_x1 - 2), (l_y1 - 2), 4, 4); } String l_tip = null; XYToolTipGenerator l_tipGenerator = getToolTipGenerator(x_series, x_item); if (null != l_tipGenerator) { l_tip = l_tipGenerator.generateToolTip(x_dataset, x_series, x_item); } String l_url = null; XYURLGenerator l_urlGenerator = getURLGenerator(); if (null != l_urlGenerator) { l_url = l_urlGenerator.generateURL(x_dataset, x_series, x_item); } XYItemEntity l_entity = new XYItemEntity(l_entityArea, x_dataset, x_series, x_item, l_tip, l_url); l_entities.add(l_entity); } // draw the item label if there is one... if (isItemLabelVisible(x_series, x_item)) { drawItemLabel(x_graphics, l_orientation, x_dataset, x_series, x_item, l_x1, l_y1, (l_y1 < 0.0)); } int l_domainAxisIndex = x_plot.getDomainAxisIndex(x_domainAxis); int l_rangeAxisIndex = x_plot.getRangeAxisIndex(x_rangeAxis); updateCrosshairValues(x_crosshairState, l_x0, l_y0, l_domainAxisIndex, l_rangeAxisIndex, l_x1, l_y1, l_orientation); if (0 == x_item) { return; } double l_x2 = x_domainAxis.valueToJava2D(x_dataset.getXValue(x_series, (x_item - 1)), x_dataArea, l_domainAxisLocation); double l_y2 = x_rangeAxis.valueToJava2D(x_dataset.getYValue(x_series, (x_item - 1)), x_dataArea, l_rangeAxisLocation); Line2D l_line = null; if (PlotOrientation.HORIZONTAL == l_orientation) { l_line = new Line2D.Double(l_y1, l_x1, l_y2, l_x2); } else if (PlotOrientation.VERTICAL == l_orientation) { l_line = new Line2D.Double(l_x1, l_y1, l_x2, l_y2); } if ((null != l_line) && l_line.intersects(x_dataArea)) { x_graphics.setPaint(getItemPaint(x_series, x_item)); x_graphics.setStroke(getItemStroke(x_series, x_item)); x_graphics.draw(l_line); } } /** * Determines if a dataset is degenerate. A degenerate dataset is a * dataset where either series has less than two (2) points. * * @param x_dataset the dataset. * @param x_impliedZeroSubtrahend if false, do not check the subtrahend * * @return true if the dataset is degenerate. */ private boolean isEitherSeriesDegenerate(XYDataset x_dataset, boolean x_impliedZeroSubtrahend) { if (x_impliedZeroSubtrahend) { return (x_dataset.getItemCount(0) < 2); } return ((x_dataset.getItemCount(0) < 2) || (x_dataset.getItemCount(1) < 2)); } /** * Determines if the two (2) series are disjoint. * Disjoint series do not overlap in the domain space. * * @param x_dataset the dataset. * * @return true if the dataset is degenerate. */ private boolean areSeriesDisjoint(XYDataset x_dataset) { int l_minuendItemCount = x_dataset.getItemCount(0); double l_minuendFirst = x_dataset.getXValue(0, 0); double l_minuendLast = x_dataset.getXValue(0, l_minuendItemCount - 1); int l_subtrahendItemCount = x_dataset.getItemCount(1); double l_subtrahendFirst = x_dataset.getXValue(1, 0); double l_subtrahendLast = x_dataset.getXValue(1, l_subtrahendItemCount - 1); return ((l_minuendLast < l_subtrahendFirst) || (l_subtrahendLast < l_minuendFirst)); } /** * Draws the visual representation of a polygon * * @param x_graphics the graphics device. * @param x_dataArea the area within which the data is being drawn. * @param x_plot the plot (can be used to obtain standard color * information etc). * @param x_domainAxis the domain (horizontal) axis. * @param x_rangeAxis the range (vertical) axis. * @param x_positive indicates if the polygon is positive (true) or * negative (false). * @param x_xValues a linked list of the x values (expects values to be * of type Double). * @param x_yValues a linked list of the y values (expects values to be * of type Double). */ private void createPolygon (Graphics2D x_graphics, Rectangle2D x_dataArea, XYPlot x_plot, ValueAxis x_domainAxis, ValueAxis x_rangeAxis, boolean x_positive, LinkedList x_xValues, LinkedList x_yValues) { PlotOrientation l_orientation = x_plot.getOrientation(); RectangleEdge l_domainAxisLocation = x_plot.getDomainAxisEdge(); RectangleEdge l_rangeAxisLocation = x_plot.getRangeAxisEdge(); Object[] l_xValues = x_xValues.toArray(); Object[] l_yValues = x_yValues.toArray(); GeneralPath l_path = new GeneralPath(); if (PlotOrientation.VERTICAL == l_orientation) { double l_x = x_domainAxis.valueToJava2D((Double) l_xValues[0], x_dataArea, l_domainAxisLocation); if (this.roundXCoordinates) { l_x = Math.rint(l_x); } double l_y = x_rangeAxis.valueToJava2D((Double) l_yValues[0], x_dataArea, l_rangeAxisLocation); l_path.moveTo((float) l_x, (float) l_y); for (int i = 1; i < l_xValues.length; i++) { l_x = x_domainAxis.valueToJava2D((Double) l_xValues[i], x_dataArea, l_domainAxisLocation); if (this.roundXCoordinates) { l_x = Math.rint(l_x); } l_y = x_rangeAxis.valueToJava2D((Double) l_yValues[i], x_dataArea, l_rangeAxisLocation); l_path.lineTo((float) l_x, (float) l_y); } l_path.closePath(); } else { double l_x = x_domainAxis.valueToJava2D((Double) l_xValues[0], x_dataArea, l_domainAxisLocation); if (this.roundXCoordinates) { l_x = Math.rint(l_x); } double l_y = x_rangeAxis.valueToJava2D((Double) l_yValues[0], x_dataArea, l_rangeAxisLocation); l_path.moveTo((float) l_y, (float) l_x); for (int i = 1; i < l_xValues.length; i++) { l_x = x_domainAxis.valueToJava2D((Double) l_xValues[i], x_dataArea, l_domainAxisLocation); if (this.roundXCoordinates) { l_x = Math.rint(l_x); } l_y = x_rangeAxis.valueToJava2D((Double) l_yValues[i], x_dataArea, l_rangeAxisLocation); l_path.lineTo((float) l_y, (float) l_x); } l_path.closePath(); } if (l_path.intersects(x_dataArea)) { x_graphics.setPaint(x_positive ? getPositivePaint() : getNegativePaint()); x_graphics.fill(l_path); } } /** * Returns a default legend item for the specified series. Subclasses * should override this method to generate customised items. * * @param datasetIndex the dataset index (zero-based). * @param series the series index (zero-based). * * @return A legend item for the series. */ @Override public LegendItem getLegendItem(int datasetIndex, int series) { LegendItem result = null; XYPlot p = getPlot(); if (p != null) { XYDataset dataset = p.getDataset(datasetIndex); if (dataset != null) { if (getItemVisible(series, 0)) { String label = getLegendItemLabelGenerator().generateLabel( dataset, series); String description = label; String toolTipText = null; if (getLegendItemToolTipGenerator() != null) { toolTipText = getLegendItemToolTipGenerator().generateLabel( dataset, series); } String urlText = null; if (getLegendItemURLGenerator() != null) { urlText = getLegendItemURLGenerator().generateLabel( dataset, series); } Paint paint = lookupSeriesPaint(series); Stroke stroke = lookupSeriesStroke(series); Shape line = getLegendLine(); result = new LegendItem(label, description, toolTipText, urlText, line, stroke, paint); result.setLabelFont(lookupLegendTextFont(series)); Paint labelPaint = lookupLegendTextPaint(series); if (labelPaint != null) { result.setLabelPaint(labelPaint); } result.setDataset(dataset); result.setDatasetIndex(datasetIndex); result.setSeriesKey(dataset.getSeriesKey(series)); result.setSeriesIndex(series); } } } return result; } /** * Tests this renderer for equality with an arbitrary object. * * @param obj the object (<code>null</code> permitted). * * @return A boolean. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof XYDifferenceRenderer)) { return false; } if (!super.equals(obj)) { return false; } XYDifferenceRenderer that = (XYDifferenceRenderer) obj; if (!PaintUtilities.equal(this.positivePaint, that.positivePaint)) { return false; } if (!PaintUtilities.equal(this.negativePaint, that.negativePaint)) { return false; } if (this.shapesVisible != that.shapesVisible) { return false; } if (!ShapeUtilities.equal(this.legendLine, that.legendLine)) { return false; } if (this.roundXCoordinates != that.roundXCoordinates) { return false; } return true; } /** * Returns a clone of the renderer. * * @return A clone. * * @throws CloneNotSupportedException if the renderer cannot be cloned. */ @Override public Object clone() throws CloneNotSupportedException { XYDifferenceRenderer clone = (XYDifferenceRenderer) super.clone(); clone.legendLine = ShapeUtilities.clone(this.legendLine); return clone; } /** * Provides serialization support. * * @param stream the output stream. * * @throws IOException if there is an I/O error. */ private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); SerialUtilities.writePaint(this.positivePaint, stream); SerialUtilities.writePaint(this.negativePaint, stream); SerialUtilities.writeShape(this.legendLine, stream); } /** * Provides serialization support. * * @param stream the input stream. * * @throws IOException if there is an I/O error. * @throws ClassNotFoundException if there is a classpath problem. */ private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); this.positivePaint = SerialUtilities.readPaint(stream); this.negativePaint = SerialUtilities.readPaint(stream); this.legendLine = SerialUtilities.readShape(stream); } }
48,534
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
AbstractXYItemRenderer.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/renderer/xy/AbstractXYItemRenderer.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2014, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * --------------------------- * AbstractXYItemRenderer.java * --------------------------- * (C) Copyright 2002-2014, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): Richard Atkinson; * Focus Computer Services Limited; * Tim Bardzil; * Sergei Ivanov; * Peter Kolb (patch 2809117); * Martin Krauskopf; * * Changes: * -------- * 15-Mar-2002 : Version 1 (DG); * 09-Apr-2002 : Added a getToolTipGenerator() method reflecting the change in * the XYItemRenderer interface (DG); * 05-Aug-2002 : Added a urlGenerator member variable to support HTML image * maps (RA); * 20-Aug-2002 : Added property change events for the tooltip and URL * generators (DG); * 22-Aug-2002 : Moved property change support into AbstractRenderer class (DG); * 23-Sep-2002 : Fixed errors reported by Checkstyle tool (DG); * 18-Nov-2002 : Added methods for drawing grid lines (DG); * 17-Jan-2003 : Moved plot classes into a separate package (DG); * 25-Mar-2003 : Implemented Serializable (DG); * 01-May-2003 : Modified initialise() return type and drawItem() method * signature (DG); * 15-May-2003 : Modified to take into account the plot orientation (DG); * 21-May-2003 : Added labels to markers (DG); * 05-Jun-2003 : Added domain and range grid bands (sponsored by Focus Computer * Services Ltd) (DG); * 27-Jul-2003 : Added getRangeType() to support stacked XY area charts (RA); * 31-Jul-2003 : Deprecated all but the default constructor (DG); * 13-Aug-2003 : Implemented Cloneable (DG); * 16-Sep-2003 : Changed ChartRenderingInfo --> PlotRenderingInfo (DG); * 29-Oct-2003 : Added workaround for font alignment in PDF output (DG); * 05-Nov-2003 : Fixed marker rendering bug (833623) (DG); * 11-Feb-2004 : Updated labelling for markers (DG); * 25-Feb-2004 : Added updateCrosshairValues() method. Moved deprecated code * to bottom of source file (DG); * 16-Apr-2004 : Added support for IntervalMarker in drawRangeMarker() method * - thanks to Tim Bardzil (DG); * 05-May-2004 : Fixed bug (948310) where interval markers extend beyond axis * range (DG); * 03-Jun-2004 : Fixed more bugs in drawing interval markers (DG); * 26-Aug-2004 : Added the addEntity() method (DG); * 29-Sep-2004 : Added annotation support (with layers) (DG); * 30-Sep-2004 : Moved drawRotatedString() from RefineryUtilities --> * TextUtilities (DG); * 06-Oct-2004 : Added findDomainBounds() method and renamed * getRangeExtent() --> findRangeBounds() (DG); * 07-Jan-2005 : Removed deprecated code (DG); * 27-Jan-2005 : Modified getLegendItem() to omit hidden series (DG); * 24-Feb-2005 : Added getLegendItems() method (DG); * 08-Mar-2005 : Fixed positioning of marker labels (DG); * 20-Apr-2005 : Renamed XYLabelGenerator --> XYItemLabelGenerator and * added generators for legend labels, tooltips and URLs (DG); * 01-Jun-2005 : Handle one dimension of the marker label adjustment * automatically (DG); * ------------- JFREECHART 1.0.x --------------------------------------------- * 20-Jul-2006 : Set dataset and series indices in LegendItem (DG); * 24-Oct-2006 : Respect alpha setting in markers (see patch 1567843 by Sergei * Ivanov) (DG); * 24-Oct-2006 : Added code to draw outlines for interval markers (DG); * 24-Nov-2006 : Fixed cloning for legend item generators (DG); * 06-Feb-2007 : Added new updateCrosshairValues() method that takes into * account multiple axis plots (see bug 1086307) (DG); * 20-Feb-2007 : Fixed equals() method implementation (DG); * 01-Mar-2007 : Fixed interval marker drawing (patch 1670686 thanks to * Sergei Ivanov) (DG); * 22-Mar-2007 : Modified the tool tip generator look up (DG); * 23-Mar-2007 : Added drawDomainLine() method (DG); * 20-Apr-2007 : Updated getLegendItem() for renderer change, and deprecated * itemLabelGenerator and toolTipGenerator override fields (DG); * 18-May-2007 : Set dataset and seriesKey for LegendItem (DG); * 12-Nov-2007 : Fixed domain and range band drawing methods (DG); * 07-Apr-2008 : Minor API doc update (DG); * 14-May-2008 : Updated addEntity() method to take plot orientation into * account when the incoming area is null (DG); * 02-Jun-2008 : Added isPointInRect() method (DG); * 17-Jun-2008 : Apply legend shape, font and paint attributes (DG); * 09-Mar-2009 : Added getAnnotations() method (DG); * 27-Mar-2009 : Added new findDomainBounds() and findRangeBounds() methods to * take account of hidden series (DG); * 01-Apr-2009 : Moved defaultEntityRadius up to superclass (DG); * 28-Apr-2009 : Updated getLegendItem() method to observe new * 'treatLegendShapeAsLine' flag (DG); * 24-Jun-2009 : Added support for annotation events - see patch 2809117 * by PK (DG); * 01-Sep-2009 : Bug 2840132 - set renderer index when drawing * annotations (DG); * 06-Oct-2011 : Add utility methods to work with 1.4 API in GeneralPath (MK); * 16-Jun-2012 : Removed JCommon dependencies (DG); * 10-Mar-2014 : Remove LegendItemCollection (DG); * */ package org.jfree.chart.renderer.xy; import java.awt.AlphaComposite; import java.awt.Composite; import java.awt.Font; import java.awt.GradientPaint; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.Shape; import java.awt.Stroke; import java.awt.geom.Ellipse2D; import java.awt.geom.GeneralPath; import java.awt.geom.Line2D; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import org.jfree.chart.LegendItem; import org.jfree.chart.annotations.Annotation; import org.jfree.chart.annotations.XYAnnotation; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.ui.GradientPaintTransformer; import org.jfree.chart.ui.Layer; import org.jfree.chart.ui.LengthAdjustmentType; import org.jfree.chart.ui.RectangleAnchor; import org.jfree.chart.ui.RectangleInsets; import org.jfree.chart.util.ObjectList; import org.jfree.chart.util.ObjectUtilities; import org.jfree.chart.util.PublicCloneable; import org.jfree.chart.entity.EntityCollection; import org.jfree.chart.entity.XYItemEntity; import org.jfree.chart.event.AnnotationChangeEvent; import org.jfree.chart.event.AnnotationChangeListener; import org.jfree.chart.event.RendererChangeEvent; import org.jfree.chart.labels.ItemLabelPosition; import org.jfree.chart.labels.StandardXYSeriesLabelGenerator; import org.jfree.chart.labels.XYItemLabelGenerator; import org.jfree.chart.labels.XYSeriesLabelGenerator; import org.jfree.chart.labels.XYToolTipGenerator; import org.jfree.chart.plot.CrosshairState; import org.jfree.chart.plot.DrawingSupplier; import org.jfree.chart.plot.IntervalMarker; import org.jfree.chart.plot.Marker; import org.jfree.chart.plot.Plot; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.PlotRenderingInfo; import org.jfree.chart.plot.ValueMarker; import org.jfree.chart.plot.XYPlot; import org.jfree.chart.renderer.AbstractRenderer; import org.jfree.chart.text.TextUtilities; import org.jfree.chart.urls.XYURLGenerator; import org.jfree.chart.util.ParamChecks; import org.jfree.data.Range; import org.jfree.data.general.DatasetUtilities; import org.jfree.data.xy.XYDataset; /** * A base class that can be used to create new {@link XYItemRenderer} * implementations. */ public abstract class AbstractXYItemRenderer extends AbstractRenderer implements XYItemRenderer, AnnotationChangeListener, Cloneable, Serializable { /** For serialization. */ private static final long serialVersionUID = 8019124836026607990L; /** The plot. */ private XYPlot plot; /** A list of item label generators (one per series). */ private ObjectList<XYItemLabelGenerator> itemLabelGeneratorList; /** The base item label generator. */ private XYItemLabelGenerator baseItemLabelGenerator; /** A list of tool tip generators (one per series). */ private ObjectList<XYToolTipGenerator> toolTipGeneratorList; /** The base tool tip generator. */ private XYToolTipGenerator baseToolTipGenerator; /** The URL text generator. */ private XYURLGenerator urlGenerator; /** * Annotations to be drawn in the background layer ('underneath' the data * items). */ private List<XYAnnotation> backgroundAnnotations; /** * Annotations to be drawn in the foreground layer ('on top' of the data * items). */ private List<XYAnnotation> foregroundAnnotations; /** The legend item label generator. */ private XYSeriesLabelGenerator legendItemLabelGenerator; /** The legend item tool tip generator. */ private XYSeriesLabelGenerator legendItemToolTipGenerator; /** The legend item URL generator. */ private XYSeriesLabelGenerator legendItemURLGenerator; /** * Creates a renderer where the tooltip generator and the URL generator are * both <code>null</code>. */ protected AbstractXYItemRenderer() { super(); this.itemLabelGeneratorList = new ObjectList<XYItemLabelGenerator>(); this.toolTipGeneratorList = new ObjectList<XYToolTipGenerator>(); this.urlGenerator = null; this.backgroundAnnotations = new java.util.ArrayList<XYAnnotation>(); this.foregroundAnnotations = new java.util.ArrayList<XYAnnotation>(); this.legendItemLabelGenerator = new StandardXYSeriesLabelGenerator( "{0}"); } /** * Returns the number of passes through the data that the renderer requires * in order to draw the chart. Most charts will require a single pass, but * some require two passes. * * @return The pass count. */ @Override public int getPassCount() { return 1; } /** * Returns the plot that the renderer is assigned to. * * @return The plot (possibly <code>null</code>). */ @Override public XYPlot getPlot() { return this.plot; } /** * Sets the plot that the renderer is assigned to. * * @param plot the plot (<code>null</code> permitted). */ @Override public void setPlot(XYPlot plot) { this.plot = plot; } /** * Initialises the renderer and returns a state object that should be * passed to all subsequent calls to the drawItem() method. * <P> * This method will be called before the first item is rendered, giving the * renderer an opportunity to initialise any state information it wants to * maintain. The renderer can do nothing if it chooses. * * @param g2 the graphics device. * @param dataArea the area inside the axes. * @param plot the plot. * @param data the data. * @param info an optional info collection object to return data back to * the caller. * * @return The renderer state (never <code>null</code>). */ @Override public XYItemRendererState initialise(Graphics2D g2, Rectangle2D dataArea, XYPlot plot, XYDataset data, PlotRenderingInfo info) { return new XYItemRendererState(info); } // ITEM LABEL GENERATOR /** * Returns the label generator for a data item. This implementation simply * passes control to the {@link #getSeriesItemLabelGenerator(int)} method. * If, for some reason, you want a different generator for individual * items, you can override this method. * * @param series the series index (zero based). * @param item the item index (zero based). * * @return The generator (possibly <code>null</code>). */ @Override public XYItemLabelGenerator getItemLabelGenerator(int series, int item) { XYItemLabelGenerator generator = this.itemLabelGeneratorList.get(series); if (generator == null) { generator = this.baseItemLabelGenerator; } return generator; } /** * Returns the item label generator for a series. * * @param series the series index (zero based). * * @return The generator (possibly <code>null</code>). */ @Override public XYItemLabelGenerator getSeriesItemLabelGenerator(int series) { return this.itemLabelGeneratorList.get(series); } /** * Sets the item label generator for a series and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param series the series index (zero based). * @param generator the generator (<code>null</code> permitted). */ @Override public void setSeriesItemLabelGenerator(int series, XYItemLabelGenerator generator) { setSeriesItemLabelGenerator(series, generator, true); } /** * Sets the item label generator for a series and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param series the series index (zero based). * @param generator the generator (<code>null</code> permitted). * @param notify notify listeners? */ @Override public void setSeriesItemLabelGenerator(int series, XYItemLabelGenerator generator, boolean notify) { this.itemLabelGeneratorList.set(series, generator); if (notify) { fireChangeEvent(); } } /** * Returns the default item label generator. * * @return The default item label generator (possibly <code>null</code>). */ @Override public XYItemLabelGenerator getDefaultItemLabelGenerator() { return this.baseItemLabelGenerator; } /** * Sets the default item label generator and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param generator the generator (<code>null</code> permitted). */ @Override public void setDefaultItemLabelGenerator(XYItemLabelGenerator generator) { setDefaultItemLabelGenerator(generator, true); } /** * Sets the default item label generator and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param generator the generator (<code>null</code> permitted). * @param notify notify listeners? */ @Override public void setDefaultItemLabelGenerator(XYItemLabelGenerator generator, boolean notify) { this.baseItemLabelGenerator = generator; if (notify) { fireChangeEvent(); } } // TOOL TIP GENERATOR /** * Returns the tool tip generator for a data item. If, for some reason, * you want a different generator for individual items, you can override * this method. * * @param series the series index (zero based). * @param item the item index (zero based). * * @return The generator (possibly <code>null</code>). */ @Override public XYToolTipGenerator getToolTipGenerator(int series, int item) { XYToolTipGenerator generator = this.toolTipGeneratorList.get(series); if (generator == null) { generator = this.baseToolTipGenerator; } return generator; } /** * Returns the tool tip generator for a series. * * @param series the series index (zero based). * * @return The generator (possibly <code>null</code>). */ @Override public XYToolTipGenerator getSeriesToolTipGenerator(int series) { return this.toolTipGeneratorList.get(series); } /** * Sets the tool tip generator for a series and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param series the series index (zero based). * @param generator the generator (<code>null</code> permitted). */ @Override public void setSeriesToolTipGenerator(int series, XYToolTipGenerator generator) { setSeriesToolTipGenerator(series, generator, true); } /** * Sets the tool tip generator for a series and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param series the series index (zero based). * @param generator the generator (<code>null</code> permitted). * @param notify notify listeners? */ @Override public void setSeriesToolTipGenerator(int series, XYToolTipGenerator generator, boolean notify) { this.toolTipGeneratorList.set(series, generator); if (notify) { fireChangeEvent(); } } /** * Returns the default tool tip generator. * * @return The default tool tip generator (possibly <code>null</code>). * * @see #setDefaultToolTipGenerator(XYToolTipGenerator) */ @Override public XYToolTipGenerator getDefaultToolTipGenerator() { return this.baseToolTipGenerator; } /** * Sets the default tool tip generator and sends a {@link RendererChangeEvent} * to all registered listeners. * * @param generator the generator (<code>null</code> permitted). * * @see #getDefaultToolTipGenerator() */ @Override public void setDefaultToolTipGenerator(XYToolTipGenerator generator) { setDefaultToolTipGenerator(generator, true); } /** * Sets the base tool tip generator and sends a {@link RendererChangeEvent} * to all registered listeners. * * @param generator the generator (<code>null</code> permitted). * @param notify notify listeners? * * @see #getBaseToolTipGenerator() */ @Override public void setDefaultToolTipGenerator(XYToolTipGenerator generator, boolean notify) { this.baseToolTipGenerator = generator; if (notify) { fireChangeEvent(); } } // URL GENERATOR /** * Returns the URL generator for HTML image maps. * * @return The URL generator (possibly <code>null</code>). */ @Override public XYURLGenerator getURLGenerator() { return this.urlGenerator; } /** * Sets the URL generator for HTML image maps and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param urlGenerator the URL generator (<code>null</code> permitted). */ @Override public void setURLGenerator(XYURLGenerator urlGenerator) { setURLGenerator(urlGenerator, true); } /** * Sets the URL generator for HTML image maps and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param urlGenerator the URL generator (<code>null</code> permitted). * @param notify notify listeners? */ @Override public void setURLGenerator(XYURLGenerator urlGenerator, boolean notify) { this.urlGenerator = urlGenerator; if (notify) { fireChangeEvent(); } } /** * Adds an annotation and sends a {@link RendererChangeEvent} to all * registered listeners. The annotation is added to the foreground * layer. * * @param annotation the annotation (<code>null</code> not permitted). */ @Override public void addAnnotation(XYAnnotation annotation) { // defer argument checking addAnnotation(annotation, Layer.FOREGROUND); } /** * Adds an annotation to the specified layer and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param annotation the annotation (<code>null</code> not permitted). * @param layer the layer (<code>null</code> not permitted). */ @Override public void addAnnotation(XYAnnotation annotation, Layer layer) { ParamChecks.nullNotPermitted(annotation, "annotation"); if (layer.equals(Layer.FOREGROUND)) { this.foregroundAnnotations.add(annotation); annotation.addChangeListener(this); fireChangeEvent(); } else if (layer.equals(Layer.BACKGROUND)) { this.backgroundAnnotations.add(annotation); annotation.addChangeListener(this); fireChangeEvent(); } else { // should never get here throw new RuntimeException("Unknown layer."); } } /** * Removes the specified annotation and sends a {@link RendererChangeEvent} * to all registered listeners. * * @param annotation the annotation to remove (<code>null</code> not * permitted). * * @return A boolean to indicate whether or not the annotation was * successfully removed. */ @Override public boolean removeAnnotation(XYAnnotation annotation) { boolean removed = this.foregroundAnnotations.remove(annotation); removed = removed & this.backgroundAnnotations.remove(annotation); annotation.removeChangeListener(this); fireChangeEvent(); return removed; } /** * Removes all annotations and sends a {@link RendererChangeEvent} * to all registered listeners. */ @Override public void removeAnnotations() { for (XYAnnotation annotation : this.foregroundAnnotations) { annotation.removeChangeListener(this); } for (XYAnnotation annotation : this.backgroundAnnotations) { annotation.removeChangeListener(this); } this.foregroundAnnotations.clear(); this.backgroundAnnotations.clear(); fireChangeEvent(); } /** * Receives notification of a change to an {@link Annotation} added to * this renderer. * * @param event information about the event (not used here). * * @since 1.0.14 */ @Override public void annotationChanged(AnnotationChangeEvent event) { fireChangeEvent(); } /** * Returns a collection of the annotations that are assigned to the * renderer. * * @return A collection of annotations (possibly empty but never * <code>null</code>). * * @since 1.0.13 */ @Override public Collection<XYAnnotation> getAnnotations() { List<XYAnnotation> result = new java.util.ArrayList<XYAnnotation>( this.foregroundAnnotations); result.addAll(this.backgroundAnnotations); return result; } /** * Returns the legend item label generator. * * @return The label generator (never <code>null</code>). * * @see #setLegendItemLabelGenerator(XYSeriesLabelGenerator) */ @Override public XYSeriesLabelGenerator getLegendItemLabelGenerator() { return this.legendItemLabelGenerator; } /** * Sets the legend item label generator and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param generator the generator (<code>null</code> not permitted). * * @see #getLegendItemLabelGenerator() */ @Override public void setLegendItemLabelGenerator(XYSeriesLabelGenerator generator) { setLegendItemLabelGenerator(generator, true); } /** * Sets the legend item label generator and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param generator the generator (<code>null</code> not permitted). * @param notify notify listeners? * * @see #getLegendItemLabelGenerator() */ @Override public void setLegendItemLabelGenerator(XYSeriesLabelGenerator generator, boolean notify) { ParamChecks.nullNotPermitted(generator, "generator"); this.legendItemLabelGenerator = generator; if (notify) { fireChangeEvent(); } } /** * Returns the legend item tool tip generator. * * @return The tool tip generator (possibly <code>null</code>). * * @see #setLegendItemToolTipGenerator(XYSeriesLabelGenerator) */ public XYSeriesLabelGenerator getLegendItemToolTipGenerator() { return this.legendItemToolTipGenerator; } /** * Sets the legend item tool tip generator and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param generator the generator (<code>null</code> permitted). * * @see #getLegendItemToolTipGenerator() */ public void setLegendItemToolTipGenerator( XYSeriesLabelGenerator generator) { this.legendItemToolTipGenerator = generator; fireChangeEvent(); } /** * Returns the legend item URL generator. * * @return The URL generator (possibly <code>null</code>). * * @see #setLegendItemURLGenerator(XYSeriesLabelGenerator) */ public XYSeriesLabelGenerator getLegendItemURLGenerator() { return this.legendItemURLGenerator; } /** * Sets the legend item URL generator and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param generator the generator (<code>null</code> permitted). * * @see #getLegendItemURLGenerator() */ public void setLegendItemURLGenerator(XYSeriesLabelGenerator generator) { this.legendItemURLGenerator = generator; fireChangeEvent(); } /** * Returns the lower and upper bounds (range) of the x-values in the * specified dataset. * * @param dataset the dataset (<code>null</code> permitted). * * @return The range (<code>null</code> if the dataset is <code>null</code> * or empty). * * @see #findRangeBounds(XYDataset) */ @Override public Range findDomainBounds(XYDataset dataset) { return findDomainBounds(dataset, false); } /** * Returns the lower and upper bounds (range) of the x-values in the * specified dataset. * * @param dataset the dataset (<code>null</code> permitted). * @param includeInterval include the interval (if any) for the dataset? * * @return The range (<code>null</code> if the dataset is <code>null</code> * or empty). * * @since 1.0.13 */ protected Range findDomainBounds(XYDataset dataset, boolean includeInterval) { if (dataset == null) { return null; } if (getDataBoundsIncludesVisibleSeriesOnly()) { List<Comparable> visibleSeriesKeys = new ArrayList<Comparable>(); int seriesCount = dataset.getSeriesCount(); for (int s = 0; s < seriesCount; s++) { if (isSeriesVisible(s)) { visibleSeriesKeys.add(dataset.getSeriesKey(s)); } } return DatasetUtilities.findDomainBounds(dataset, visibleSeriesKeys, includeInterval); } return DatasetUtilities.findDomainBounds(dataset, includeInterval); } /** * Returns the range of values the renderer requires to display all the * items from the specified dataset. * * @param dataset the dataset (<code>null</code> permitted). * * @return The range (<code>null</code> if the dataset is <code>null</code> * or empty). * * @see #findDomainBounds(XYDataset) */ @Override public Range findRangeBounds(XYDataset dataset) { return findRangeBounds(dataset, false); } /** * Returns the range of values the renderer requires to display all the * items from the specified dataset. * * @param dataset the dataset (<code>null</code> permitted). * @param includeInterval include the interval (if any) for the dataset? * * @return The range (<code>null</code> if the dataset is <code>null</code> * or empty). * * @since 1.0.13 */ protected Range findRangeBounds(XYDataset dataset, boolean includeInterval) { if (dataset == null) { return null; } if (getDataBoundsIncludesVisibleSeriesOnly()) { List<Comparable> visibleSeriesKeys = new ArrayList<Comparable>(); int seriesCount = dataset.getSeriesCount(); for (int s = 0; s < seriesCount; s++) { if (isSeriesVisible(s)) { visibleSeriesKeys.add(dataset.getSeriesKey(s)); } } // the bounds should be calculated using just the items within // the current range of the x-axis...if there is one Range xRange = null; XYPlot p = getPlot(); if (p != null) { ValueAxis xAxis = null; int index = p.getIndexOf(this); if (index >= 0) { xAxis = this.plot.getDomainAxisForDataset(index); } if (xAxis != null) { xRange = xAxis.getRange(); } } if (xRange == null) { xRange = new Range(Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY); } return DatasetUtilities.findRangeBounds(dataset, visibleSeriesKeys, xRange, includeInterval); } return DatasetUtilities.findRangeBounds(dataset, includeInterval); } /** * Returns a (possibly empty) collection of legend items for the series * that this renderer is responsible for drawing. * * @return The legend item collection (never <code>null</code>). */ @Override public List<LegendItem> getLegendItems() { if (this.plot == null) { return new ArrayList<LegendItem>(); } List<LegendItem> result = new ArrayList<LegendItem>(); int index = this.plot.getIndexOf(this); XYDataset dataset = this.plot.getDataset(index); if (dataset != null) { int seriesCount = dataset.getSeriesCount(); for (int i = 0; i < seriesCount; i++) { if (isSeriesVisibleInLegend(i)) { LegendItem item = getLegendItem(index, i); if (item != null) { result.add(item); } } } } return result; } /** * Returns a default legend item for the specified series. Subclasses * should override this method to generate customised items. * * @param datasetIndex the dataset index (zero-based). * @param series the series index (zero-based). * * @return A legend item for the series. */ @Override public LegendItem getLegendItem(int datasetIndex, int series) { XYPlot xyplot = getPlot(); if (xyplot == null) { return null; } XYDataset dataset = xyplot.getDataset(datasetIndex); if (dataset == null) { return null; } String label = this.legendItemLabelGenerator.generateLabel(dataset, series); String toolTipText = null; if (getLegendItemToolTipGenerator() != null) { toolTipText = getLegendItemToolTipGenerator().generateLabel( dataset, series); } String urlText = null; if (getLegendItemURLGenerator() != null) { urlText = getLegendItemURLGenerator().generateLabel(dataset, series); } Shape shape = lookupLegendShape(series); Paint paint = lookupSeriesPaint(series); LegendItem item = new LegendItem(label, paint); item.setToolTipText(toolTipText); item.setURLText(urlText); item.setLabelFont(lookupLegendTextFont(series)); Paint labelPaint = lookupLegendTextPaint(series); if (labelPaint != null) { item.setLabelPaint(labelPaint); } item.setSeriesKey(dataset.getSeriesKey(series)); item.setSeriesIndex(series); item.setDataset(dataset); item.setDatasetIndex(datasetIndex); if (getTreatLegendShapeAsLine()) { item.setLineVisible(true); item.setLine(shape); item.setLinePaint(paint); item.setShapeVisible(false); } else { Paint outlinePaint = lookupSeriesOutlinePaint(series); Stroke outlineStroke = lookupSeriesOutlineStroke(series); item.setOutlinePaint(outlinePaint); item.setOutlineStroke(outlineStroke); } return item; } /** * Fills a band between two values on the axis. This can be used to color * bands between the grid lines. * * @param g2 the graphics device. * @param plot the plot. * @param axis the domain axis. * @param dataArea the data area. * @param start the start value. * @param end the end value. */ @Override public void fillDomainGridBand(Graphics2D g2, XYPlot plot, ValueAxis axis, Rectangle2D dataArea, double start, double end) { double x1 = axis.valueToJava2D(start, dataArea, plot.getDomainAxisEdge()); double x2 = axis.valueToJava2D(end, dataArea, plot.getDomainAxisEdge()); Rectangle2D band; if (plot.getOrientation() == PlotOrientation.VERTICAL) { band = new Rectangle2D.Double(Math.min(x1, x2), dataArea.getMinY(), Math.abs(x2 - x1), dataArea.getHeight()); } else { band = new Rectangle2D.Double(dataArea.getMinX(), Math.min(x1, x2), dataArea.getWidth(), Math.abs(x2 - x1)); } Paint paint = plot.getDomainTickBandPaint(); if (paint != null) { g2.setPaint(paint); g2.fill(band); } } /** * Fills a band between two values on the range axis. This can be used to * color bands between the grid lines. * * @param g2 the graphics device. * @param plot the plot. * @param axis the range axis. * @param dataArea the data area. * @param start the start value. * @param end the end value. */ @Override public void fillRangeGridBand(Graphics2D g2, XYPlot plot, ValueAxis axis, Rectangle2D dataArea, double start, double end) { double y1 = axis.valueToJava2D(start, dataArea, plot.getRangeAxisEdge()); double y2 = axis.valueToJava2D(end, dataArea, plot.getRangeAxisEdge()); Rectangle2D band; if (plot.getOrientation() == PlotOrientation.VERTICAL) { band = new Rectangle2D.Double(dataArea.getMinX(), Math.min(y1, y2), dataArea.getWidth(), Math.abs(y2 - y1)); } else { band = new Rectangle2D.Double(Math.min(y1, y2), dataArea.getMinY(), Math.abs(y2 - y1), dataArea.getHeight()); } Paint paint = plot.getRangeTickBandPaint(); if (paint != null) { g2.setPaint(paint); g2.fill(band); } } /** * Draws a grid line against the range axis. * * @param g2 the graphics device. * @param plot the plot. * @param axis the value axis. * @param dataArea the area for plotting data (not yet adjusted for any * 3D effect). * @param value the value at which the grid line should be drawn. */ @Override public void drawDomainGridline(Graphics2D g2, XYPlot plot, ValueAxis axis, Rectangle2D dataArea, double value) { Range range = axis.getRange(); if (!range.contains(value)) { return; } PlotOrientation orientation = plot.getOrientation(); double v = axis.valueToJava2D(value, dataArea, plot.getDomainAxisEdge()); Line2D line = null; if (orientation == PlotOrientation.HORIZONTAL) { line = new Line2D.Double(dataArea.getMinX(), v, dataArea.getMaxX(), v); } else if (orientation == PlotOrientation.VERTICAL) { line = new Line2D.Double(v, dataArea.getMinY(), v, dataArea.getMaxY()); } Paint paint = plot.getDomainGridlinePaint(); Stroke stroke = plot.getDomainGridlineStroke(); g2.setPaint(paint != null ? paint : Plot.DEFAULT_OUTLINE_PAINT); g2.setStroke(stroke != null ? stroke : Plot.DEFAULT_OUTLINE_STROKE); g2.draw(line); } /** * Draws a line perpendicular to the domain axis. * * @param g2 the graphics device. * @param plot the plot. * @param axis the value axis. * @param dataArea the area for plotting data (not yet adjusted for any 3D * effect). * @param value the value at which the grid line should be drawn. * @param paint the paint (<code>null</code> not permitted). * @param stroke the stroke (<code>null</code> not permitted). * * @since 1.0.5 */ public void drawDomainLine(Graphics2D g2, XYPlot plot, ValueAxis axis, Rectangle2D dataArea, double value, Paint paint, Stroke stroke) { Range range = axis.getRange(); if (!range.contains(value)) { return; } PlotOrientation orientation = plot.getOrientation(); Line2D line = null; double v = axis.valueToJava2D(value, dataArea, plot.getDomainAxisEdge()); if (orientation == PlotOrientation.HORIZONTAL) { line = new Line2D.Double(dataArea.getMinX(), v, dataArea.getMaxX(), v); } else if (orientation == PlotOrientation.VERTICAL) { line = new Line2D.Double(v, dataArea.getMinY(), v, dataArea.getMaxY()); } g2.setPaint(paint); g2.setStroke(stroke); g2.draw(line); } /** * Draws a line perpendicular to the range axis. * * @param g2 the graphics device. * @param plot the plot. * @param axis the value axis. * @param dataArea the area for plotting data (not yet adjusted for any 3D * effect). * @param value the value at which the grid line should be drawn. * @param paint the paint. * @param stroke the stroke. */ @Override public void drawRangeGridline(Graphics2D g2, XYPlot plot, ValueAxis axis, Rectangle2D dataArea, double value, Paint paint, Stroke stroke) { Range range = axis.getRange(); if (!range.contains(value)) { return; } PlotOrientation orientation = plot.getOrientation(); Line2D line = null; double v = axis.valueToJava2D(value, dataArea, plot.getRangeAxisEdge()); if (orientation == PlotOrientation.HORIZONTAL) { line = new Line2D.Double(v, dataArea.getMinY(), v, dataArea.getMaxY()); } else if (orientation == PlotOrientation.VERTICAL) { line = new Line2D.Double(dataArea.getMinX(), v, dataArea.getMaxX(), v); } g2.setPaint(paint); g2.setStroke(stroke); g2.draw(line); } /** * Draws a vertical line on the chart to represent a 'range marker'. * * @param g2 the graphics device. * @param plot the plot. * @param domainAxis the domain axis. * @param marker the marker line. * @param dataArea the axis data area. */ @Override public void drawDomainMarker(Graphics2D g2, XYPlot plot, ValueAxis domainAxis, Marker marker, Rectangle2D dataArea) { if (marker instanceof ValueMarker) { ValueMarker vm = (ValueMarker) marker; double value = vm.getValue(); Range range = domainAxis.getRange(); if (!range.contains(value)) { return; } double v = domainAxis.valueToJava2D(value, dataArea, plot.getDomainAxisEdge()); PlotOrientation orientation = plot.getOrientation(); Line2D line = null; if (orientation == PlotOrientation.HORIZONTAL) { line = new Line2D.Double(dataArea.getMinX(), v, dataArea.getMaxX(), v); } else if (orientation == PlotOrientation.VERTICAL) { line = new Line2D.Double(v, dataArea.getMinY(), v, dataArea.getMaxY()); } else { throw new IllegalStateException(); } final Composite originalComposite = g2.getComposite(); g2.setComposite(AlphaComposite.getInstance( AlphaComposite.SRC_OVER, marker.getAlpha())); g2.setPaint(marker.getPaint()); g2.setStroke(marker.getStroke()); g2.draw(line); String label = marker.getLabel(); RectangleAnchor anchor = marker.getLabelAnchor(); if (label != null) { Font labelFont = marker.getLabelFont(); g2.setFont(labelFont); g2.setPaint(marker.getLabelPaint()); Point2D coordinates = calculateDomainMarkerTextAnchorPoint( g2, orientation, dataArea, line.getBounds2D(), marker.getLabelOffset(), LengthAdjustmentType.EXPAND, anchor); TextUtilities.drawAlignedString(label, g2, (float) coordinates.getX(), (float) coordinates.getY(), marker.getLabelTextAnchor()); } g2.setComposite(originalComposite); } else if (marker instanceof IntervalMarker) { IntervalMarker im = (IntervalMarker) marker; double start = im.getStartValue(); double end = im.getEndValue(); Range range = domainAxis.getRange(); if (!(range.intersects(start, end))) { return; } double start2d = domainAxis.valueToJava2D(start, dataArea, plot.getDomainAxisEdge()); double end2d = domainAxis.valueToJava2D(end, dataArea, plot.getDomainAxisEdge()); double low = Math.min(start2d, end2d); double high = Math.max(start2d, end2d); PlotOrientation orientation = plot.getOrientation(); Rectangle2D rect = null; if (orientation == PlotOrientation.HORIZONTAL) { // clip top and bottom bounds to data area low = Math.max(low, dataArea.getMinY()); high = Math.min(high, dataArea.getMaxY()); rect = new Rectangle2D.Double(dataArea.getMinX(), low, dataArea.getWidth(), high - low); } else if (orientation == PlotOrientation.VERTICAL) { // clip left and right bounds to data area low = Math.max(low, dataArea.getMinX()); high = Math.min(high, dataArea.getMaxX()); rect = new Rectangle2D.Double(low, dataArea.getMinY(), high - low, dataArea.getHeight()); } final Composite originalComposite = g2.getComposite(); g2.setComposite(AlphaComposite.getInstance( AlphaComposite.SRC_OVER, marker.getAlpha())); Paint p = marker.getPaint(); if (p instanceof GradientPaint) { GradientPaint gp = (GradientPaint) p; GradientPaintTransformer t = im.getGradientPaintTransformer(); if (t != null) { gp = t.transform(gp, rect); } g2.setPaint(gp); } else { g2.setPaint(p); } g2.fill(rect); // now draw the outlines, if visible... if (im.getOutlinePaint() != null && im.getOutlineStroke() != null) { if (orientation == PlotOrientation.VERTICAL) { Line2D line = new Line2D.Double(); double y0 = dataArea.getMinY(); double y1 = dataArea.getMaxY(); g2.setPaint(im.getOutlinePaint()); g2.setStroke(im.getOutlineStroke()); if (range.contains(start)) { line.setLine(start2d, y0, start2d, y1); g2.draw(line); } if (range.contains(end)) { line.setLine(end2d, y0, end2d, y1); g2.draw(line); } } else { // PlotOrientation.HORIZONTAL Line2D line = new Line2D.Double(); double x0 = dataArea.getMinX(); double x1 = dataArea.getMaxX(); g2.setPaint(im.getOutlinePaint()); g2.setStroke(im.getOutlineStroke()); if (range.contains(start)) { line.setLine(x0, start2d, x1, start2d); g2.draw(line); } if (range.contains(end)) { line.setLine(x0, end2d, x1, end2d); g2.draw(line); } } } String label = marker.getLabel(); RectangleAnchor anchor = marker.getLabelAnchor(); if (label != null) { Font labelFont = marker.getLabelFont(); g2.setFont(labelFont); g2.setPaint(marker.getLabelPaint()); Point2D coordinates = calculateDomainMarkerTextAnchorPoint( g2, orientation, dataArea, rect, marker.getLabelOffset(), marker.getLabelOffsetType(), anchor); TextUtilities.drawAlignedString(label, g2, (float) coordinates.getX(), (float) coordinates.getY(), marker.getLabelTextAnchor()); } g2.setComposite(originalComposite); } } /** * Calculates the (x, y) coordinates for drawing a marker label. * * @param g2 the graphics device. * @param orientation the plot orientation. * @param dataArea the data area. * @param markerArea the rectangle surrounding the marker area. * @param markerOffset the marker label offset. * @param labelOffsetType the label offset type. * @param anchor the label anchor. * * @return The coordinates for drawing the marker label. */ protected Point2D calculateDomainMarkerTextAnchorPoint(Graphics2D g2, PlotOrientation orientation, Rectangle2D dataArea, Rectangle2D markerArea, RectangleInsets markerOffset, LengthAdjustmentType labelOffsetType, RectangleAnchor anchor) { Rectangle2D anchorRect = null; if (orientation == PlotOrientation.HORIZONTAL) { anchorRect = markerOffset.createAdjustedRectangle(markerArea, LengthAdjustmentType.CONTRACT, labelOffsetType); } else if (orientation == PlotOrientation.VERTICAL) { anchorRect = markerOffset.createAdjustedRectangle(markerArea, labelOffsetType, LengthAdjustmentType.CONTRACT); } return RectangleAnchor.coordinates(anchorRect, anchor); } /** * Draws a horizontal line across the chart to represent a 'range marker'. * * @param g2 the graphics device. * @param plot the plot. * @param rangeAxis the range axis. * @param marker the marker line. * @param dataArea the axis data area. */ @Override public void drawRangeMarker(Graphics2D g2, XYPlot plot, ValueAxis rangeAxis, Marker marker, Rectangle2D dataArea) { if (marker instanceof ValueMarker) { ValueMarker vm = (ValueMarker) marker; double value = vm.getValue(); Range range = rangeAxis.getRange(); if (!range.contains(value)) { return; } double v = rangeAxis.valueToJava2D(value, dataArea, plot.getRangeAxisEdge()); PlotOrientation orientation = plot.getOrientation(); Line2D line; if (orientation == PlotOrientation.HORIZONTAL) { line = new Line2D.Double(v, dataArea.getMinY(), v, dataArea.getMaxY()); } else if (orientation == PlotOrientation.VERTICAL) { line = new Line2D.Double(dataArea.getMinX(), v, dataArea.getMaxX(), v); } else { throw new IllegalStateException("Unknown orientation."); } final Composite originalComposite = g2.getComposite(); g2.setComposite(AlphaComposite.getInstance( AlphaComposite.SRC_OVER, marker.getAlpha())); g2.setPaint(marker.getPaint()); g2.setStroke(marker.getStroke()); g2.draw(line); String label = marker.getLabel(); RectangleAnchor anchor = marker.getLabelAnchor(); if (label != null) { Font labelFont = marker.getLabelFont(); g2.setFont(labelFont); g2.setPaint(marker.getLabelPaint()); Point2D coordinates = calculateRangeMarkerTextAnchorPoint( g2, orientation, dataArea, line.getBounds2D(), marker.getLabelOffset(), LengthAdjustmentType.EXPAND, anchor); TextUtilities.drawAlignedString(label, g2, (float) coordinates.getX(), (float) coordinates.getY(), marker.getLabelTextAnchor()); } g2.setComposite(originalComposite); } else if (marker instanceof IntervalMarker) { IntervalMarker im = (IntervalMarker) marker; double start = im.getStartValue(); double end = im.getEndValue(); Range range = rangeAxis.getRange(); if (!(range.intersects(start, end))) { return; } double start2d = rangeAxis.valueToJava2D(start, dataArea, plot.getRangeAxisEdge()); double end2d = rangeAxis.valueToJava2D(end, dataArea, plot.getRangeAxisEdge()); double low = Math.min(start2d, end2d); double high = Math.max(start2d, end2d); PlotOrientation orientation = plot.getOrientation(); Rectangle2D rect = null; if (orientation == PlotOrientation.HORIZONTAL) { // clip left and right bounds to data area low = Math.max(low, dataArea.getMinX()); high = Math.min(high, dataArea.getMaxX()); rect = new Rectangle2D.Double(low, dataArea.getMinY(), high - low, dataArea.getHeight()); } else if (orientation == PlotOrientation.VERTICAL) { // clip top and bottom bounds to data area low = Math.max(low, dataArea.getMinY()); high = Math.min(high, dataArea.getMaxY()); rect = new Rectangle2D.Double(dataArea.getMinX(), low, dataArea.getWidth(), high - low); } final Composite originalComposite = g2.getComposite(); g2.setComposite(AlphaComposite.getInstance( AlphaComposite.SRC_OVER, marker.getAlpha())); Paint p = marker.getPaint(); if (p instanceof GradientPaint) { GradientPaint gp = (GradientPaint) p; GradientPaintTransformer t = im.getGradientPaintTransformer(); if (t != null) { gp = t.transform(gp, rect); } g2.setPaint(gp); } else { g2.setPaint(p); } g2.fill(rect); // now draw the outlines, if visible... if (im.getOutlinePaint() != null && im.getOutlineStroke() != null) { if (orientation == PlotOrientation.VERTICAL) { Line2D line = new Line2D.Double(); double x0 = dataArea.getMinX(); double x1 = dataArea.getMaxX(); g2.setPaint(im.getOutlinePaint()); g2.setStroke(im.getOutlineStroke()); if (range.contains(start)) { line.setLine(x0, start2d, x1, start2d); g2.draw(line); } if (range.contains(end)) { line.setLine(x0, end2d, x1, end2d); g2.draw(line); } } else { // PlotOrientation.HORIZONTAL Line2D line = new Line2D.Double(); double y0 = dataArea.getMinY(); double y1 = dataArea.getMaxY(); g2.setPaint(im.getOutlinePaint()); g2.setStroke(im.getOutlineStroke()); if (range.contains(start)) { line.setLine(start2d, y0, start2d, y1); g2.draw(line); } if (range.contains(end)) { line.setLine(end2d, y0, end2d, y1); g2.draw(line); } } } String label = marker.getLabel(); RectangleAnchor anchor = marker.getLabelAnchor(); if (label != null) { Font labelFont = marker.getLabelFont(); g2.setFont(labelFont); g2.setPaint(marker.getLabelPaint()); Point2D coordinates = calculateRangeMarkerTextAnchorPoint( g2, orientation, dataArea, rect, marker.getLabelOffset(), marker.getLabelOffsetType(), anchor); TextUtilities.drawAlignedString(label, g2, (float) coordinates.getX(), (float) coordinates.getY(), marker.getLabelTextAnchor()); } g2.setComposite(originalComposite); } } /** * Calculates the (x, y) coordinates for drawing a marker label. * * @param g2 the graphics device. * @param orientation the plot orientation. * @param dataArea the data area. * @param markerArea the marker area. * @param markerOffset the marker offset. * @param labelOffsetForRange ?? * @param anchor the label anchor. * * @return The coordinates for drawing the marker label. */ private Point2D calculateRangeMarkerTextAnchorPoint(Graphics2D g2, PlotOrientation orientation, Rectangle2D dataArea, Rectangle2D markerArea, RectangleInsets markerOffset, LengthAdjustmentType labelOffsetForRange, RectangleAnchor anchor) { Rectangle2D anchorRect = null; if (orientation == PlotOrientation.HORIZONTAL) { anchorRect = markerOffset.createAdjustedRectangle(markerArea, labelOffsetForRange, LengthAdjustmentType.CONTRACT); } else if (orientation == PlotOrientation.VERTICAL) { anchorRect = markerOffset.createAdjustedRectangle(markerArea, LengthAdjustmentType.CONTRACT, labelOffsetForRange); } return RectangleAnchor.coordinates(anchorRect, anchor); } /** * Returns a clone of the renderer. * * @return A clone. * * @throws CloneNotSupportedException if the renderer does not support * cloning. */ @Override protected Object clone() throws CloneNotSupportedException { AbstractXYItemRenderer clone = (AbstractXYItemRenderer) super.clone(); // 'plot' : just retain reference, not a deep copy clone.itemLabelGeneratorList = (ObjectList<XYItemLabelGenerator>) this.itemLabelGeneratorList.clone(); if (this.baseItemLabelGenerator != null && this.baseItemLabelGenerator instanceof PublicCloneable) { PublicCloneable pc = (PublicCloneable) this.baseItemLabelGenerator; clone.baseItemLabelGenerator = (XYItemLabelGenerator) pc.clone(); } clone.toolTipGeneratorList = (ObjectList<XYToolTipGenerator>) this.toolTipGeneratorList.clone(); if (this.baseToolTipGenerator != null && this.baseToolTipGenerator instanceof PublicCloneable) { PublicCloneable pc = (PublicCloneable) this.baseToolTipGenerator; clone.baseToolTipGenerator = (XYToolTipGenerator) pc.clone(); } if (this.legendItemLabelGenerator instanceof PublicCloneable) { clone.legendItemLabelGenerator = ObjectUtilities.clone(this.legendItemLabelGenerator); } if (this.legendItemToolTipGenerator instanceof PublicCloneable) { clone.legendItemToolTipGenerator = ObjectUtilities.clone(this.legendItemToolTipGenerator); } if (this.legendItemURLGenerator instanceof PublicCloneable) { clone.legendItemURLGenerator = ObjectUtilities.clone(this.legendItemURLGenerator); } clone.foregroundAnnotations = ObjectUtilities.deepClone( this.foregroundAnnotations); clone.backgroundAnnotations = ObjectUtilities.deepClone( this.backgroundAnnotations); return clone; } /** * Tests this renderer for equality with another object. * * @param obj the object (<code>null</code> permitted). * * @return <code>true</code> or <code>false</code>. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof AbstractXYItemRenderer)) { return false; } AbstractXYItemRenderer that = (AbstractXYItemRenderer) obj; if (!this.itemLabelGeneratorList.equals(that.itemLabelGeneratorList)) { return false; } if (!ObjectUtilities.equal(this.baseItemLabelGenerator, that.baseItemLabelGenerator)) { return false; } if (!this.toolTipGeneratorList.equals(that.toolTipGeneratorList)) { return false; } if (!ObjectUtilities.equal(this.baseToolTipGenerator, that.baseToolTipGenerator)) { return false; } if (!ObjectUtilities.equal(this.urlGenerator, that.urlGenerator)) { return false; } if (!this.foregroundAnnotations.equals(that.foregroundAnnotations)) { return false; } if (!this.backgroundAnnotations.equals(that.backgroundAnnotations)) { return false; } if (!ObjectUtilities.equal(this.legendItemLabelGenerator, that.legendItemLabelGenerator)) { return false; } if (!ObjectUtilities.equal(this.legendItemToolTipGenerator, that.legendItemToolTipGenerator)) { return false; } if (!ObjectUtilities.equal(this.legendItemURLGenerator, that.legendItemURLGenerator)) { return false; } return super.equals(obj); } /** * Returns the drawing supplier from the plot. * * @return The drawing supplier (possibly <code>null</code>). */ @Override public DrawingSupplier getDrawingSupplier() { DrawingSupplier result = null; XYPlot p = getPlot(); if (p != null) { result = p.getDrawingSupplier(); } return result; } /** * Considers the current (x, y) coordinate and updates the crosshair point * if it meets the criteria (usually means the (x, y) coordinate is the * closest to the anchor point so far). * * @param crosshairState the crosshair state (<code>null</code> permitted, * but the method does nothing in that case). * @param x the x-value (in data space). * @param y the y-value (in data space). * @param domainAxisIndex the index of the domain axis for the point. * @param rangeAxisIndex the index of the range axis for the point. * @param transX the x-value translated to Java2D space. * @param transY the y-value translated to Java2D space. * @param orientation the plot orientation (<code>null</code> not * permitted). * * @since 1.0.4 */ protected void updateCrosshairValues(CrosshairState crosshairState, double x, double y, int domainAxisIndex, int rangeAxisIndex, double transX, double transY, PlotOrientation orientation) { ParamChecks.nullNotPermitted(orientation, "orientation"); if (crosshairState != null) { // do we need to update the crosshair values? if (this.plot.isDomainCrosshairLockedOnData()) { if (this.plot.isRangeCrosshairLockedOnData()) { // both axes crosshairState.updateCrosshairPoint(x, y, domainAxisIndex, rangeAxisIndex, transX, transY, orientation); } else { // just the domain axis... crosshairState.updateCrosshairX(x, domainAxisIndex); } } else { if (this.plot.isRangeCrosshairLockedOnData()) { // just the range axis... crosshairState.updateCrosshairY(y, rangeAxisIndex); } } } } /** * Draws an item label. * * @param g2 the graphics device. * @param orientation the orientation. * @param dataset the dataset. * @param series the series index (zero-based). * @param item the item index (zero-based). * @param x the x coordinate (in Java2D space). * @param y the y coordinate (in Java2D space). * @param negative indicates a negative value (which affects the item * label position). */ protected void drawItemLabel(Graphics2D g2, PlotOrientation orientation, XYDataset dataset, int series, int item, double x, double y, boolean negative) { XYItemLabelGenerator generator = getItemLabelGenerator(series, item); if (generator != null) { Font labelFont = getItemLabelFont(series, item); Paint paint = getItemLabelPaint(series, item); g2.setFont(labelFont); g2.setPaint(paint); String label = generator.generateLabel(dataset, series, item); // get the label position.. ItemLabelPosition position; if (!negative) { position = getPositiveItemLabelPosition(series, item); } else { position = getNegativeItemLabelPosition(series, item); } // work out the label anchor point... Point2D anchorPoint = calculateLabelAnchorPoint( position.getItemLabelAnchor(), x, y, orientation); TextUtilities.drawRotatedString(label, g2, (float) anchorPoint.getX(), (float) anchorPoint.getY(), position.getTextAnchor(), position.getAngle(), position.getRotationAnchor()); } } /** * Draws all the annotations for the specified layer. * * @param g2 the graphics device. * @param dataArea the data area. * @param domainAxis the domain axis. * @param rangeAxis the range axis. * @param layer the layer. * @param info the plot rendering info. */ @Override public void drawAnnotations(Graphics2D g2, Rectangle2D dataArea, ValueAxis domainAxis, ValueAxis rangeAxis, Layer layer, PlotRenderingInfo info) { Iterator<XYAnnotation> iterator; if (layer.equals(Layer.FOREGROUND)) { iterator = this.foregroundAnnotations.iterator(); } else if (layer.equals(Layer.BACKGROUND)) { iterator = this.backgroundAnnotations.iterator(); } else { // should not get here throw new RuntimeException("Unknown layer."); } while (iterator.hasNext()) { XYAnnotation annotation = iterator.next(); int index = this.plot.getIndexOf(this); annotation.draw(g2, this.plot, dataArea, domainAxis, rangeAxis, index, info); } } /** * Adds an entity to the collection. * * @param entities the entity collection being populated. * @param area the entity area (if <code>null</code> a default will be * used). * @param dataset the dataset. * @param series the series. * @param item the item. * @param entityX the entity's center x-coordinate in user space (only * used if <code>area</code> is <code>null</code>). * @param entityY the entity's center y-coordinate in user space (only * used if <code>area</code> is <code>null</code>). */ protected void addEntity(EntityCollection entities, Shape area, XYDataset dataset, int series, int item, double entityX, double entityY) { if (!getItemCreateEntity(series, item)) { return; } Shape hotspot = area; if (hotspot == null) { double r = getDefaultEntityRadius(); double w = r * 2; if (getPlot().getOrientation() == PlotOrientation.VERTICAL) { hotspot = new Ellipse2D.Double(entityX - r, entityY - r, w, w); } else { hotspot = new Ellipse2D.Double(entityY - r, entityX - r, w, w); } } String tip = null; XYToolTipGenerator generator = getToolTipGenerator(series, item); if (generator != null) { tip = generator.generateToolTip(dataset, series, item); } String url = null; if (getURLGenerator() != null) { url = getURLGenerator().generateURL(dataset, series, item); } XYItemEntity entity = new XYItemEntity(hotspot, dataset, series, item, tip, url); entities.add(entity); } /** * Returns <code>true</code> if the specified point (x, y) falls within or * on the boundary of the specified rectangle. * * @param rect the rectangle (<code>null</code> not permitted). * @param x the x-coordinate. * @param y the y-coordinate. * * @return A boolean. * * @since 1.0.10 */ public static boolean isPointInRect(Rectangle2D rect, double x, double y) { // TODO: For JFreeChart 1.2.0, this method should go in the // ShapeUtilities class return (x >= rect.getMinX() && x <= rect.getMaxX() && y >= rect.getMinY() && y <= rect.getMaxY()); } /** * Utility method delegating to {@link GeneralPath#moveTo} taking double as * parameters. * * @param hotspot the region under construction (<code>null</code> not * permitted); * @param x the x coordinate; * @param y the y coordinate; * * @since 1.0.14 */ protected static void moveTo(GeneralPath hotspot, double x, double y) { hotspot.moveTo((float) x, (float) y); } /** * Utility method delegating to {@link GeneralPath#lineTo} taking double as * parameters. * * @param hotspot the region under construction (<code>null</code> not * permitted); * @param x the x coordinate; * @param y the y coordinate; * * @since 1.0.14 */ protected static void lineTo(GeneralPath hotspot, double x, double y) { hotspot.lineTo((float) x, (float) y); } }
70,520
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
StackedXYAreaRenderer3.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/renderer/xy/StackedXYAreaRenderer3.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * --------------------------- * StackedXYAreaRenderer2.java * --------------------------- * (C) Copyright 2004-2012, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited), based on * the StackedXYAreaRenderer class by Richard Atkinson; * Contributor(s): -; * * Changes: * -------- * 30-Apr-2004 : Version 1 (DG); * 15-Jul-2004 : Switched getX() with getXValue() and getY() with * getYValue() (DG); * 10-Sep-2004 : Removed getRangeType() method (DG); * 06-Jan-2004 : Renamed getRangeExtent() --> findRangeBounds (DG); * 28-Mar-2005 : Use getXValue() and getYValue() from dataset (DG); * 03-Oct-2005 : Add entity generation to drawItem() method (DG); * ------------- JFREECHART 1.0.x --------------------------------------------- * 22-Aug-2006 : Handle null and empty datasets correctly in the * findRangeBounds() method (DG); * 22-Sep-2006 : Added a flag to allow rounding of x-coordinates (after * translation to Java2D space) in order to avoid the striping * that can result from anti-aliasing (thanks to Doug * Clayton) (DG); * 30-Nov-2006 : Added accessor methods for the roundXCoordinates flag (DG); * 02-Jun-2008 : Fixed bug with PlotOrientation.HORIZONTAL (DG); * 17-Jun-2012 : Removed JCommon dependencies (DG); * */ package org.jfree.chart.renderer.xy; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.entity.EntityCollection; import org.jfree.chart.event.RendererChangeEvent; import org.jfree.chart.labels.XYToolTipGenerator; import org.jfree.chart.plot.CrosshairState; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.PlotRenderingInfo; import org.jfree.chart.plot.XYPlot; import org.jfree.chart.ui.RectangleEdge; import org.jfree.chart.urls.XYURLGenerator; import org.jfree.chart.util.PublicCloneable; import org.jfree.data.Range; import org.jfree.data.xy.TableXYDataset; import org.jfree.data.xy.XYDataset; import java.awt.*; import java.awt.geom.GeneralPath; import java.awt.geom.Rectangle2D; import java.io.Serializable; /** * A stacked area renderer for the {@link XYPlot} class. * The example shown here is generated by the * <code>StackedXYAreaChartDemo2.java</code> program included in the * JFreeChart demo collection: * <br><br> * <img src="../../../../../images/StackedXYAreaRenderer2Sample.png" * alt="StackedXYAreaRenderer2Sample.png" /> */ public class StackedXYAreaRenderer3 extends XYAreaRenderer2 implements Cloneable, PublicCloneable, Serializable { /** For serialization. */ private static final long serialVersionUID = 7752676509764539182L; /** * This flag controls whether or not the x-coordinates (in Java2D space) * are rounded to integers. When set to true, this can avoid the vertical * striping that anti-aliasing can generate. However, the rounding may not * be appropriate for output in high resolution formats (for example, * vector graphics formats such as SVG and PDF). * * @since 1.0.3 */ private boolean roundXCoordinates; /** * Creates a new renderer. */ public StackedXYAreaRenderer3() { this(null, null); } /** * Constructs a new renderer. * * @param labelGenerator the tool tip generator to use. <code>null</code> * is none. * @param urlGenerator the URL generator (<code>null</code> permitted). */ public StackedXYAreaRenderer3(XYToolTipGenerator labelGenerator, XYURLGenerator urlGenerator) { super(labelGenerator, urlGenerator); this.roundXCoordinates = true; } /** * Returns the flag that controls whether or not the x-coordinates (in * Java2D space) are rounded to integer values. * * @return The flag. * * @since 1.0.4 * * @see #setRoundXCoordinates(boolean) */ public boolean getRoundXCoordinates() { return this.roundXCoordinates; } /** * Sets the flag that controls whether or not the x-coordinates (in * Java2D space) are rounded to integer values, and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param round the new flag value. * * @since 1.0.4 * * @see #getRoundXCoordinates() */ public void setRoundXCoordinates(boolean round) { this.roundXCoordinates = round; fireChangeEvent(); } /** * Returns the range of values the renderer requires to display all the * items from the specified dataset. * * @param dataset the dataset (<code>null</code> permitted). * * @return The range (or <code>null</code> if the dataset is * <code>null</code> or empty). */ @Override public Range findRangeBounds(XYDataset dataset) { if (dataset == null) { return null; } double min = Double.POSITIVE_INFINITY; double max = Double.NEGATIVE_INFINITY; TableXYDataset d = (TableXYDataset) dataset; int itemCount = d.getItemCount(); for (int i = 0; i < itemCount; i++) { double[] stackValues = getStackValues((TableXYDataset) dataset, d.getSeriesCount(), i); min = Math.min(min, stackValues[0]); max = Math.max(max, stackValues[1]); } if (min == Double.POSITIVE_INFINITY) { return null; } return new Range(min, max); } /** * Returns the number of passes required by the renderer. * * @return 1. */ @Override public int getPassCount() { return 1; } /** * Draws the visual representation of a single data item. * * @param g2 the graphics device. * @param state the renderer state. * @param dataArea the area within which the data is being drawn. * @param info collects information about the drawing. * @param plot the plot (can be used to obtain standard color information * etc). * @param domainAxis the domain axis. * @param rangeAxis the range axis. * @param dataset the dataset. * @param series the series index (zero-based). * @param item the item index (zero-based). * @param crosshairState information about crosshairs on a plot. * @param pass the pass index. */ @Override public void drawItem(Graphics2D g2, XYItemRendererState state, Rectangle2D dataArea, PlotRenderingInfo info, XYPlot plot, ValueAxis domainAxis, ValueAxis rangeAxis, XYDataset dataset, int series, int item, CrosshairState crosshairState, int pass) { // setup for collecting optional entity info... Shape entityArea = null; EntityCollection entities = null; if (info != null) { entities = info.getOwner().getEntityCollection(); } TableXYDataset tdataset = (TableXYDataset) dataset; PlotOrientation orientation = plot.getOrientation(); // get the data point... double x1 = dataset.getXValue(series, item); double y1 = dataset.getYValue(series, item); if (Double.isNaN(y1)) { y1 = 0.0; } double[] stack1 = getStackValues(tdataset, series, item); // get the previous point and the next point so we can calculate a // "hot spot" for the area (used by the chart entity)... double x0 = dataset.getXValue(series, Math.max(item - 1, 0)); double y0 = dataset.getYValue(series, Math.max(item - 1, 0)); if (Double.isNaN(y0)) { y0 = 0.0; } double[] stack0 = getStackValues(tdataset, series, Math.max(item - 1, 0)); int itemCount = dataset.getItemCount(series); double x2 = dataset.getXValue(series, Math.min(item + 1, itemCount - 1)); double y2 = dataset.getYValue(series, Math.min(item + 1, itemCount - 1)); if (Double.isNaN(y2)) { y2 = 0.0; } double[] stack2 = getStackValues(tdataset, series, Math.min(item + 1, itemCount - 1)); double xleft = (x0 + x1) / 2.0; double xright = (x1 + x2) / 2.0; double[] stackLeft = averageStackValues(stack0, stack1); double[] stackRight = averageStackValues(stack1, stack2); double[] adjStackLeft = adjustedStackValues(stack0, stack1); double[] adjStackRight = adjustedStackValues(stack1, stack2); RectangleEdge edge0 = plot.getDomainAxisEdge(); float transX1 = (float) domainAxis.valueToJava2D(x1, dataArea, edge0); float transXLeft = (float) domainAxis.valueToJava2D(xleft, dataArea, edge0); float transXRight = (float) domainAxis.valueToJava2D(xright, dataArea, edge0); if (this.roundXCoordinates) { transX1 = Math.round(transX1); transXLeft = Math.round(transXLeft); transXRight = Math.round(transXRight); } float transY1 = 0; RectangleEdge edge1 = plot.getRangeAxisEdge(); GeneralPath left = new GeneralPath(); GeneralPath right = new GeneralPath(); /*if (y1 >= 0.0) { */ // handle positive value transY1 = (float) rangeAxis.valueToJava2D(y1 + stack1[1], dataArea, edge1); float transStack1 = (float) rangeAxis.valueToJava2D(stack1[1], dataArea, edge1); float transStackLeft = (float) rangeAxis.valueToJava2D( adjStackLeft[1], dataArea, edge1); // LEFT POLYGON if (y0 >= 0.0) { double yleft = (y0 + y1) / 2.0 + stackLeft[1]; float transYLeft = (float) rangeAxis.valueToJava2D(yleft, dataArea, edge1); if (orientation == PlotOrientation.VERTICAL) { left.moveTo(transX1, transY1); left.lineTo(transX1, transStack1); left.lineTo(transXLeft, transStackLeft); left.lineTo(transXLeft, transYLeft); } else { left.moveTo(transY1, transX1); left.lineTo(transStack1, transX1); left.lineTo(transStackLeft, transXLeft); left.lineTo(transYLeft, transXLeft); } left.closePath(); } else { if (orientation == PlotOrientation.VERTICAL) { left.moveTo(transX1, transStack1); left.lineTo(transX1, transY1); left.lineTo(transXLeft, transStackLeft); } else { left.moveTo(transStack1, transX1); left.lineTo(transY1, transX1); left.lineTo(transStackLeft, transXLeft); } left.closePath(); } float transStackRight = (float) rangeAxis.valueToJava2D( adjStackRight[1], dataArea, edge1); // RIGHT POLYGON if (y2 >= 0.0) { double yright = (y1 + y2) / 2.0 + stackRight[1]; float transYRight = (float) rangeAxis.valueToJava2D(yright, dataArea, edge1); if (orientation == PlotOrientation.VERTICAL) { right.moveTo(transX1, transStack1); right.lineTo(transX1, transY1); right.lineTo(transXRight, transYRight); right.lineTo(transXRight, transStackRight); } else { right.moveTo(transStack1, transX1); right.lineTo(transY1, transX1); right.lineTo(transYRight, transXRight); right.lineTo(transStackRight, transXRight); } right.closePath(); } else { if (orientation == PlotOrientation.VERTICAL) { right.moveTo(transX1, transStack1); right.lineTo(transX1, transY1); right.lineTo(transXRight, transStackRight); } else { right.moveTo(transStack1, transX1); right.lineTo(transY1, transX1); right.lineTo(transStackRight, transXRight); } right.closePath(); } // Get series Paint and Stroke Paint itemPaint = getItemPaint(series, item); if (pass == 0) { g2.setPaint(itemPaint); g2.fill(left); g2.fill(right); } // add an entity for the item... if (entities != null) { GeneralPath gp = new GeneralPath(left); gp.append(right, false); entityArea = gp; addEntity(entities, entityArea, dataset, series, item, transX1, transY1); } } /** * Calculates the stacked values (one positive and one negative) of all * series up to, but not including, <code>series</code> for the specified * item. It returns [0.0, 0.0] if <code>series</code> is the first series. * * @param dataset the dataset (<code>null</code> not permitted). * @param series the series index. * @param index the item index. * * @return An array containing the cumulative negative and positive values * for all series values up to but excluding <code>series</code> * for <code>index</code>. */ private double[] getStackValues(TableXYDataset dataset, int series, int index) { double[] result = new double[2]; for (int i = 0; i < series; i++) { double v = dataset.getYValue(i, index); if (!Double.isNaN(v)) { if (v >= 0.0) { result[1] += v; } else { result[0] += v; } } } return result; } /** * Returns a pair of "stack" values calculated as the mean of the two * specified stack value pairs. * * @param stack1 the first stack pair. * @param stack2 the second stack pair. * * @return A pair of average stack values. */ private double[] averageStackValues(double[] stack1, double[] stack2) { double[] result = new double[2]; result[0] = (stack1[0] + stack2[0]) / 2.0; result[1] = (stack1[1] + stack2[1]) / 2.0; return result; } /** * Calculates adjusted stack values from the supplied values. The value is * the mean of the supplied values, unless either of the supplied values * is zero, in which case the adjusted value is zero also. * * @param stack1 the first stack pair. * @param stack2 the second stack pair. * * @return A pair of average stack values. */ private double[] adjustedStackValues(double[] stack1, double[] stack2) { double[] result = new double[2]; if (stack1[0] == 0.0 || stack2[0] == 0.0) { result[0] = 0.0; } else { result[0] = (stack1[0] + stack2[0]) / 2.0; } if (stack1[1] == 0.0 || stack2[1] == 0.0) { result[1] = 0.0; } else { result[1] = (stack1[1] + stack2[1]) / 2.0; } return result; } /** * Tests this renderer for equality with an arbitrary object. * * @param obj the object (<code>null</code> permitted). * * @return A boolean. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof StackedXYAreaRenderer3)) { return false; } StackedXYAreaRenderer3 that = (StackedXYAreaRenderer3) obj; if (this.roundXCoordinates != that.roundXCoordinates) { return false; } return super.equals(obj); } /** * Returns a clone of the renderer. * * @return A clone. * * @throws CloneNotSupportedException if the renderer cannot be cloned. */ @Override public Object clone() throws CloneNotSupportedException { return super.clone(); } }
18,067
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
CandlestickRenderer.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/renderer/xy/CandlestickRenderer.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ------------------------ * CandlestickRenderer.java * ------------------------ * (C) Copyright 2001-2012, by Object Refinery Limited. * * Original Authors: David Gilbert (for Object Refinery Limited); * Sylvain Vieujot; * Contributor(s): Richard Atkinson; * Christian W. Zuckschwerdt; * Jerome Fisher; * * Changes * ------- * 13-Dec-2001 : Version 1. Based on code in the (now redundant) * CandlestickPlot class, written by Sylvain Vieujot (DG); * 23-Jan-2002 : Added DrawInfo parameter to drawItem() method (DG); * 28-Mar-2002 : Added a property change listener mechanism so that renderers * no longer need to be immutable. Added properties for up and * down colors (DG); * 04-Apr-2002 : Updated with new automatic width calculation and optional * volume display, contributed by Sylvain Vieujot (DG); * 09-Apr-2002 : Removed translatedRangeZero from the drawItem() method, and * changed the return type of the drawItem method to void, * reflecting a change in the XYItemRenderer interface. Added * tooltip code to drawItem() method (DG); * 25-Jun-2002 : Removed redundant code (DG); * 05-Aug-2002 : Small modification to drawItem method to support URLs for HTML * image maps (RA); * 19-Sep-2002 : Fixed errors reported by Checkstyle (DG); * 25-Mar-2003 : Implemented Serializable (DG); * 01-May-2003 : Modified drawItem() method signature (DG); * 30-Jun-2003 : Added support for PlotOrientation (for completeness, this * renderer is unlikely to be used with a HORIZONTAL * orientation) (DG); * 30-Jul-2003 : Modified entity constructor (CZ); * 20-Aug-2003 : Implemented Cloneable and PublicCloneable (DG); * 29-Aug-2003 : Moved maxVolume calculation to initialise method (see bug * report 796619) (DG); * 02-Sep-2003 : Added maxCandleWidthInMilliseconds as workaround for bug * 796621 (DG); * 08-Sep-2003 : Changed ValueAxis API (DG); * 16-Sep-2003 : Changed ChartRenderingInfo --> PlotRenderingInfo (DG); * 13-Oct-2003 : Applied patch from Jerome Fisher to improve auto width * calculations (DG); * 23-Dec-2003 : Fixed bug where up and down paint are used incorrectly (DG); * 25-Feb-2004 : Replaced CrosshairInfo with CrosshairState (DG); * 15-Jul-2004 : Switched getX() with getXValue() and getY() with * getYValue() (DG); * ------------- JFREECHART 1.0.x --------------------------------------------- * 06-Jul-2006 : Swapped calls to getX() --> getXValue(), and the same for the * other data values (DG); * 17-Aug-2006 : Corrections to the equals() method (DG); * 05-Mar-2007 : Added flag to allow optional use of outline paint (DG); * 08-Oct-2007 : Added new volumePaint field (DG); * 08-Apr-2008 : Added findRangeBounds() method override (DG); * 13-May-2008 : Fixed chart entity bugs (1962467 and 1962472) (DG); * 27-Mar-2009 : Updated findRangeBounds() to call new method in * superclass (DG); * 16-Jun-2012 : Removed JCommon dependencies (DG); * */ package org.jfree.chart.renderer.xy; import java.awt.AlphaComposite; import java.awt.Color; import java.awt.Composite; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.Stroke; import java.awt.geom.Line2D; import java.awt.geom.Rectangle2D; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.ui.RectangleEdge; import org.jfree.chart.util.PaintUtilities; import org.jfree.chart.util.PublicCloneable; import org.jfree.chart.entity.EntityCollection; import org.jfree.chart.event.RendererChangeEvent; import org.jfree.chart.labels.HighLowItemLabelGenerator; import org.jfree.chart.labels.XYToolTipGenerator; import org.jfree.chart.plot.CrosshairState; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.PlotRenderingInfo; import org.jfree.chart.plot.XYPlot; import org.jfree.chart.util.SerialUtilities; import org.jfree.data.Range; import org.jfree.data.xy.IntervalXYDataset; import org.jfree.data.xy.OHLCDataset; import org.jfree.data.xy.XYDataset; /** * A renderer that draws candlesticks on an {@link XYPlot} (requires a * {@link OHLCDataset}). The example shown here is generated * by the <code>CandlestickChartDemo1.java</code> program included in the * JFreeChart demo collection: * <br><br> * <img src="../../../../../images/CandlestickRendererSample.png" * alt="CandlestickRendererSample.png" /> * <P> * This renderer does not include code to calculate the crosshair point for the * plot. */ public class CandlestickRenderer extends AbstractXYItemRenderer implements XYItemRenderer, Cloneable, PublicCloneable, Serializable { /** For serialization. */ private static final long serialVersionUID = 50390395841817121L; /** The average width method. */ public static final int WIDTHMETHOD_AVERAGE = 0; /** The smallest width method. */ public static final int WIDTHMETHOD_SMALLEST = 1; /** The interval data method. */ public static final int WIDTHMETHOD_INTERVALDATA = 2; /** The method of automatically calculating the candle width. */ private int autoWidthMethod = WIDTHMETHOD_AVERAGE; /** * The number (generally between 0.0 and 1.0) by which the available space * automatically calculated for the candles will be multiplied to determine * the actual width to use. */ private double autoWidthFactor = 4.5 / 7; /** The minimum gap between one candle and the next */ private double autoWidthGap = 0.0; /** The candle width. */ private double candleWidth; /** The maximum candlewidth in milliseconds. */ private double maxCandleWidthInMilliseconds = 1000.0 * 60.0 * 60.0 * 20.0; /** Temporary storage for the maximum candle width. */ private double maxCandleWidth; /** * The paint used to fill the candle when the price moved up from open to * close. */ private transient Paint upPaint; /** * The paint used to fill the candle when the price moved down from open * to close. */ private transient Paint downPaint; /** A flag controlling whether or not volume bars are drawn on the chart. */ private boolean drawVolume; /** * The paint used to fill the volume bars (if they are visible). Once * initialised, this field should never be set to <code>null</code>. * * @since 1.0.7 */ private transient Paint volumePaint; /** Temporary storage for the maximum volume. */ private transient double maxVolume; /** * A flag that controls whether or not the renderer's outline paint is * used to draw the outline of the candlestick. The default value is * <code>false</code> to avoid a change of behaviour for existing code. * * @since 1.0.5 */ private boolean useOutlinePaint; /** * Creates a new renderer for candlestick charts. */ public CandlestickRenderer() { this(-1.0); } /** * Creates a new renderer for candlestick charts. * <P> * Use -1 for the candle width if you prefer the width to be calculated * automatically. * * @param candleWidth The candle width. */ public CandlestickRenderer(double candleWidth) { this(candleWidth, true, new HighLowItemLabelGenerator()); } /** * Creates a new renderer for candlestick charts. * <P> * Use -1 for the candle width if you prefer the width to be calculated * automatically. * * @param candleWidth the candle width. * @param drawVolume a flag indicating whether or not volume bars should * be drawn. * @param toolTipGenerator the tool tip generator. <code>null</code> is * none. */ public CandlestickRenderer(double candleWidth, boolean drawVolume, XYToolTipGenerator toolTipGenerator) { super(); setDefaultToolTipGenerator(toolTipGenerator); this.candleWidth = candleWidth; this.drawVolume = drawVolume; this.volumePaint = Color.GRAY; this.upPaint = Color.GREEN; this.downPaint = Color.RED; this.useOutlinePaint = false; // false preserves the old behaviour // prior to introducing this flag } /** * Returns the width of each candle. * * @return The candle width. * * @see #setCandleWidth(double) */ public double getCandleWidth() { return this.candleWidth; } /** * Sets the candle width and sends a {@link RendererChangeEvent} to all * registered listeners. * <P> * If you set the width to a negative value, the renderer will calculate * the candle width automatically based on the space available on the chart. * * @param width The width. * @see #setAutoWidthMethod(int) * @see #setAutoWidthGap(double) * @see #setAutoWidthFactor(double) * @see #setMaxCandleWidthInMilliseconds(double) */ public void setCandleWidth(double width) { if (width != this.candleWidth) { this.candleWidth = width; fireChangeEvent(); } } /** * Returns the maximum width (in milliseconds) of each candle. * * @return The maximum candle width in milliseconds. * * @see #setMaxCandleWidthInMilliseconds(double) */ public double getMaxCandleWidthInMilliseconds() { return this.maxCandleWidthInMilliseconds; } /** * Sets the maximum candle width (in milliseconds) and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param millis The maximum width. * * @see #getMaxCandleWidthInMilliseconds() * @see #setCandleWidth(double) * @see #setAutoWidthMethod(int) * @see #setAutoWidthGap(double) * @see #setAutoWidthFactor(double) */ public void setMaxCandleWidthInMilliseconds(double millis) { this.maxCandleWidthInMilliseconds = millis; fireChangeEvent(); } /** * Returns the method of automatically calculating the candle width. * * @return The method of automatically calculating the candle width. * * @see #setAutoWidthMethod(int) */ public int getAutoWidthMethod() { return this.autoWidthMethod; } /** * Sets the method of automatically calculating the candle width and * sends a {@link RendererChangeEvent} to all registered listeners. * <p> * <code>WIDTHMETHOD_AVERAGE</code>: Divides the entire display (ignoring * scale factor) by the number of items, and uses this as the available * width.<br> * <code>WIDTHMETHOD_SMALLEST</code>: Checks the interval between each * item, and uses the smallest as the available width.<br> * <code>WIDTHMETHOD_INTERVALDATA</code>: Assumes that the dataset supports * the IntervalXYDataset interface, and uses the startXValue - endXValue as * the available width. * <br> * * @param autoWidthMethod The method of automatically calculating the * candle width. * * @see #WIDTHMETHOD_AVERAGE * @see #WIDTHMETHOD_SMALLEST * @see #WIDTHMETHOD_INTERVALDATA * @see #getAutoWidthMethod() * @see #setCandleWidth(double) * @see #setAutoWidthGap(double) * @see #setAutoWidthFactor(double) * @see #setMaxCandleWidthInMilliseconds(double) */ public void setAutoWidthMethod(int autoWidthMethod) { if (this.autoWidthMethod != autoWidthMethod) { this.autoWidthMethod = autoWidthMethod; fireChangeEvent(); } } /** * Returns the factor by which the available space automatically * calculated for the candles will be multiplied to determine the actual * width to use. * * @return The width factor (generally between 0.0 and 1.0). * * @see #setAutoWidthFactor(double) */ public double getAutoWidthFactor() { return this.autoWidthFactor; } /** * Sets the factor by which the available space automatically calculated * for the candles will be multiplied to determine the actual width to use. * * @param autoWidthFactor The width factor (generally between 0.0 and 1.0). * * @see #getAutoWidthFactor() * @see #setCandleWidth(double) * @see #setAutoWidthMethod(int) * @see #setAutoWidthGap(double) * @see #setMaxCandleWidthInMilliseconds(double) */ public void setAutoWidthFactor(double autoWidthFactor) { if (this.autoWidthFactor != autoWidthFactor) { this.autoWidthFactor = autoWidthFactor; fireChangeEvent(); } } /** * Returns the amount of space to leave on the left and right of each * candle when automatically calculating widths. * * @return The gap. * * @see #setAutoWidthGap(double) */ public double getAutoWidthGap() { return this.autoWidthGap; } /** * Sets the amount of space to leave on the left and right of each candle * when automatically calculating widths and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param autoWidthGap The gap. * * @see #getAutoWidthGap() * @see #setCandleWidth(double) * @see #setAutoWidthMethod(int) * @see #setAutoWidthFactor(double) * @see #setMaxCandleWidthInMilliseconds(double) */ public void setAutoWidthGap(double autoWidthGap) { if (this.autoWidthGap != autoWidthGap) { this.autoWidthGap = autoWidthGap; fireChangeEvent(); } } /** * Returns the paint used to fill candles when the price moves up from open * to close. * * @return The paint (possibly <code>null</code>). * * @see #setUpPaint(Paint) */ public Paint getUpPaint() { return this.upPaint; } /** * Sets the paint used to fill candles when the price moves up from open * to close and sends a {@link RendererChangeEvent} to all registered * listeners. * * @param paint the paint (<code>null</code> permitted). * * @see #getUpPaint() */ public void setUpPaint(Paint paint) { this.upPaint = paint; fireChangeEvent(); } /** * Returns the paint used to fill candles when the price moves down from * open to close. * * @return The paint (possibly <code>null</code>). * * @see #setDownPaint(Paint) */ public Paint getDownPaint() { return this.downPaint; } /** * Sets the paint used to fill candles when the price moves down from open * to close and sends a {@link RendererChangeEvent} to all registered * listeners. * * @param paint The paint (<code>null</code> permitted). */ public void setDownPaint(Paint paint) { this.downPaint = paint; fireChangeEvent(); } /** * Returns a flag indicating whether or not volume bars are drawn on the * chart. * * @return A boolean. * * @since 1.0.5 * * @see #setDrawVolume(boolean) */ public boolean getDrawVolume() { return this.drawVolume; } /** * Sets a flag that controls whether or not volume bars are drawn in the * background and sends a {@link RendererChangeEvent} to all registered * listeners. * * @param flag the flag. * * @see #getDrawVolume() */ public void setDrawVolume(boolean flag) { if (this.drawVolume != flag) { this.drawVolume = flag; fireChangeEvent(); } } /** * Returns the paint that is used to fill the volume bars if they are * visible. * * @return The paint (never <code>null</code>). * * @see #setVolumePaint(Paint) * * @since 1.0.7 */ public Paint getVolumePaint() { return this.volumePaint; } /** * Sets the paint used to fill the volume bars, and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param paint the paint (<code>null</code> not permitted). * * @see #getVolumePaint() * @see #getDrawVolume() * * @since 1.0.7 */ public void setVolumePaint(Paint paint) { if (paint == null) { throw new IllegalArgumentException("Null 'paint' argument."); } this.volumePaint = paint; fireChangeEvent(); } /** * Returns the flag that controls whether or not the renderer's outline * paint is used to draw the candlestick outline. The default value is * <code>false</code>. * * @return A boolean. * * @since 1.0.5 * * @see #setUseOutlinePaint(boolean) */ public boolean getUseOutlinePaint() { return this.useOutlinePaint; } /** * Sets the flag that controls whether or not the renderer's outline * paint is used to draw the candlestick outline, and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param use the new flag value. * * @since 1.0.5 * * @see #getUseOutlinePaint() */ public void setUseOutlinePaint(boolean use) { if (this.useOutlinePaint != use) { this.useOutlinePaint = use; fireChangeEvent(); } } /** * Returns the range of values the renderer requires to display all the * items from the specified dataset. * * @param dataset the dataset (<code>null</code> permitted). * * @return The range (<code>null</code> if the dataset is <code>null</code> * or empty). */ @Override public Range findRangeBounds(XYDataset dataset) { return findRangeBounds(dataset, true); } /** * Initialises the renderer then returns the number of 'passes' through the * data that the renderer will require (usually just one). This method * will be called before the first item is rendered, giving the renderer * an opportunity to initialise any state information it wants to maintain. * The renderer can do nothing if it chooses. * * @param g2 the graphics device. * @param dataArea the area inside the axes. * @param plot the plot. * @param dataset the data. * @param info an optional info collection object to return data back to * the caller. * * @return The number of passes the renderer requires. */ @Override public XYItemRendererState initialise(Graphics2D g2, Rectangle2D dataArea, XYPlot plot, XYDataset dataset, PlotRenderingInfo info) { // calculate the maximum allowed candle width from the axis... ValueAxis axis = plot.getDomainAxis(); double x1 = axis.getLowerBound(); double x2 = x1 + this.maxCandleWidthInMilliseconds; RectangleEdge edge = plot.getDomainAxisEdge(); double xx1 = axis.valueToJava2D(x1, dataArea, edge); double xx2 = axis.valueToJava2D(x2, dataArea, edge); this.maxCandleWidth = Math.abs(xx2 - xx1); // Absolute value, since the relative x // positions are reversed for horizontal orientation // calculate the highest volume in the dataset... if (this.drawVolume) { OHLCDataset highLowDataset = (OHLCDataset) dataset; this.maxVolume = 0.0; for (int series = 0; series < highLowDataset.getSeriesCount(); series++) { for (int item = 0; item < highLowDataset.getItemCount(series); item++) { double volume = highLowDataset.getVolumeValue(series, item); if (volume > this.maxVolume) { this.maxVolume = volume; } } } } return new XYItemRendererState(info); } /** * Draws the visual representation of a single data item. * * @param g2 the graphics device. * @param state the renderer state. * @param dataArea the area within which the plot is being drawn. * @param info collects info about the drawing. * @param plot the plot (can be used to obtain standard color * information etc). * @param domainAxis the domain axis. * @param rangeAxis the range axis. * @param dataset the dataset. * @param series the series index (zero-based). * @param item the item index (zero-based). * @param crosshairState crosshair information for the plot * (<code>null</code> permitted). * @param pass the pass index. */ @Override public void drawItem(Graphics2D g2, XYItemRendererState state, Rectangle2D dataArea, PlotRenderingInfo info, XYPlot plot, ValueAxis domainAxis, ValueAxis rangeAxis, XYDataset dataset, int series, int item, CrosshairState crosshairState, int pass) { boolean horiz; PlotOrientation orientation = plot.getOrientation(); if (orientation == PlotOrientation.HORIZONTAL) { horiz = true; } else if (orientation == PlotOrientation.VERTICAL) { horiz = false; } else { return; } // setup for collecting optional entity info... EntityCollection entities = null; if (info != null) { entities = info.getOwner().getEntityCollection(); } OHLCDataset highLowData = (OHLCDataset) dataset; double x = highLowData.getXValue(series, item); double yHigh = highLowData.getHighValue(series, item); double yLow = highLowData.getLowValue(series, item); double yOpen = highLowData.getOpenValue(series, item); double yClose = highLowData.getCloseValue(series, item); RectangleEdge domainEdge = plot.getDomainAxisEdge(); double xx = domainAxis.valueToJava2D(x, dataArea, domainEdge); RectangleEdge edge = plot.getRangeAxisEdge(); double yyHigh = rangeAxis.valueToJava2D(yHigh, dataArea, edge); double yyLow = rangeAxis.valueToJava2D(yLow, dataArea, edge); double yyOpen = rangeAxis.valueToJava2D(yOpen, dataArea, edge); double yyClose = rangeAxis.valueToJava2D(yClose, dataArea, edge); double volumeWidth; double stickWidth; if (this.candleWidth > 0) { // These are deliberately not bounded to minimums/maxCandleWidth to // retain old behaviour. volumeWidth = this.candleWidth; stickWidth = this.candleWidth; } else { double xxWidth = 0; int itemCount; switch (this.autoWidthMethod) { case WIDTHMETHOD_AVERAGE: itemCount = highLowData.getItemCount(series); if (horiz) { xxWidth = dataArea.getHeight() / itemCount; } else { xxWidth = dataArea.getWidth() / itemCount; } break; case WIDTHMETHOD_SMALLEST: // Note: It would be nice to pre-calculate this per series itemCount = highLowData.getItemCount(series); double lastPos = -1; xxWidth = dataArea.getWidth(); for (int i = 0; i < itemCount; i++) { double pos = domainAxis.valueToJava2D( highLowData.getXValue(series, i), dataArea, domainEdge); if (lastPos != -1) { xxWidth = Math.min(xxWidth, Math.abs(pos - lastPos)); } lastPos = pos; } break; case WIDTHMETHOD_INTERVALDATA: IntervalXYDataset intervalXYData = (IntervalXYDataset) dataset; double startPos = domainAxis.valueToJava2D( intervalXYData.getStartXValue(series, item), dataArea, plot.getDomainAxisEdge()); double endPos = domainAxis.valueToJava2D( intervalXYData.getEndXValue(series, item), dataArea, plot.getDomainAxisEdge()); xxWidth = Math.abs(endPos - startPos); break; } xxWidth -= 2 * this.autoWidthGap; xxWidth *= this.autoWidthFactor; xxWidth = Math.min(xxWidth, this.maxCandleWidth); volumeWidth = Math.max(Math.min(1, this.maxCandleWidth), xxWidth); stickWidth = Math.max(Math.min(3, this.maxCandleWidth), xxWidth); } Paint p = getItemPaint(series, item); Paint outlinePaint = null; if (this.useOutlinePaint) { outlinePaint = getItemOutlinePaint(series, item); } Stroke s = getItemStroke(series, item); g2.setStroke(s); if (this.drawVolume) { int volume = (int) highLowData.getVolumeValue(series, item); double volumeHeight = volume / this.maxVolume; double min, max; if (horiz) { min = dataArea.getMinX(); max = dataArea.getMaxX(); } else { min = dataArea.getMinY(); max = dataArea.getMaxY(); } double zzVolume = volumeHeight * (max - min); g2.setPaint(getVolumePaint()); Composite originalComposite = g2.getComposite(); g2.setComposite(AlphaComposite.getInstance( AlphaComposite.SRC_OVER, 0.3f)); if (horiz) { g2.fill(new Rectangle2D.Double(min, xx - volumeWidth / 2, zzVolume, volumeWidth)); } else { g2.fill(new Rectangle2D.Double(xx - volumeWidth / 2, max - zzVolume, volumeWidth, zzVolume)); } g2.setComposite(originalComposite); } if (this.useOutlinePaint) { g2.setPaint(outlinePaint); } else { g2.setPaint(p); } double yyMaxOpenClose = Math.max(yyOpen, yyClose); double yyMinOpenClose = Math.min(yyOpen, yyClose); double maxOpenClose = Math.max(yOpen, yClose); double minOpenClose = Math.min(yOpen, yClose); // draw the upper shadow if (yHigh > maxOpenClose) { if (horiz) { g2.draw(new Line2D.Double(yyHigh, xx, yyMaxOpenClose, xx)); } else { g2.draw(new Line2D.Double(xx, yyHigh, xx, yyMaxOpenClose)); } } // draw the lower shadow if (yLow < minOpenClose) { if (horiz) { g2.draw(new Line2D.Double(yyLow, xx, yyMinOpenClose, xx)); } else { g2.draw(new Line2D.Double(xx, yyLow, xx, yyMinOpenClose)); } } // draw the body Rectangle2D body; Rectangle2D hotspot; double length = Math.abs(yyHigh - yyLow); double base = Math.min(yyHigh, yyLow); if (horiz) { body = new Rectangle2D.Double(yyMinOpenClose, xx - stickWidth / 2, yyMaxOpenClose - yyMinOpenClose, stickWidth); hotspot = new Rectangle2D.Double(base, xx - stickWidth / 2, length, stickWidth); } else { body = new Rectangle2D.Double(xx - stickWidth / 2, yyMinOpenClose, stickWidth, yyMaxOpenClose - yyMinOpenClose); hotspot = new Rectangle2D.Double(xx - stickWidth / 2, base, stickWidth, length); } if (yClose > yOpen) { if (this.upPaint != null) { g2.setPaint(this.upPaint); } else { g2.setPaint(p); } g2.fill(body); } else { if (this.downPaint != null) { g2.setPaint(this.downPaint); } else { g2.setPaint(p); } g2.fill(body); } if (this.useOutlinePaint) { g2.setPaint(outlinePaint); } else { g2.setPaint(p); } g2.draw(body); // add an entity for the item... if (entities != null) { addEntity(entities, hotspot, dataset, series, item, 0.0, 0.0); } } /** * Tests this renderer for equality with another object. * * @param obj the object (<code>null</code> permitted). * * @return <code>true</code> or <code>false</code>. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof CandlestickRenderer)) { return false; } CandlestickRenderer that = (CandlestickRenderer) obj; if (this.candleWidth != that.candleWidth) { return false; } if (!PaintUtilities.equal(this.upPaint, that.upPaint)) { return false; } if (!PaintUtilities.equal(this.downPaint, that.downPaint)) { return false; } if (this.drawVolume != that.drawVolume) { return false; } if (this.maxCandleWidthInMilliseconds != that.maxCandleWidthInMilliseconds) { return false; } if (this.autoWidthMethod != that.autoWidthMethod) { return false; } if (this.autoWidthFactor != that.autoWidthFactor) { return false; } if (this.autoWidthGap != that.autoWidthGap) { return false; } if (this.useOutlinePaint != that.useOutlinePaint) { return false; } if (!PaintUtilities.equal(this.volumePaint, that.volumePaint)) { return false; } return super.equals(obj); } /** * Returns a clone of the renderer. * * @return A clone. * * @throws CloneNotSupportedException if the renderer cannot be cloned. */ @Override public Object clone() throws CloneNotSupportedException { return super.clone(); } /** * Provides serialization support. * * @param stream the output stream. * * @throws IOException if there is an I/O error. */ private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); SerialUtilities.writePaint(this.upPaint, stream); SerialUtilities.writePaint(this.downPaint, stream); SerialUtilities.writePaint(this.volumePaint, stream); } /** * Provides serialization support. * * @param stream the input stream. * * @throws IOException if there is an I/O error. * @throws ClassNotFoundException if there is a classpath problem. */ private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); this.upPaint = SerialUtilities.readPaint(stream); this.downPaint = SerialUtilities.readPaint(stream); this.volumePaint = SerialUtilities.readPaint(stream); } }
33,739
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
XYAreaRenderer2.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/renderer/xy/XYAreaRenderer2.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * -------------------- * XYAreaRenderer2.java * -------------------- * (C) Copyright 2004-2012, by Hari and Contributors. * * Original Author: Hari ([email protected]); * Contributor(s): David Gilbert (for Object Refinery Limited); * Richard Atkinson; * Christian W. Zuckschwerdt; * Martin Krauskopf; * * Changes: * -------- * 03-Apr-2002 : Version 1, contributed by Hari. This class is based on the * StandardXYItemRenderer class (DG); * 09-Apr-2002 : Removed the translated zero from the drawItem method - * overridden the initialise() method to calculate it (DG); * 30-May-2002 : Added tool tip generator to constructor to match super * class (DG); * 25-Jun-2002 : Removed unnecessary local variable (DG); * 05-Aug-2002 : Small modification to drawItem method to support URLs for * HTML image maps (RA); * 01-Oct-2002 : Fixed errors reported by Checkstyle (DG); * 07-Nov-2002 : Renamed AreaXYItemRenderer --> XYAreaRenderer (DG); * 25-Mar-2003 : Implemented Serializable (DG); * 01-May-2003 : Modified drawItem() method signature (DG); * 27-Jul-2003 : Made line and polygon properties protected rather than * private (RA); * 30-Jul-2003 : Modified entity constructor (CZ); * 20-Aug-2003 : Implemented Cloneable and PublicCloneable (DG); * 16-Sep-2003 : Changed ChartRenderingInfo --> PlotRenderingInfo (DG); * 07-Oct-2003 : Added renderer state (DG); * 08-Dec-2003 : Modified hotspot for chart entity (DG); * 10-Feb-2004 : Changed the drawItem() method to make cut-and-paste * overriding easier. Also moved state class into this * class (DG); * 25-Feb-2004 : Replaced CrosshairInfo with CrosshairState. Renamed * XYToolTipGenerator --> XYItemLabelGenerator (DG); * 15-Jul-2004 : Switched getX() with getXValue() and getY() with * getYValue() (DG); * 11-Nov-2004 : Now uses ShapeUtilities to translate shapes (DG); * 19-Jan-2005 : Now accesses only primitives from the dataset (DG); * 21-Mar-2005 : Override getLegendItem() (DG); * 20-Apr-2005 : Use generators for legend tooltips and URLs (DG); * ------------- JFREECHART 1.0.x --------------------------------------------- * 30-Nov-2006 : Fixed equals() and clone() implementations (DG); * 06-Feb-2007 : Fixed bug 1086307, crosshairs with multiple axes (DG); * 20-Apr-2007 : Updated getLegendItem() and drawItem() for renderer * change (DG); * 17-May-2007 : Set datasetIndex and seriesIndex in getLegendItem() (DG); * 18-May-2007 : Set dataset and seriesKey for LegendItem (DG); * 17-Jun-2008 : Apply legend font and paint attributes (DG); * 06-Oct-2011 : Avoid GeneralPath methods requiring Java 1.5 (MK); * 17-Jun-2012 : Removed JCommon dependencies (DG); * */ package org.jfree.chart.renderer.xy; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.Shape; import java.awt.Stroke; import java.awt.geom.GeneralPath; import java.awt.geom.Rectangle2D; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import org.jfree.chart.LegendItem; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.util.PublicCloneable; import org.jfree.chart.util.ShapeUtilities; import org.jfree.chart.entity.EntityCollection; import org.jfree.chart.entity.XYItemEntity; import org.jfree.chart.event.RendererChangeEvent; import org.jfree.chart.labels.XYSeriesLabelGenerator; import org.jfree.chart.labels.XYToolTipGenerator; import org.jfree.chart.plot.CrosshairState; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.PlotRenderingInfo; import org.jfree.chart.plot.XYPlot; import org.jfree.chart.urls.XYURLGenerator; import org.jfree.chart.util.SerialUtilities; import org.jfree.data.xy.XYDataset; /** * Area item renderer for an {@link XYPlot}. The example shown here is * generated by the <code>XYAreaRenderer2Demo1.java</code> program included in * the JFreeChart demo collection: * <br><br> * <img src="../../../../../images/XYAreaRenderer2Sample.png" * alt="XYAreaRenderer2Sample.png" /> */ public class XYAreaRenderer2 extends AbstractXYItemRenderer implements XYItemRenderer, PublicCloneable { /** For serialization. */ private static final long serialVersionUID = -7378069681579984133L; /** A flag that controls whether or not the outline is shown. */ private boolean showOutline; /** * The shape used to represent an area in each legend item (this should * never be <code>null</code>). */ private transient Shape legendArea; /** * Constructs a new renderer. */ public XYAreaRenderer2() { this(null, null); } /** * Constructs a new renderer. * * @param labelGenerator the tool tip generator to use. <code>null</code> * is none. * @param urlGenerator the URL generator (null permitted). */ public XYAreaRenderer2(XYToolTipGenerator labelGenerator, XYURLGenerator urlGenerator) { super(); this.showOutline = false; setDefaultToolTipGenerator(labelGenerator); setURLGenerator(urlGenerator); GeneralPath area = new GeneralPath(); area.moveTo(0.0f, -4.0f); area.lineTo(3.0f, -2.0f); area.lineTo(4.0f, 4.0f); area.lineTo(-4.0f, 4.0f); area.lineTo(-3.0f, -2.0f); area.closePath(); this.legendArea = area; } /** * Returns a flag that controls whether or not outlines of the areas are * drawn. * * @return The flag. * * @see #setOutline(boolean) */ public boolean isOutline() { return this.showOutline; } /** * Sets a flag that controls whether or not outlines of the areas are * drawn, and sends a {@link RendererChangeEvent} to all registered * listeners. * * @param show the flag. * * @see #isOutline() */ public void setOutline(boolean show) { this.showOutline = show; fireChangeEvent(); } /** * Returns the shape used to represent an area in the legend. * * @return The legend area (never <code>null</code>). * * @see #setLegendArea(Shape) */ public Shape getLegendArea() { return this.legendArea; } /** * Sets the shape used as an area in each legend item and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param area the area (<code>null</code> not permitted). * * @see #getLegendArea() */ public void setLegendArea(Shape area) { if (area == null) { throw new IllegalArgumentException("Null 'area' argument."); } this.legendArea = area; fireChangeEvent(); } /** * Returns a default legend item for the specified series. Subclasses * should override this method to generate customised items. * * @param datasetIndex the dataset index (zero-based). * @param series the series index (zero-based). * * @return A legend item for the series. */ @Override public LegendItem getLegendItem(int datasetIndex, int series) { LegendItem result = null; XYPlot xyplot = getPlot(); if (xyplot != null) { XYDataset dataset = xyplot.getDataset(datasetIndex); if (dataset != null) { XYSeriesLabelGenerator lg = getLegendItemLabelGenerator(); String label = lg.generateLabel(dataset, series); String description = label; String toolTipText = null; if (getLegendItemToolTipGenerator() != null) { toolTipText = getLegendItemToolTipGenerator().generateLabel( dataset, series); } String urlText = null; if (getLegendItemURLGenerator() != null) { urlText = getLegendItemURLGenerator().generateLabel( dataset, series); } Paint paint = lookupSeriesPaint(series); result = new LegendItem(label, description, toolTipText, urlText, this.legendArea, paint); result.setLabelFont(lookupLegendTextFont(series)); Paint labelPaint = lookupLegendTextPaint(series); if (labelPaint != null) { result.setLabelPaint(labelPaint); } result.setDataset(dataset); result.setDatasetIndex(datasetIndex); result.setSeriesKey(dataset.getSeriesKey(series)); result.setSeriesIndex(series); } } return result; } /** * Draws the visual representation of a single data item. * * @param g2 the graphics device. * @param state the renderer state. * @param dataArea the area within which the data is being drawn. * @param info collects information about the drawing. * @param plot the plot (can be used to obtain standard color * information etc). * @param domainAxis the domain axis. * @param rangeAxis the range axis. * @param dataset the dataset. * @param series the series index (zero-based). * @param item the item index (zero-based). * @param crosshairState crosshair information for the plot * (<code>null</code> permitted). * @param pass the pass index. */ @Override public void drawItem(Graphics2D g2, XYItemRendererState state, Rectangle2D dataArea, PlotRenderingInfo info, XYPlot plot, ValueAxis domainAxis, ValueAxis rangeAxis, XYDataset dataset, int series, int item, CrosshairState crosshairState, int pass) { if (!getItemVisible(series, item)) { return; } // get the data point... double x1 = dataset.getXValue(series, item); double y1 = dataset.getYValue(series, item); if (Double.isNaN(y1)) { y1 = 0.0; } double transX1 = domainAxis.valueToJava2D(x1, dataArea, plot.getDomainAxisEdge()); double transY1 = rangeAxis.valueToJava2D(y1, dataArea, plot.getRangeAxisEdge()); // get the previous point and the next point so we can calculate a // "hot spot" for the area (used by the chart entity)... double x0 = dataset.getXValue(series, Math.max(item - 1, 0)); double y0 = dataset.getYValue(series, Math.max(item - 1, 0)); if (Double.isNaN(y0)) { y0 = 0.0; } double transX0 = domainAxis.valueToJava2D(x0, dataArea, plot.getDomainAxisEdge()); double transY0 = rangeAxis.valueToJava2D(y0, dataArea, plot.getRangeAxisEdge()); int itemCount = dataset.getItemCount(series); double x2 = dataset.getXValue(series, Math.min(item + 1, itemCount - 1)); double y2 = dataset.getYValue(series, Math.min(item + 1, itemCount - 1)); if (Double.isNaN(y2)) { y2 = 0.0; } double transX2 = domainAxis.valueToJava2D(x2, dataArea, plot.getDomainAxisEdge()); double transY2 = rangeAxis.valueToJava2D(y2, dataArea, plot.getRangeAxisEdge()); double transZero = rangeAxis.valueToJava2D(0.0, dataArea, plot.getRangeAxisEdge()); GeneralPath hotspot = new GeneralPath(); if (plot.getOrientation() == PlotOrientation.HORIZONTAL) { moveTo(hotspot, transZero, ((transX0 + transX1) / 2.0)); lineTo(hotspot, ((transY0 + transY1) / 2.0), ((transX0 + transX1) / 2.0)); lineTo(hotspot, transY1, transX1); lineTo(hotspot, ((transY1 + transY2) / 2.0), ((transX1 + transX2) / 2.0)); lineTo(hotspot, transZero, ((transX1 + transX2) / 2.0)); } else { // vertical orientation moveTo(hotspot, ((transX0 + transX1) / 2.0), transZero); lineTo(hotspot, ((transX0 + transX1) / 2.0), ((transY0 + transY1) / 2.0)); lineTo(hotspot, transX1, transY1); lineTo(hotspot, ((transX1 + transX2) / 2.0), ((transY1 + transY2) / 2.0)); lineTo(hotspot, ((transX1 + transX2) / 2.0), transZero); } hotspot.closePath(); PlotOrientation orientation = plot.getOrientation(); Paint paint = getItemPaint(series, item); Stroke stroke = getItemStroke(series, item); g2.setPaint(paint); g2.setStroke(stroke); // Check if the item is the last item for the series. // and number of items > 0. We can't draw an area for a single point. g2.fill(hotspot); // draw an outline around the Area. if (isOutline()) { g2.setStroke(lookupSeriesOutlineStroke(series)); g2.setPaint(lookupSeriesOutlinePaint(series)); g2.draw(hotspot); } int domainAxisIndex = plot.getDomainAxisIndex(domainAxis); int rangeAxisIndex = plot.getRangeAxisIndex(rangeAxis); updateCrosshairValues(crosshairState, x1, y1, domainAxisIndex, rangeAxisIndex, transX1, transY1, orientation); // collect entity and tool tip information... if (state.getInfo() != null) { EntityCollection entities = state.getEntityCollection(); if (entities != null) { String tip = null; XYToolTipGenerator generator = getToolTipGenerator(series, item); if (generator != null) { tip = generator.generateToolTip(dataset, series, item); } String url = null; if (getURLGenerator() != null) { url = getURLGenerator().generateURL(dataset, series, item); } XYItemEntity entity = new XYItemEntity(hotspot, dataset, series, item, tip, url); entities.add(entity); } } } /** * Tests this renderer for equality with an arbitrary object. * * @param obj the object (<code>null</code> not permitted). * * @return A boolean. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof XYAreaRenderer2)) { return false; } XYAreaRenderer2 that = (XYAreaRenderer2) obj; if (this.showOutline != that.showOutline) { return false; } if (!ShapeUtilities.equal(this.legendArea, that.legendArea)) { return false; } return super.equals(obj); } /** * Returns a clone of the renderer. * * @return A clone. * * @throws CloneNotSupportedException if the renderer cannot be cloned. */ @Override public Object clone() throws CloneNotSupportedException { XYAreaRenderer2 clone = (XYAreaRenderer2) super.clone(); clone.legendArea = ShapeUtilities.clone(this.legendArea); return clone; } /** * Provides serialization support. * * @param stream the input stream. * * @throws IOException if there is an I/O error. * @throws ClassNotFoundException if there is a classpath problem. */ private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); this.legendArea = SerialUtilities.readShape(stream); } /** * Provides serialization support. * * @param stream the output stream. * * @throws IOException if there is an I/O error. */ private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); SerialUtilities.writeShape(this.legendArea, stream); } }
17,800
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
XYErrorRenderer.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/renderer/xy/XYErrorRenderer.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * -------------------- * XYErrorRenderer.java * -------------------- * (C) Copyright 2006-2012, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 25-Oct-2006 : Version 1 (DG); * 23-Mar-2007 : Check item visibility before drawing error bars - see bug * 1686178 (DG); * 28-Jan-2009 : Added stroke options for error indicators (DG); * 16-Jun-2012 : Removed JCommon dependencies (DG); * */ package org.jfree.chart.renderer.xy; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.Stroke; import java.awt.geom.Line2D; import java.awt.geom.Rectangle2D; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.ui.RectangleEdge; import org.jfree.chart.util.ObjectUtilities; import org.jfree.chart.util.PaintUtilities; import org.jfree.chart.event.RendererChangeEvent; import org.jfree.chart.plot.CrosshairState; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.PlotRenderingInfo; import org.jfree.chart.plot.XYPlot; import org.jfree.chart.util.SerialUtilities; import org.jfree.data.Range; import org.jfree.data.xy.IntervalXYDataset; import org.jfree.data.xy.XYDataset; /** * A line and shape renderer that can also display x and/or y-error values. * This renderer expects an {@link IntervalXYDataset}, otherwise it reverts * to the behaviour of the super class. The example shown here is generated by * the <code>XYErrorRendererDemo1.java</code> program included in the * JFreeChart demo collection: * <br><br> * <img src="../../../../../images/XYErrorRendererSample.png" * alt="XYErrorRendererSample.png" /> * * @since 1.0.3 */ public class XYErrorRenderer extends XYLineAndShapeRenderer { /** For serialization. */ static final long serialVersionUID = 5162283570955172424L; /** A flag that controls whether or not the x-error bars are drawn. */ private boolean drawXError; /** A flag that controls whether or not the y-error bars are drawn. */ private boolean drawYError; /** The length of the cap at the end of the error bars. */ private double capLength; /** * The paint used to draw the error bars (if <code>null</code> we use the * series paint). */ private transient Paint errorPaint; /** * The stroke used to draw the error bars (if <code>null</code> we use the * series outline stroke). * * @since 1.0.13 */ private transient Stroke errorStroke; /** * Creates a new <code>XYErrorRenderer</code> instance. */ public XYErrorRenderer() { super(false, true); this.drawXError = true; this.drawYError = true; this.errorPaint = null; this.errorStroke = null; this.capLength = 4.0; } /** * Returns the flag that controls whether or not the renderer draws error * bars for the x-values. * * @return A boolean. * * @see #setDrawXError(boolean) */ public boolean getDrawXError() { return this.drawXError; } /** * Sets the flag that controls whether or not the renderer draws error * bars for the x-values and, if the flag changes, sends a * {@link RendererChangeEvent} to all registered listeners. * * @param draw the flag value. * * @see #getDrawXError() */ public void setDrawXError(boolean draw) { if (this.drawXError != draw) { this.drawXError = draw; fireChangeEvent(); } } /** * Returns the flag that controls whether or not the renderer draws error * bars for the y-values. * * @return A boolean. * * @see #setDrawYError(boolean) */ public boolean getDrawYError() { return this.drawYError; } /** * Sets the flag that controls whether or not the renderer draws error * bars for the y-values and, if the flag changes, sends a * {@link RendererChangeEvent} to all registered listeners. * * @param draw the flag value. * * @see #getDrawYError() */ public void setDrawYError(boolean draw) { if (this.drawYError != draw) { this.drawYError = draw; fireChangeEvent(); } } /** * Returns the length (in Java2D units) of the cap at the end of the error * bars. * * @return The cap length. * * @see #setCapLength(double) */ public double getCapLength() { return this.capLength; } /** * Sets the length of the cap at the end of the error bars, and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param length the length (in Java2D units). * * @see #getCapLength() */ public void setCapLength(double length) { this.capLength = length; fireChangeEvent(); } /** * Returns the paint used to draw the error bars. If this is * <code>null</code> (the default), the item paint is used instead. * * @return The paint (possibly <code>null</code>). * * @see #setErrorPaint(Paint) */ public Paint getErrorPaint() { return this.errorPaint; } /** * Sets the paint used to draw the error bars and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param paint the paint (<code>null</code> permitted). * * @see #getErrorPaint() */ public void setErrorPaint(Paint paint) { this.errorPaint = paint; fireChangeEvent(); } /** * Returns the stroke used to draw the error bars. If this is * <code>null</code> (the default), the item outline stroke is used * instead. * * @return The stroke (possibly <code>null</code>). * * @see #setErrorStroke(Stroke) * * @since 1.0.13 */ public Stroke getErrorStroke() { return this.errorStroke; } /** * Sets the stroke used to draw the error bars and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param stroke the stroke (<code>null</code> permitted). * * @see #getErrorStroke() * * @since 1.0.13 */ public void setErrorStroke(Stroke stroke) { this.errorStroke = stroke; fireChangeEvent(); } /** * Returns the range required by this renderer to display all the domain * values in the specified dataset. * * @param dataset the dataset (<code>null</code> permitted). * * @return The range, or <code>null</code> if the dataset is * <code>null</code>. */ @Override public Range findDomainBounds(XYDataset dataset) { // include the interval if there is one return findDomainBounds(dataset, true); } /** * Returns the range required by this renderer to display all the range * values in the specified dataset. * * @param dataset the dataset (<code>null</code> permitted). * * @return The range, or <code>null</code> if the dataset is * <code>null</code>. */ @Override public Range findRangeBounds(XYDataset dataset) { // include the interval if there is one return findRangeBounds(dataset, true); } /** * Draws the visual representation for one data item. * * @param g2 the graphics output target. * @param state the renderer state. * @param dataArea the data area. * @param info the plot rendering info. * @param plot the plot. * @param domainAxis the domain axis. * @param rangeAxis the range axis. * @param dataset the dataset. * @param series the series index. * @param item the item index. * @param crosshairState the crosshair state. * @param pass the pass index. */ @Override public void drawItem(Graphics2D g2, XYItemRendererState state, Rectangle2D dataArea, PlotRenderingInfo info, XYPlot plot, ValueAxis domainAxis, ValueAxis rangeAxis, XYDataset dataset, int series, int item, CrosshairState crosshairState, int pass) { if (pass == 0 && dataset instanceof IntervalXYDataset && getItemVisible(series, item)) { IntervalXYDataset ixyd = (IntervalXYDataset) dataset; PlotOrientation orientation = plot.getOrientation(); if (this.drawXError) { // draw the error bar for the x-interval double x0 = ixyd.getStartXValue(series, item); double x1 = ixyd.getEndXValue(series, item); double y = ixyd.getYValue(series, item); RectangleEdge edge = plot.getDomainAxisEdge(); double xx0 = domainAxis.valueToJava2D(x0, dataArea, edge); double xx1 = domainAxis.valueToJava2D(x1, dataArea, edge); double yy = rangeAxis.valueToJava2D(y, dataArea, plot.getRangeAxisEdge()); Line2D line; Line2D cap1 = null; Line2D cap2 = null; double adj = this.capLength / 2.0; if (orientation == PlotOrientation.VERTICAL) { line = new Line2D.Double(xx0, yy, xx1, yy); cap1 = new Line2D.Double(xx0, yy - adj, xx0, yy + adj); cap2 = new Line2D.Double(xx1, yy - adj, xx1, yy + adj); } else { // PlotOrientation.HORIZONTAL line = new Line2D.Double(yy, xx0, yy, xx1); cap1 = new Line2D.Double(yy - adj, xx0, yy + adj, xx0); cap2 = new Line2D.Double(yy - adj, xx1, yy + adj, xx1); } if (this.errorPaint != null) { g2.setPaint(this.errorPaint); } else { g2.setPaint(getItemPaint(series, item)); } if (this.errorStroke != null) { g2.setStroke(this.errorStroke); } else { g2.setStroke(getItemStroke(series, item)); } g2.draw(line); g2.draw(cap1); g2.draw(cap2); } if (this.drawYError) { // draw the error bar for the y-interval double y0 = ixyd.getStartYValue(series, item); double y1 = ixyd.getEndYValue(series, item); double x = ixyd.getXValue(series, item); RectangleEdge edge = plot.getRangeAxisEdge(); double yy0 = rangeAxis.valueToJava2D(y0, dataArea, edge); double yy1 = rangeAxis.valueToJava2D(y1, dataArea, edge); double xx = domainAxis.valueToJava2D(x, dataArea, plot.getDomainAxisEdge()); Line2D line; Line2D cap1 = null; Line2D cap2 = null; double adj = this.capLength / 2.0; if (orientation == PlotOrientation.VERTICAL) { line = new Line2D.Double(xx, yy0, xx, yy1); cap1 = new Line2D.Double(xx - adj, yy0, xx + adj, yy0); cap2 = new Line2D.Double(xx - adj, yy1, xx + adj, yy1); } else { // PlotOrientation.HORIZONTAL line = new Line2D.Double(yy0, xx, yy1, xx); cap1 = new Line2D.Double(yy0, xx - adj, yy0, xx + adj); cap2 = new Line2D.Double(yy1, xx - adj, yy1, xx + adj); } if (this.errorPaint != null) { g2.setPaint(this.errorPaint); } else { g2.setPaint(getItemPaint(series, item)); } if (this.errorStroke != null) { g2.setStroke(this.errorStroke); } else { g2.setStroke(getItemStroke(series, item)); } g2.draw(line); g2.draw(cap1); g2.draw(cap2); } } super.drawItem(g2, state, dataArea, info, plot, domainAxis, rangeAxis, dataset, series, item, crosshairState, pass); } /** * Tests this instance for equality with an arbitrary object. * * @param obj the object (<code>null</code> permitted). * * @return A boolean. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof XYErrorRenderer)) { return false; } XYErrorRenderer that = (XYErrorRenderer) obj; if (this.drawXError != that.drawXError) { return false; } if (this.drawYError != that.drawYError) { return false; } if (this.capLength != that.capLength) { return false; } if (!PaintUtilities.equal(this.errorPaint, that.errorPaint)) { return false; } if (!ObjectUtilities.equal(this.errorStroke, that.errorStroke)) { return false; } return super.equals(obj); } /** * Provides serialization support. * * @param stream the input stream. * * @throws IOException if there is an I/O error. * @throws ClassNotFoundException if there is a classpath problem. */ private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); this.errorPaint = SerialUtilities.readPaint(stream); this.errorStroke = SerialUtilities.readStroke(stream); } /** * Provides serialization support. * * @param stream the output stream. * * @throws IOException if there is an I/O error. */ private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); SerialUtilities.writePaint(this.errorPaint, stream); SerialUtilities.writeStroke(this.errorStroke, stream); } }
15,599
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
XYLine3DRenderer.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/renderer/xy/XYLine3DRenderer.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * --------------------- * XYLine3DRenderer.java * --------------------- * (C) Copyright 2005-2012, by Object Refinery Limited. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * Changes * ------- * 14-Jan-2005 : Added standard header (DG); * 01-May-2007 : Fixed equals() and serialization bugs (DG); * 17-Jun-2012 : Removed JCommon dependencies (DG); * */ package org.jfree.chart.renderer.xy; import java.awt.Color; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.Shape; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import org.jfree.chart.Effect3D; import org.jfree.chart.util.PaintUtilities; import org.jfree.chart.event.RendererChangeEvent; import org.jfree.chart.util.SerialUtilities; /** * A XYLineAndShapeRenderer that adds a shadow line to the graph * to emulate a 3D-effect. */ public class XYLine3DRenderer extends XYLineAndShapeRenderer implements Effect3D, Serializable { /** For serialization. */ private static final long serialVersionUID = 588933208243446087L; /** The default x-offset for the 3D effect. */ public static final double DEFAULT_X_OFFSET = 12.0; /** The default y-offset for the 3D effect. */ public static final double DEFAULT_Y_OFFSET = 8.0; /** The default wall paint. */ public static final Paint DEFAULT_WALL_PAINT = new Color(0xDD, 0xDD, 0xDD); /** The size of x-offset for the 3D effect. */ private double xOffset; /** The size of y-offset for the 3D effect. */ private double yOffset; /** The paint used to shade the left and lower 3D wall. */ private transient Paint wallPaint; /** * Creates a new renderer. */ public XYLine3DRenderer() { this.wallPaint = DEFAULT_WALL_PAINT; this.xOffset = DEFAULT_X_OFFSET; this.yOffset = DEFAULT_Y_OFFSET; } /** * Returns the x-offset for the 3D effect. * * @return The 3D effect. */ @Override public double getXOffset() { return this.xOffset; } /** * Returns the y-offset for the 3D effect. * * @return The 3D effect. */ @Override public double getYOffset() { return this.yOffset; } /** * Sets the x-offset and sends a {@link RendererChangeEvent} to all * registered listeners. * * @param xOffset the x-offset. */ public void setXOffset(double xOffset) { this.xOffset = xOffset; fireChangeEvent(); } /** * Sets the y-offset and sends a {@link RendererChangeEvent} to all * registered listeners. * * @param yOffset the y-offset. */ public void setYOffset(double yOffset) { this.yOffset = yOffset; fireChangeEvent(); } /** * Returns the paint used to highlight the left and bottom wall in the plot * background. * * @return The paint. */ public Paint getWallPaint() { return this.wallPaint; } /** * Sets the paint used to hightlight the left and bottom walls in the plot * background and sends a {@link RendererChangeEvent} to all registered * listeners. * * @param paint the paint. */ public void setWallPaint(Paint paint) { this.wallPaint = paint; fireChangeEvent(); } /** * Returns the number of passes through the data that the renderer requires * in order to draw the chart. Most charts will require a single pass, * but some require two passes. * * @return The pass count. */ @Override public int getPassCount() { return 3; } /** * Returns <code>true</code> if the specified pass involves drawing lines. * * @param pass the pass. * * @return A boolean. */ @Override protected boolean isLinePass(int pass) { return pass == 0 || pass == 1; } /** * Returns <code>true</code> if the specified pass involves drawing items. * * @param pass the pass. * * @return A boolean. */ @Override protected boolean isItemPass(int pass) { return pass == 2; } /** * Returns <code>true</code> if the specified pass involves drawing shadows. * * @param pass the pass. * * @return A boolean. */ protected boolean isShadowPass (int pass) { return pass == 0; } /** * Overrides the method in the subclass to draw a shadow in the first pass. * * @param g2 the graphics device. * @param pass the pass. * @param series the series index (zero-based). * @param item the item index (zero-based). * @param shape the shape. */ @Override protected void drawFirstPassShape(Graphics2D g2, int pass, int series, int item, Shape shape) { if (isShadowPass(pass)) { if (getWallPaint() != null) { g2.setStroke(getItemStroke(series, item)); g2.setPaint(getWallPaint()); g2.translate(getXOffset(), getYOffset()); g2.draw(shape); g2.translate(-getXOffset(), -getYOffset()); } } else { // now draw the real shape super.drawFirstPassShape(g2, pass, series, item, shape); } } /** * Tests this renderer for equality with an arbitrary object. * * @param obj the object (<code>null</code> permitted). * * @return A boolean. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof XYLine3DRenderer)) { return false; } XYLine3DRenderer that = (XYLine3DRenderer) obj; if (this.xOffset != that.xOffset) { return false; } if (this.yOffset != that.yOffset) { return false; } if (!PaintUtilities.equal(this.wallPaint, that.wallPaint)) { return false; } return super.equals(obj); } /** * Provides serialization support. * * @param stream the input stream. * * @throws IOException if there is an I/O error. * @throws ClassNotFoundException if there is a classpath problem. */ private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); this.wallPaint = SerialUtilities.readPaint(stream); } /** * Provides serialization support. * * @param stream the output stream. * * @throws IOException if there is an I/O error. */ private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); SerialUtilities.writePaint(this.wallPaint, stream); } }
8,392
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
XYBoxAndWhiskerRenderer.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/renderer/xy/XYBoxAndWhiskerRenderer.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ---------------------------- * XYBoxAndWhiskerRenderer.java * ---------------------------- * (C) Copyright 2003-2012, by David Browning and Contributors. * * Original Author: David Browning (for Australian Institute of Marine * Science); * Contributor(s): David Gilbert (for Object Refinery Limited); * * Changes * ------- * 05-Aug-2003 : Version 1, contributed by David Browning. Based on code in the * CandlestickRenderer class. Additional modifications by David * Gilbert to make the code work with 0.9.10 changes (DG); * 08-Aug-2003 : Updated some of the Javadoc * Allowed BoxAndwhiskerDataset Average value to be null - the * average value is an AIMS requirement * Allow the outlier and farout coefficients to be set - though * at the moment this only affects the calculation of farouts. * Added artifactPaint variable and setter/getter * 12-Aug-2003 Rewrote code to sort out and process outliers to take * advantage of changes in DefaultBoxAndWhiskerDataset * Added a limit of 10% for width of box should no width be * specified...maybe this should be setable??? * 20-Aug-2003 : Implemented Cloneable and PublicCloneable (DG); * 08-Sep-2003 : Changed ValueAxis API (DG); * 16-Sep-2003 : Changed ChartRenderingInfo --> PlotRenderingInfo (DG); * 25-Feb-2004 : Replaced CrosshairInfo with CrosshairState (DG); * 23-Apr-2004 : Added fillBox attribute, extended equals() method and fixed * serialization issue (DG); * 29-Apr-2004 : Fixed problem with drawing upper and lower shadows - bug id * 944011 (DG); * 15-Jul-2004 : Switched getX() with getXValue() and getY() with * getYValue() (DG); * 01-Oct-2004 : Renamed 'paint' --> 'boxPaint' to avoid conflict with * inherited attribute (DG); * 10-Jun-2005 : Updated equals() to handle GradientPaint (DG); * 06-Oct-2005 : Removed setPaint() call in drawItem(), it is causing a * loop (DG); * ------------- JFREECHART 1.0.x --------------------------------------------- * 02-Feb-2007 : Removed author tags from all over JFreeChart sources (DG); * 05-Feb-2007 : Added event notifications and fixed drawing for horizontal * plot orientation (DG); * 13-Jun-2007 : Replaced deprecated method call (DG); * 03-Jan-2008 : Check visibility of average marker before drawing it (DG); * 27-Mar-2008 : If boxPaint is null, revert to itemPaint (DG); * 27-Mar-2009 : Added findRangeBounds() method override (DG); * 08-Dec-2009 : Fix for bug 2909215, NullPointerException for null * outliers (DG); * 16-Jun-2012 : Removed JCommon dependencies (DG); * */ package org.jfree.chart.renderer.xy; import java.awt.Color; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.Shape; import java.awt.Stroke; import java.awt.geom.Ellipse2D; import java.awt.geom.Line2D; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.ui.RectangleEdge; import org.jfree.chart.util.PaintUtilities; import org.jfree.chart.util.PublicCloneable; import org.jfree.chart.entity.EntityCollection; import org.jfree.chart.event.RendererChangeEvent; import org.jfree.chart.labels.BoxAndWhiskerXYToolTipGenerator; import org.jfree.chart.plot.CrosshairState; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.PlotRenderingInfo; import org.jfree.chart.plot.XYPlot; import org.jfree.chart.renderer.Outlier; import org.jfree.chart.renderer.OutlierList; import org.jfree.chart.renderer.OutlierListCollection; import org.jfree.chart.util.SerialUtilities; import org.jfree.data.Range; import org.jfree.data.statistics.BoxAndWhiskerXYDataset; import org.jfree.data.xy.XYDataset; /** * A renderer that draws box-and-whisker items on an {@link XYPlot}. This * renderer requires a {@link BoxAndWhiskerXYDataset}). The example shown here * is generated by the <code>BoxAndWhiskerChartDemo2.java</code> program * included in the JFreeChart demo collection: * <br><br> * <img src="../../../../../images/XYBoxAndWhiskerRendererSample.png" * alt="XYBoxAndWhiskerRendererSample.png" /> * <P> * This renderer does not include any code to calculate the crosshair point. */ public class XYBoxAndWhiskerRenderer extends AbstractXYItemRenderer implements XYItemRenderer, Cloneable, PublicCloneable, Serializable { /** For serialization. */ private static final long serialVersionUID = -8020170108532232324L; /** The box width. */ private double boxWidth; /** The paint used to fill the box. */ private transient Paint boxPaint; /** A flag that controls whether or not the box is filled. */ private boolean fillBox; /** * The paint used to draw various artifacts such as outliers, farout * symbol, average ellipse and median line. */ private transient Paint artifactPaint = Color.BLACK; /** * Creates a new renderer for box and whisker charts. */ public XYBoxAndWhiskerRenderer() { this(-1.0); } /** * Creates a new renderer for box and whisker charts. * <P> * Use -1 for the box width if you prefer the width to be calculated * automatically. * * @param boxWidth the box width. */ public XYBoxAndWhiskerRenderer(double boxWidth) { super(); this.boxWidth = boxWidth; this.boxPaint = Color.GREEN; this.fillBox = true; setDefaultToolTipGenerator(new BoxAndWhiskerXYToolTipGenerator()); } /** * Returns the width of each box. * * @return The box width. * * @see #setBoxWidth(double) */ public double getBoxWidth() { return this.boxWidth; } /** * Sets the box width and sends a {@link RendererChangeEvent} to all * registered listeners. * <P> * If you set the width to a negative value, the renderer will calculate * the box width automatically based on the space available on the chart. * * @param width the width. * * @see #getBoxWidth() */ public void setBoxWidth(double width) { if (width != this.boxWidth) { this.boxWidth = width; fireChangeEvent(); } } /** * Returns the paint used to fill boxes. * * @return The paint (possibly <code>null</code>). * * @see #setBoxPaint(Paint) */ public Paint getBoxPaint() { return this.boxPaint; } /** * Sets the paint used to fill boxes and sends a {@link RendererChangeEvent} * to all registered listeners. * * @param paint the paint (<code>null</code> permitted). * * @see #getBoxPaint() */ public void setBoxPaint(Paint paint) { this.boxPaint = paint; fireChangeEvent(); } /** * Returns the flag that controls whether or not the box is filled. * * @return A boolean. * * @see #setFillBox(boolean) */ public boolean getFillBox() { return this.fillBox; } /** * Sets the flag that controls whether or not the box is filled and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param flag the flag. * * @see #setFillBox(boolean) */ public void setFillBox(boolean flag) { this.fillBox = flag; fireChangeEvent(); } /** * Returns the paint used to paint the various artifacts such as outliers, * farout symbol, median line and the averages ellipse. * * @return The paint (never <code>null</code>). * * @see #setArtifactPaint(Paint) */ public Paint getArtifactPaint() { return this.artifactPaint; } /** * Sets the paint used to paint the various artifacts such as outliers, * farout symbol, median line and the averages ellipse, and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param paint the paint (<code>null</code> not permitted). * * @see #getArtifactPaint() */ public void setArtifactPaint(Paint paint) { if (paint == null) { throw new IllegalArgumentException("Null 'paint' argument."); } this.artifactPaint = paint; fireChangeEvent(); } /** * Returns the range of values the renderer requires to display all the * items from the specified dataset. * * @param dataset the dataset (<code>null</code> permitted). * * @return The range (<code>null</code> if the dataset is <code>null</code> * or empty). * * @see #findDomainBounds(XYDataset) */ @Override public Range findRangeBounds(XYDataset dataset) { return findRangeBounds(dataset, true); } /** * Returns the box paint or, if this is <code>null</code>, the item * paint. * * @param series the series index. * @param item the item index. * * @return The paint used to fill the box for the specified item (never * <code>null</code>). * * @since 1.0.10 */ protected Paint lookupBoxPaint(int series, int item) { Paint p = getBoxPaint(); if (p != null) { return p; } else { // TODO: could change this to itemFillPaint(). For backwards // compatibility, it might require a useFillPaint flag. return getItemPaint(series, item); } } /** * Draws the visual representation of a single data item. * * @param g2 the graphics device. * @param state the renderer state. * @param dataArea the area within which the plot is being drawn. * @param info collects info about the drawing. * @param plot the plot (can be used to obtain standard color * information etc). * @param domainAxis the domain axis. * @param rangeAxis the range axis. * @param dataset the dataset (must be an instance of * {@link BoxAndWhiskerXYDataset}). * @param series the series index (zero-based). * @param item the item index (zero-based). * @param crosshairState crosshair information for the plot * (<code>null</code> permitted). * @param pass the pass index. */ @Override public void drawItem(Graphics2D g2, XYItemRendererState state, Rectangle2D dataArea, PlotRenderingInfo info, XYPlot plot, ValueAxis domainAxis, ValueAxis rangeAxis, XYDataset dataset, int series, int item, CrosshairState crosshairState, int pass) { PlotOrientation orientation = plot.getOrientation(); if (orientation == PlotOrientation.HORIZONTAL) { drawHorizontalItem(g2, dataArea, info, plot, domainAxis, rangeAxis, dataset, series, item, crosshairState, pass); } else if (orientation == PlotOrientation.VERTICAL) { drawVerticalItem(g2, dataArea, info, plot, domainAxis, rangeAxis, dataset, series, item, crosshairState, pass); } } /** * Draws the visual representation of a single data item. * * @param g2 the graphics device. * @param dataArea the area within which the plot is being drawn. * @param info collects info about the drawing. * @param plot the plot (can be used to obtain standard color * information etc). * @param domainAxis the domain axis. * @param rangeAxis the range axis. * @param dataset the dataset (must be an instance of * {@link BoxAndWhiskerXYDataset}). * @param series the series index (zero-based). * @param item the item index (zero-based). * @param crosshairState crosshair information for the plot * (<code>null</code> permitted). * @param pass the pass index. */ public void drawHorizontalItem(Graphics2D g2, Rectangle2D dataArea, PlotRenderingInfo info, XYPlot plot, ValueAxis domainAxis, ValueAxis rangeAxis, XYDataset dataset, int series, int item, CrosshairState crosshairState, int pass) { // setup for collecting optional entity info... EntityCollection entities = null; if (info != null) { entities = info.getOwner().getEntityCollection(); } BoxAndWhiskerXYDataset boxAndWhiskerData = (BoxAndWhiskerXYDataset) dataset; Number x = boxAndWhiskerData.getX(series, item); Number yMax = boxAndWhiskerData.getMaxRegularValue(series, item); Number yMin = boxAndWhiskerData.getMinRegularValue(series, item); Number yMedian = boxAndWhiskerData.getMedianValue(series, item); Number yAverage = boxAndWhiskerData.getMeanValue(series, item); Number yQ1Median = boxAndWhiskerData.getQ1Value(series, item); Number yQ3Median = boxAndWhiskerData.getQ3Value(series, item); double xx = domainAxis.valueToJava2D(x.doubleValue(), dataArea, plot.getDomainAxisEdge()); RectangleEdge location = plot.getRangeAxisEdge(); double yyMax = rangeAxis.valueToJava2D(yMax.doubleValue(), dataArea, location); double yyMin = rangeAxis.valueToJava2D(yMin.doubleValue(), dataArea, location); double yyMedian = rangeAxis.valueToJava2D(yMedian.doubleValue(), dataArea, location); double yyAverage = 0.0; if (yAverage != null) { yyAverage = rangeAxis.valueToJava2D(yAverage.doubleValue(), dataArea, location); } double yyQ1Median = rangeAxis.valueToJava2D(yQ1Median.doubleValue(), dataArea, location); double yyQ3Median = rangeAxis.valueToJava2D(yQ3Median.doubleValue(), dataArea, location); double exactBoxWidth = getBoxWidth(); double width = exactBoxWidth; double dataAreaX = dataArea.getHeight(); double maxBoxPercent = 0.1; double maxBoxWidth = dataAreaX * maxBoxPercent; if (exactBoxWidth <= 0.0) { int itemCount = boxAndWhiskerData.getItemCount(series); exactBoxWidth = dataAreaX / itemCount * 4.5 / 7; if (exactBoxWidth < 3) { width = 3; } else if (exactBoxWidth > maxBoxWidth) { width = maxBoxWidth; } else { width = exactBoxWidth; } } g2.setPaint(getItemPaint(series, item)); Stroke s = getItemStroke(series, item); g2.setStroke(s); // draw the upper shadow g2.draw(new Line2D.Double(yyMax, xx, yyQ3Median, xx)); g2.draw(new Line2D.Double(yyMax, xx - width / 2, yyMax, xx + width / 2)); // draw the lower shadow g2.draw(new Line2D.Double(yyMin, xx, yyQ1Median, xx)); g2.draw(new Line2D.Double(yyMin, xx - width / 2, yyMin, xx + width / 2)); // draw the body Shape box; if (yyQ1Median < yyQ3Median) { box = new Rectangle2D.Double(yyQ1Median, xx - width / 2, yyQ3Median - yyQ1Median, width); } else { box = new Rectangle2D.Double(yyQ3Median, xx - width / 2, yyQ1Median - yyQ3Median, width); } if (this.fillBox) { g2.setPaint(lookupBoxPaint(series, item)); g2.fill(box); } g2.setStroke(getItemOutlineStroke(series, item)); g2.setPaint(getItemOutlinePaint(series, item)); g2.draw(box); // draw median g2.setPaint(getArtifactPaint()); g2.draw(new Line2D.Double(yyMedian, xx - width / 2, yyMedian, xx + width / 2)); // draw average - SPECIAL AIMS REQUIREMENT if (yAverage != null) { double aRadius = width / 4; // here we check that the average marker will in fact be visible // before drawing it... if ((yyAverage > (dataArea.getMinX() - aRadius)) && (yyAverage < (dataArea.getMaxX() + aRadius))) { Ellipse2D.Double avgEllipse = new Ellipse2D.Double( yyAverage - aRadius, xx - aRadius, aRadius * 2, aRadius * 2); g2.fill(avgEllipse); g2.draw(avgEllipse); } } // FIXME: draw outliers // add an entity for the item... if (entities != null && box.intersects(dataArea)) { addEntity(entities, box, dataset, series, item, yyAverage, xx); } } /** * Draws the visual representation of a single data item. * * @param g2 the graphics device. * @param dataArea the area within which the plot is being drawn. * @param info collects info about the drawing. * @param plot the plot (can be used to obtain standard color * information etc). * @param domainAxis the domain axis. * @param rangeAxis the range axis. * @param dataset the dataset (must be an instance of * {@link BoxAndWhiskerXYDataset}). * @param series the series index (zero-based). * @param item the item index (zero-based). * @param crosshairState crosshair information for the plot * (<code>null</code> permitted). * @param pass the pass index. */ public void drawVerticalItem(Graphics2D g2, Rectangle2D dataArea, PlotRenderingInfo info, XYPlot plot, ValueAxis domainAxis, ValueAxis rangeAxis, XYDataset dataset, int series, int item, CrosshairState crosshairState, int pass) { // setup for collecting optional entity info... EntityCollection entities = null; if (info != null) { entities = info.getOwner().getEntityCollection(); } BoxAndWhiskerXYDataset boxAndWhiskerData = (BoxAndWhiskerXYDataset) dataset; Number x = boxAndWhiskerData.getX(series, item); Number yMax = boxAndWhiskerData.getMaxRegularValue(series, item); Number yMin = boxAndWhiskerData.getMinRegularValue(series, item); Number yMedian = boxAndWhiskerData.getMedianValue(series, item); Number yAverage = boxAndWhiskerData.getMeanValue(series, item); Number yQ1Median = boxAndWhiskerData.getQ1Value(series, item); Number yQ3Median = boxAndWhiskerData.getQ3Value(series, item); List<Number> yOutliers = boxAndWhiskerData.getOutliers(series, item); // yOutliers can be null, but we'd prefer it to be an empty list in // that case... if (yOutliers == null) { yOutliers = Collections.EMPTY_LIST; } double xx = domainAxis.valueToJava2D(x.doubleValue(), dataArea, plot.getDomainAxisEdge()); RectangleEdge location = plot.getRangeAxisEdge(); double yyMax = rangeAxis.valueToJava2D(yMax.doubleValue(), dataArea, location); double yyMin = rangeAxis.valueToJava2D(yMin.doubleValue(), dataArea, location); double yyMedian = rangeAxis.valueToJava2D(yMedian.doubleValue(), dataArea, location); double yyAverage = 0.0; if (yAverage != null) { yyAverage = rangeAxis.valueToJava2D(yAverage.doubleValue(), dataArea, location); } double yyQ1Median = rangeAxis.valueToJava2D(yQ1Median.doubleValue(), dataArea, location); double yyQ3Median = rangeAxis.valueToJava2D(yQ3Median.doubleValue(), dataArea, location); double yyOutlier; double exactBoxWidth = getBoxWidth(); double width = exactBoxWidth; double dataAreaX = dataArea.getMaxX() - dataArea.getMinX(); double maxBoxPercent = 0.1; double maxBoxWidth = dataAreaX * maxBoxPercent; if (exactBoxWidth <= 0.0) { int itemCount = boxAndWhiskerData.getItemCount(series); exactBoxWidth = dataAreaX / itemCount * 4.5 / 7; if (exactBoxWidth < 3) { width = 3; } else if (exactBoxWidth > maxBoxWidth) { width = maxBoxWidth; } else { width = exactBoxWidth; } } g2.setPaint(getItemPaint(series, item)); Stroke s = getItemStroke(series, item); g2.setStroke(s); // draw the upper shadow g2.draw(new Line2D.Double(xx, yyMax, xx, yyQ3Median)); g2.draw(new Line2D.Double(xx - width / 2, yyMax, xx + width / 2, yyMax)); // draw the lower shadow g2.draw(new Line2D.Double(xx, yyMin, xx, yyQ1Median)); g2.draw(new Line2D.Double(xx - width / 2, yyMin, xx + width / 2, yyMin)); // draw the body Shape box; if (yyQ1Median > yyQ3Median) { box = new Rectangle2D.Double(xx - width / 2, yyQ3Median, width, yyQ1Median - yyQ3Median); } else { box = new Rectangle2D.Double(xx - width / 2, yyQ1Median, width, yyQ3Median - yyQ1Median); } if (this.fillBox) { g2.setPaint(lookupBoxPaint(series, item)); g2.fill(box); } g2.setStroke(getItemOutlineStroke(series, item)); g2.setPaint(getItemOutlinePaint(series, item)); g2.draw(box); // draw median g2.setPaint(getArtifactPaint()); g2.draw(new Line2D.Double(xx - width / 2, yyMedian, xx + width / 2, yyMedian)); double aRadius = 0; // average radius double oRadius = width / 3; // outlier radius // draw average - SPECIAL AIMS REQUIREMENT if (yAverage != null) { aRadius = width / 4; // here we check that the average marker will in fact be visible // before drawing it... if ((yyAverage > (dataArea.getMinY() - aRadius)) && (yyAverage < (dataArea.getMaxY() + aRadius))) { Ellipse2D.Double avgEllipse = new Ellipse2D.Double(xx - aRadius, yyAverage - aRadius, aRadius * 2, aRadius * 2); g2.fill(avgEllipse); g2.draw(avgEllipse); } } List<Outlier> outliers = new ArrayList<Outlier>(); OutlierListCollection outlierListCollection = new OutlierListCollection(); /* From outlier array sort out which are outliers and put these into * an arraylist. If there are any farouts, set the flag on the * OutlierListCollection */ for (Number yOutlier : yOutliers) { double outlier = yOutlier.doubleValue(); if (outlier > boxAndWhiskerData.getMaxOutlier(series, item).doubleValue()) { outlierListCollection.setHighFarOut(true); } else if (outlier < boxAndWhiskerData.getMinOutlier(series, item).doubleValue()) { outlierListCollection.setLowFarOut(true); } else if (outlier > boxAndWhiskerData.getMaxRegularValue(series, item).doubleValue()) { yyOutlier = rangeAxis.valueToJava2D(outlier, dataArea, location); outliers.add(new Outlier(xx, yyOutlier, oRadius)); } else if (outlier < boxAndWhiskerData.getMinRegularValue(series, item).doubleValue()) { yyOutlier = rangeAxis.valueToJava2D(outlier, dataArea, location); outliers.add(new Outlier(xx, yyOutlier, oRadius)); } Collections.sort(outliers); } // Process outliers. Each outlier is either added to the appropriate // outlier list or a new outlier list is made for (Outlier outlier : outliers) { outlierListCollection.add(outlier); } // draw yOutliers double maxAxisValue = rangeAxis.valueToJava2D(rangeAxis.getUpperBound(), dataArea, location) + aRadius; double minAxisValue = rangeAxis.valueToJava2D(rangeAxis.getLowerBound(), dataArea, location) - aRadius; // draw outliers for (OutlierList list : outlierListCollection) { Outlier outlier = list.getAveragedOutlier(); Point2D point = outlier.getPoint(); if (list.isMultiple()) { drawMultipleEllipse(point, width, oRadius, g2); } else { drawEllipse(point, oRadius, g2); } } // draw farout if (outlierListCollection.isHighFarOut()) { drawHighFarOut(aRadius, g2, xx, maxAxisValue); } if (outlierListCollection.isLowFarOut()) { drawLowFarOut(aRadius, g2, xx, minAxisValue); } // add an entity for the item... if (entities != null && box.intersects(dataArea)) { addEntity(entities, box, dataset, series, item, xx, yyAverage); } } /** * Draws an ellipse to represent an outlier. * * @param point the location. * @param oRadius the radius. * @param g2 the graphics device. */ protected void drawEllipse(Point2D point, double oRadius, Graphics2D g2) { Ellipse2D.Double dot = new Ellipse2D.Double(point.getX() + oRadius / 2, point.getY(), oRadius, oRadius); g2.draw(dot); } /** * Draws two ellipses to represent overlapping outliers. * * @param point the location. * @param boxWidth the box width. * @param oRadius the radius. * @param g2 the graphics device. */ protected void drawMultipleEllipse(Point2D point, double boxWidth, double oRadius, Graphics2D g2) { Ellipse2D.Double dot1 = new Ellipse2D.Double(point.getX() - (boxWidth / 2) + oRadius, point.getY(), oRadius, oRadius); Ellipse2D.Double dot2 = new Ellipse2D.Double(point.getX() + (boxWidth / 2), point.getY(), oRadius, oRadius); g2.draw(dot1); g2.draw(dot2); } /** * Draws a triangle to indicate the presence of far out values. * * @param aRadius the radius. * @param g2 the graphics device. * @param xx the x value. * @param m the max y value. */ protected void drawHighFarOut(double aRadius, Graphics2D g2, double xx, double m) { double side = aRadius * 2; g2.draw(new Line2D.Double(xx - side, m + side, xx + side, m + side)); g2.draw(new Line2D.Double(xx - side, m + side, xx, m)); g2.draw(new Line2D.Double(xx + side, m + side, xx, m)); } /** * Draws a triangle to indicate the presence of far out values. * * @param aRadius the radius. * @param g2 the graphics device. * @param xx the x value. * @param m the min y value. */ protected void drawLowFarOut(double aRadius, Graphics2D g2, double xx, double m) { double side = aRadius * 2; g2.draw(new Line2D.Double(xx - side, m - side, xx + side, m - side)); g2.draw(new Line2D.Double(xx - side, m - side, xx, m)); g2.draw(new Line2D.Double(xx + side, m - side, xx, m)); } /** * Tests this renderer for equality with another object. * * @param obj the object (<code>null</code> permitted). * * @return <code>true</code> or <code>false</code>. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof XYBoxAndWhiskerRenderer)) { return false; } if (!super.equals(obj)) { return false; } XYBoxAndWhiskerRenderer that = (XYBoxAndWhiskerRenderer) obj; if (this.boxWidth != that.getBoxWidth()) { return false; } if (!PaintUtilities.equal(this.boxPaint, that.boxPaint)) { return false; } if (!PaintUtilities.equal(this.artifactPaint, that.artifactPaint)) { return false; } if (this.fillBox != that.fillBox) { return false; } return true; } /** * Provides serialization support. * * @param stream the output stream. * * @throws IOException if there is an I/O error. */ private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); SerialUtilities.writePaint(this.boxPaint, stream); SerialUtilities.writePaint(this.artifactPaint, stream); } /** * Provides serialization support. * * @param stream the input stream. * * @throws IOException if there is an I/O error. * @throws ClassNotFoundException if there is a classpath problem. */ private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); this.boxPaint = SerialUtilities.readPaint(stream); this.artifactPaint = SerialUtilities.readPaint(stream); } /** * Returns a clone of the renderer. * * @return A clone. * * @throws CloneNotSupportedException if the renderer cannot be cloned. */ @Override public Object clone() throws CloneNotSupportedException { return super.clone(); } }
31,413
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
XYLineAndShapeRenderer.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/renderer/xy/XYLineAndShapeRenderer.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * --------------------------- * XYLineAndShapeRenderer.java * --------------------------- * (C) Copyright 2004-2012, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes: * -------- * 27-Jan-2004 : Version 1 (DG); * 10-Feb-2004 : Minor change to drawItem() method to make cut-and-paste * overriding easier (DG); * 25-Feb-2004 : Replaced CrosshairInfo with CrosshairState (DG); * 25-Aug-2004 : Added support for chart entities (required for tooltips) (DG); * 24-Sep-2004 : Added flag to allow whole series to be drawn as a path * (necessary when using a dashed stroke with many data * items) (DG); * 04-Oct-2004 : Renamed BooleanUtils --> BooleanUtilities (DG); * 11-Nov-2004 : Now uses ShapeUtilities to translate shapes (DG); * 27-Jan-2005 : The getLegendItem() method now omits hidden series (DG); * 28-Jan-2005 : Added new constructor (DG); * 09-Mar-2005 : Added fillPaint settings (DG); * 20-Apr-2005 : Use generators for legend tooltips and URLs (DG); * 22-Jul-2005 : Renamed defaultLinesVisible --> baseLinesVisible, * defaultShapesVisible --> baseShapesVisible and * defaultShapesFilled --> baseShapesFilled (DG); * 29-Jul-2005 : Added code to draw item labels (DG); * ------------- JFREECHART 1.0.x --------------------------------------------- * 20-Jul-2006 : Set dataset and series indices in LegendItem (DG); * 06-Feb-2007 : Fixed bug 1086307, crosshairs with multiple axes (DG); * 21-Feb-2007 : Fixed bugs in clone() and equals() (DG); * 20-Apr-2007 : Updated getLegendItem() for renderer change (DG); * 18-May-2007 : Set dataset and seriesKey for LegendItem (DG); * 08-Jun-2007 : Fix for bug 1731912 where entities are created even for data * items that are not displayed (DG); * 26-Oct-2007 : Deprecated override attributes (DG); * 02-Jun-2008 : Fixed tooltips at lower edges of data area (DG); * 17-Jun-2008 : Apply legend shape, font and paint attributes (DG); * 19-Sep-2008 : Fixed bug with drawSeriesLineAsPath - patch by Greg Darke (DG); * 18-May-2009 : Clip lines in drawPrimaryLine() (DG); * 15-Jun-2012 : Removed JCommon dependencies (DG); * 01-Jul-2012 : Remove deprecated code (DG); * */ package org.jfree.chart.renderer.xy; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.Shape; import java.awt.Stroke; import java.awt.geom.GeneralPath; import java.awt.geom.Line2D; import java.awt.geom.Rectangle2D; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import org.jfree.chart.LegendItem; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.ui.RectangleEdge; import org.jfree.chart.util.BooleanList; import org.jfree.chart.util.ObjectUtilities; import org.jfree.chart.util.PublicCloneable; import org.jfree.chart.util.ShapeUtilities; import org.jfree.chart.entity.EntityCollection; import org.jfree.chart.event.RendererChangeEvent; import org.jfree.chart.plot.CrosshairState; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.PlotRenderingInfo; import org.jfree.chart.plot.XYPlot; import org.jfree.chart.util.LineUtilities; import org.jfree.chart.util.SerialUtilities; import org.jfree.data.xy.XYDataset; /** * A renderer that connects data points with lines and/or draws shapes at each * data point. This renderer is designed for use with the {@link XYPlot} * class. The example shown here is generated by * the <code>XYLineAndShapeRendererDemo2.java</code> program included in the * JFreeChart demo collection: * <br><br> * <img src="../../../../../images/XYLineAndShapeRendererSample.png" * alt="XYLineAndShapeRendererSample.png" /> * */ public class XYLineAndShapeRenderer extends AbstractXYItemRenderer implements XYItemRenderer, Cloneable, PublicCloneable, Serializable { /** For serialization. */ private static final long serialVersionUID = -7435246895986425885L; /** * A table of flags that control (per series) whether or not lines are * visible. */ private BooleanList seriesLinesVisible; /** The default value returned by the getLinesVisible() method. */ private boolean baseLinesVisible; /** The shape that is used to represent a line in the legend. */ private transient Shape legendLine; /** * A table of flags that control (per series) whether or not shapes are * visible. */ private BooleanList seriesShapesVisible; /** The default value returned by the getShapeVisible() method. */ private boolean baseShapesVisible; /** * A table of flags that control (per series) whether or not shapes are * filled. */ private BooleanList seriesShapesFilled; /** The default value returned by the getShapeFilled() method. */ private boolean baseShapesFilled; /** A flag that controls whether outlines are drawn for shapes. */ private boolean drawOutlines; /** * A flag that controls whether the fill paint is used for filling * shapes. */ private boolean useFillPaint; /** * A flag that controls whether the outline paint is used for drawing shape * outlines. */ private boolean useOutlinePaint; /** * A flag that controls whether or not each series is drawn as a single * path. */ private boolean drawSeriesLineAsPath; /** * Creates a new renderer with both lines and shapes visible. */ public XYLineAndShapeRenderer() { this(true, true); } /** * Creates a new renderer. * * @param lines lines visible? * @param shapes shapes visible? */ public XYLineAndShapeRenderer(boolean lines, boolean shapes) { this.seriesLinesVisible = new BooleanList(); this.baseLinesVisible = lines; this.legendLine = new Line2D.Double(-7.0, 0.0, 7.0, 0.0); this.seriesShapesVisible = new BooleanList(); this.baseShapesVisible = shapes; this.useFillPaint = false; // use item paint for fills by default this.seriesShapesFilled = new BooleanList(); this.baseShapesFilled = true; this.drawOutlines = true; this.useOutlinePaint = false; // use item paint for outlines by // default, not outline paint this.drawSeriesLineAsPath = false; } /** * Returns a flag that controls whether or not each series is drawn as a * single path. * * @return A boolean. * * @see #setDrawSeriesLineAsPath(boolean) */ public boolean getDrawSeriesLineAsPath() { return this.drawSeriesLineAsPath; } /** * Sets the flag that controls whether or not each series is drawn as a * single path and sends a {@link RendererChangeEvent} to all registered * listeners. * * @param flag the flag. * * @see #getDrawSeriesLineAsPath() */ public void setDrawSeriesLineAsPath(boolean flag) { if (this.drawSeriesLineAsPath != flag) { this.drawSeriesLineAsPath = flag; fireChangeEvent(); } } /** * Returns the number of passes through the data that the renderer requires * in order to draw the chart. Most charts will require a single pass, but * some require two passes. * * @return The pass count. */ @Override public int getPassCount() { return 2; } // LINES VISIBLE /** * Returns the flag used to control whether or not the shape for an item is * visible. * * @param series the series index (zero-based). * @param item the item index (zero-based). * * @return A boolean. */ public boolean getItemLineVisible(int series, int item) { Boolean flag = getSeriesLinesVisible(series); if (flag != null) { return flag; } return this.baseLinesVisible; } /** * Returns the flag used to control whether or not the lines for a series * are visible. * * @param series the series index (zero-based). * * @return The flag (possibly <code>null</code>). * * @see #setSeriesLinesVisible(int, Boolean) */ public Boolean getSeriesLinesVisible(int series) { return this.seriesLinesVisible.getBoolean(series); } /** * Sets the 'lines visible' flag for a series and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param series the series index (zero-based). * @param flag the flag (<code>null</code> permitted). * * @see #getSeriesLinesVisible(int) */ public void setSeriesLinesVisible(int series, Boolean flag) { this.seriesLinesVisible.setBoolean(series, flag); fireChangeEvent(); } /** * Sets the 'lines visible' flag for a series and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param series the series index (zero-based). * @param visible the flag. * * @see #getSeriesLinesVisible(int) */ public void setSeriesLinesVisible(int series, boolean visible) { setSeriesLinesVisible(series, Boolean.valueOf(visible)); } /** * Returns the base 'lines visible' attribute. * * @return The base flag. * * @see #setBaseLinesVisible(boolean) */ public boolean getBaseLinesVisible() { return this.baseLinesVisible; } /** * Sets the base 'lines visible' flag and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param flag the flag. * * @see #getBaseLinesVisible() */ public void setBaseLinesVisible(boolean flag) { this.baseLinesVisible = flag; fireChangeEvent(); } /** * Returns the shape used to represent a line in the legend. * * @return The legend line (never <code>null</code>). * * @see #setLegendLine(Shape) */ public Shape getLegendLine() { return this.legendLine; } /** * Sets the shape used as a line in each legend item and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param line the line (<code>null</code> not permitted). * * @see #getLegendLine() */ public void setLegendLine(Shape line) { if (line == null) { throw new IllegalArgumentException("Null 'line' argument."); } this.legendLine = line; fireChangeEvent(); } // SHAPES VISIBLE /** * Returns the flag used to control whether or not the shape for an item is * visible. * <p> * The default implementation passes control to the * <code>getSeriesShapesVisible</code> method. You can override this method * if you require different behaviour. * * @param series the series index (zero-based). * @param item the item index (zero-based). * * @return A boolean. */ public boolean getItemShapeVisible(int series, int item) { Boolean flag = getSeriesShapesVisible(series); if (flag != null) { return flag; } return this.baseShapesVisible; } /** * Returns the flag used to control whether or not the shapes for a series * are visible. * * @param series the series index (zero-based). * * @return A boolean. * * @see #setSeriesShapesVisible(int, Boolean) */ public Boolean getSeriesShapesVisible(int series) { return this.seriesShapesVisible.getBoolean(series); } /** * Sets the 'shapes visible' flag for a series and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param series the series index (zero-based). * @param visible the flag. * * @see #getSeriesShapesVisible(int) */ public void setSeriesShapesVisible(int series, boolean visible) { setSeriesShapesVisible(series, Boolean.valueOf(visible)); } /** * Sets the 'shapes visible' flag for a series and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param series the series index (zero-based). * @param flag the flag. * * @see #getSeriesShapesVisible(int) */ public void setSeriesShapesVisible(int series, Boolean flag) { this.seriesShapesVisible.setBoolean(series, flag); fireChangeEvent(); } /** * Returns the base 'shape visible' attribute. * * @return The base flag. * * @see #setBaseShapesVisible(boolean) */ public boolean getBaseShapesVisible() { return this.baseShapesVisible; } /** * Sets the base 'shapes visible' flag and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param flag the flag. * * @see #getBaseShapesVisible() */ public void setBaseShapesVisible(boolean flag) { this.baseShapesVisible = flag; fireChangeEvent(); } // SHAPES FILLED /** * Returns the flag used to control whether or not the shape for an item * is filled. * <p> * The default implementation passes control to the * <code>getSeriesShapesFilled</code> method. You can override this method * if you require different behaviour. * * @param series the series index (zero-based). * @param item the item index (zero-based). * * @return A boolean. */ public boolean getItemShapeFilled(int series, int item) { Boolean flag = getSeriesShapesFilled(series); if (flag != null) { return flag; } return this.baseShapesFilled; } /** * Returns the flag used to control whether or not the shapes for a series * are filled. * * @param series the series index (zero-based). * * @return A boolean. * * @see #setSeriesShapesFilled(int, Boolean) */ public Boolean getSeriesShapesFilled(int series) { return this.seriesShapesFilled.getBoolean(series); } /** * Sets the 'shapes filled' flag for a series and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param series the series index (zero-based). * @param flag the flag. * * @see #getSeriesShapesFilled(int) */ public void setSeriesShapesFilled(int series, boolean flag) { setSeriesShapesFilled(series, Boolean.valueOf(flag)); } /** * Sets the 'shapes filled' flag for a series and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param series the series index (zero-based). * @param flag the flag. * * @see #getSeriesShapesFilled(int) */ public void setSeriesShapesFilled(int series, Boolean flag) { this.seriesShapesFilled.setBoolean(series, flag); fireChangeEvent(); } /** * Returns the base 'shape filled' attribute. * * @return The base flag. * * @see #setBaseShapesFilled(boolean) */ public boolean getBaseShapesFilled() { return this.baseShapesFilled; } /** * Sets the base 'shapes filled' flag and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param flag the flag. * * @see #getBaseShapesFilled() */ public void setBaseShapesFilled(boolean flag) { this.baseShapesFilled = flag; fireChangeEvent(); } /** * Returns <code>true</code> if outlines should be drawn for shapes, and * <code>false</code> otherwise. * * @return A boolean. * * @see #setDrawOutlines(boolean) */ public boolean getDrawOutlines() { return this.drawOutlines; } /** * Sets the flag that controls whether outlines are drawn for * shapes, and sends a {@link RendererChangeEvent} to all registered * listeners. * <P> * In some cases, shapes look better if they do NOT have an outline, but * this flag allows you to set your own preference. * * @param flag the flag. * * @see #getDrawOutlines() */ public void setDrawOutlines(boolean flag) { this.drawOutlines = flag; fireChangeEvent(); } /** * Returns <code>true</code> if the renderer should use the fill paint * setting to fill shapes, and <code>false</code> if it should just * use the regular paint. * <p> * Refer to <code>XYLineAndShapeRendererDemo2.java</code> to see the * effect of this flag. * * @return A boolean. * * @see #setUseFillPaint(boolean) * @see #getUseOutlinePaint() */ public boolean getUseFillPaint() { return this.useFillPaint; } /** * Sets the flag that controls whether the fill paint is used to fill * shapes, and sends a {@link RendererChangeEvent} to all * registered listeners. * * @param flag the flag. * * @see #getUseFillPaint() */ public void setUseFillPaint(boolean flag) { this.useFillPaint = flag; fireChangeEvent(); } /** * Returns <code>true</code> if the renderer should use the outline paint * setting to draw shape outlines, and <code>false</code> if it should just * use the regular paint. * * @return A boolean. * * @see #setUseOutlinePaint(boolean) * @see #getUseFillPaint() */ public boolean getUseOutlinePaint() { return this.useOutlinePaint; } /** * Sets the flag that controls whether the outline paint is used to draw * shape outlines, and sends a {@link RendererChangeEvent} to all * registered listeners. * <p> * Refer to <code>XYLineAndShapeRendererDemo2.java</code> to see the * effect of this flag. * * @param flag the flag. * * @see #getUseOutlinePaint() */ public void setUseOutlinePaint(boolean flag) { this.useOutlinePaint = flag; fireChangeEvent(); } /** * Records the state for the renderer. This is used to preserve state * information between calls to the drawItem() method for a single chart * drawing. */ public static class State extends XYItemRendererState { /** The path for the current series. */ public GeneralPath seriesPath; /** * A flag that indicates if the last (x, y) point was 'good' * (non-null). */ private boolean lastPointGood; /** * Creates a new state instance. * * @param info the plot rendering info. */ public State(PlotRenderingInfo info) { super(info); } /** * Returns a flag that indicates if the last point drawn (in the * current series) was 'good' (non-null). * * @return A boolean. */ public boolean isLastPointGood() { return this.lastPointGood; } /** * Sets a flag that indicates if the last point drawn (in the current * series) was 'good' (non-null). * * @param good the flag. */ public void setLastPointGood(boolean good) { this.lastPointGood = good; } /** * This method is called by the {@link XYPlot} at the start of each * series pass. We reset the state for the current series. * * @param dataset the dataset. * @param series the series index. * @param firstItem the first item index for this pass. * @param lastItem the last item index for this pass. * @param pass the current pass index. * @param passCount the number of passes. */ @Override public void startSeriesPass(XYDataset dataset, int series, int firstItem, int lastItem, int pass, int passCount) { this.seriesPath.reset(); this.lastPointGood = false; super.startSeriesPass(dataset, series, firstItem, lastItem, pass, passCount); } } /** * Initialises the renderer. * <P> * This method will be called before the first item is rendered, giving the * renderer an opportunity to initialise any state information it wants to * maintain. The renderer can do nothing if it chooses. * * @param g2 the graphics device. * @param dataArea the area inside the axes. * @param plot the plot. * @param data the data. * @param info an optional info collection object to return data back to * the caller. * * @return The renderer state. */ @Override public XYItemRendererState initialise(Graphics2D g2, Rectangle2D dataArea, XYPlot plot, XYDataset data, PlotRenderingInfo info) { State state = new State(info); state.seriesPath = new GeneralPath(); return state; } /** * Draws the visual representation of a single data item. * * @param g2 the graphics device. * @param state the renderer state. * @param dataArea the area within which the data is being drawn. * @param info collects information about the drawing. * @param plot the plot (can be used to obtain standard color * information etc). * @param domainAxis the domain axis. * @param rangeAxis the range axis. * @param dataset the dataset. * @param series the series index (zero-based). * @param item the item index (zero-based). * @param crosshairState crosshair information for the plot * (<code>null</code> permitted). * @param pass the pass index. */ @Override public void drawItem(Graphics2D g2, XYItemRendererState state, Rectangle2D dataArea, PlotRenderingInfo info, XYPlot plot, ValueAxis domainAxis, ValueAxis rangeAxis, XYDataset dataset, int series, int item, CrosshairState crosshairState, int pass) { // do nothing if item is not visible if (!getItemVisible(series, item)) { return; } // first pass draws the background (lines, for instance) if (isLinePass(pass)) { if (getItemLineVisible(series, item)) { if (this.drawSeriesLineAsPath) { drawPrimaryLineAsPath(state, g2, plot, dataset, pass, series, item, domainAxis, rangeAxis, dataArea); } else { drawPrimaryLine(state, g2, plot, dataset, pass, series, item, domainAxis, rangeAxis, dataArea); } } } // second pass adds shapes where the items are .. else if (isItemPass(pass)) { // setup for collecting optional entity info... EntityCollection entities = null; if (info != null) { entities = info.getOwner().getEntityCollection(); } drawSecondaryPass(g2, plot, dataset, pass, series, item, domainAxis, dataArea, rangeAxis, crosshairState, entities); } } /** * Returns <code>true</code> if the specified pass is the one for drawing * lines. * * @param pass the pass. * * @return A boolean. */ protected boolean isLinePass(int pass) { return pass == 0; } /** * Returns <code>true</code> if the specified pass is the one for drawing * items. * * @param pass the pass. * * @return A boolean. */ protected boolean isItemPass(int pass) { return pass == 1; } /** * Draws the item (first pass). This method draws the lines * connecting the items. * * @param g2 the graphics device. * @param state the renderer state. * @param dataArea the area within which the data is being drawn. * @param plot the plot (can be used to obtain standard color * information etc). * @param domainAxis the domain axis. * @param rangeAxis the range axis. * @param dataset the dataset. * @param pass the pass. * @param series the series index (zero-based). * @param item the item index (zero-based). */ protected void drawPrimaryLine(XYItemRendererState state, Graphics2D g2, XYPlot plot, XYDataset dataset, int pass, int series, int item, ValueAxis domainAxis, ValueAxis rangeAxis, Rectangle2D dataArea) { if (item == 0) { return; } // get the data point... double x1 = dataset.getXValue(series, item); double y1 = dataset.getYValue(series, item); if (Double.isNaN(y1) || Double.isNaN(x1)) { return; } double x0 = dataset.getXValue(series, item - 1); double y0 = dataset.getYValue(series, item - 1); if (Double.isNaN(y0) || Double.isNaN(x0)) { return; } RectangleEdge xAxisLocation = plot.getDomainAxisEdge(); RectangleEdge yAxisLocation = plot.getRangeAxisEdge(); double transX0 = domainAxis.valueToJava2D(x0, dataArea, xAxisLocation); double transY0 = rangeAxis.valueToJava2D(y0, dataArea, yAxisLocation); double transX1 = domainAxis.valueToJava2D(x1, dataArea, xAxisLocation); double transY1 = rangeAxis.valueToJava2D(y1, dataArea, yAxisLocation); // only draw if we have good values if (Double.isNaN(transX0) || Double.isNaN(transY0) || Double.isNaN(transX1) || Double.isNaN(transY1)) { return; } PlotOrientation orientation = plot.getOrientation(); boolean visible = false; if (orientation == PlotOrientation.HORIZONTAL) { state.workingLine.setLine(transY0, transX0, transY1, transX1); } else if (orientation == PlotOrientation.VERTICAL) { state.workingLine.setLine(transX0, transY0, transX1, transY1); } visible = LineUtilities.clipLine(state.workingLine, dataArea); if (visible) { drawFirstPassShape(g2, pass, series, item, state.workingLine); } } /** * Draws the first pass shape. * * @param g2 the graphics device. * @param pass the pass. * @param series the series index. * @param item the item index. * @param shape the shape. */ protected void drawFirstPassShape(Graphics2D g2, int pass, int series, int item, Shape shape) { g2.setStroke(getItemStroke(series, item)); g2.setPaint(getItemPaint(series, item)); g2.draw(shape); } /** * Draws the item (first pass). This method draws the lines * connecting the items. Instead of drawing separate lines, * a GeneralPath is constructed and drawn at the end of * the series painting. * * @param g2 the graphics device. * @param state the renderer state. * @param plot the plot (can be used to obtain standard color information * etc). * @param dataset the dataset. * @param pass the pass. * @param series the series index (zero-based). * @param item the item index (zero-based). * @param domainAxis the domain axis. * @param rangeAxis the range axis. * @param dataArea the area within which the data is being drawn. */ protected void drawPrimaryLineAsPath(XYItemRendererState state, Graphics2D g2, XYPlot plot, XYDataset dataset, int pass, int series, int item, ValueAxis domainAxis, ValueAxis rangeAxis, Rectangle2D dataArea) { RectangleEdge xAxisLocation = plot.getDomainAxisEdge(); RectangleEdge yAxisLocation = plot.getRangeAxisEdge(); // get the data point... double x1 = dataset.getXValue(series, item); double y1 = dataset.getYValue(series, item); double transX1 = domainAxis.valueToJava2D(x1, dataArea, xAxisLocation); double transY1 = rangeAxis.valueToJava2D(y1, dataArea, yAxisLocation); State s = (State) state; // update path to reflect latest point if (!Double.isNaN(transX1) && !Double.isNaN(transY1)) { float x = (float) transX1; float y = (float) transY1; PlotOrientation orientation = plot.getOrientation(); if (orientation == PlotOrientation.HORIZONTAL) { x = (float) transY1; y = (float) transX1; } if (s.isLastPointGood()) { s.seriesPath.lineTo(x, y); } else { s.seriesPath.moveTo(x, y); } s.setLastPointGood(true); } else { s.setLastPointGood(false); } // if this is the last item, draw the path ... if (item == s.getLastItemIndex()) { // draw path drawFirstPassShape(g2, pass, series, item, s.seriesPath); } } /** * Draws the item shapes and adds chart entities (second pass). This method * draws the shapes which mark the item positions. If <code>entities</code> * is not <code>null</code> it will be populated with entity information * for points that fall within the data area. * * @param g2 the graphics device. * @param plot the plot (can be used to obtain standard color * information etc). * @param domainAxis the domain axis. * @param dataArea the area within which the data is being drawn. * @param rangeAxis the range axis. * @param dataset the dataset. * @param pass the pass. * @param series the series index (zero-based). * @param item the item index (zero-based). * @param crosshairState the crosshair state. * @param entities the entity collection. */ protected void drawSecondaryPass(Graphics2D g2, XYPlot plot, XYDataset dataset, int pass, int series, int item, ValueAxis domainAxis, Rectangle2D dataArea, ValueAxis rangeAxis, CrosshairState crosshairState, EntityCollection entities) { Shape entityArea = null; // get the data point... double x1 = dataset.getXValue(series, item); double y1 = dataset.getYValue(series, item); if (Double.isNaN(y1) || Double.isNaN(x1)) { return; } PlotOrientation orientation = plot.getOrientation(); RectangleEdge xAxisLocation = plot.getDomainAxisEdge(); RectangleEdge yAxisLocation = plot.getRangeAxisEdge(); double transX1 = domainAxis.valueToJava2D(x1, dataArea, xAxisLocation); double transY1 = rangeAxis.valueToJava2D(y1, dataArea, yAxisLocation); if (getItemShapeVisible(series, item)) { Shape shape = getItemShape(series, item); if (orientation == PlotOrientation.HORIZONTAL) { shape = ShapeUtilities.createTranslatedShape(shape, transY1, transX1); } else if (orientation == PlotOrientation.VERTICAL) { shape = ShapeUtilities.createTranslatedShape(shape, transX1, transY1); } entityArea = shape; if (shape.intersects(dataArea)) { if (getItemShapeFilled(series, item)) { if (this.useFillPaint) { g2.setPaint(getItemFillPaint(series, item)); } else { g2.setPaint(getItemPaint(series, item)); } g2.fill(shape); } if (this.drawOutlines) { if (getUseOutlinePaint()) { g2.setPaint(getItemOutlinePaint(series, item)); } else { g2.setPaint(getItemPaint(series, item)); } g2.setStroke(getItemOutlineStroke(series, item)); g2.draw(shape); } } } double xx = transX1; double yy = transY1; if (orientation == PlotOrientation.HORIZONTAL) { xx = transY1; yy = transX1; } // draw the item label if there is one... if (isItemLabelVisible(series, item)) { drawItemLabel(g2, orientation, dataset, series, item, xx, yy, (y1 < 0.0)); } int domainAxisIndex = plot.getDomainAxisIndex(domainAxis); int rangeAxisIndex = plot.getRangeAxisIndex(rangeAxis); updateCrosshairValues(crosshairState, x1, y1, domainAxisIndex, rangeAxisIndex, transX1, transY1, orientation); // add an entity for the item, but only if it falls within the data // area... if (entities != null && isPointInRect(dataArea, xx, yy)) { addEntity(entities, entityArea, dataset, series, item, xx, yy); } } /** * Returns a legend item for the specified series. * * @param datasetIndex the dataset index (zero-based). * @param series the series index (zero-based). * * @return A legend item for the series (possibly <code>null</code). */ @Override public LegendItem getLegendItem(int datasetIndex, int series) { XYPlot plot = getPlot(); if (plot == null) { return null; } XYDataset dataset = plot.getDataset(datasetIndex); if (dataset == null) { return null; } if (!getItemVisible(series, 0)) { return null; } String label = getLegendItemLabelGenerator().generateLabel(dataset, series); String description = label; String toolTipText = null; if (getLegendItemToolTipGenerator() != null) { toolTipText = getLegendItemToolTipGenerator().generateLabel( dataset, series); } String urlText = null; if (getLegendItemURLGenerator() != null) { urlText = getLegendItemURLGenerator().generateLabel(dataset, series); } boolean shapeIsVisible = getItemShapeVisible(series, 0); Shape shape = lookupLegendShape(series); boolean shapeIsFilled = getItemShapeFilled(series, 0); Paint fillPaint = (this.useFillPaint ? lookupSeriesFillPaint(series) : lookupSeriesPaint(series)); boolean shapeOutlineVisible = this.drawOutlines; Paint outlinePaint = (this.useOutlinePaint ? lookupSeriesOutlinePaint( series) : lookupSeriesPaint(series)); Stroke outlineStroke = lookupSeriesOutlineStroke(series); boolean lineVisible = getItemLineVisible(series, 0); Stroke lineStroke = lookupSeriesStroke(series); Paint linePaint = lookupSeriesPaint(series); LegendItem result = new LegendItem(label, description, toolTipText, urlText, shapeIsVisible, shape, shapeIsFilled, fillPaint, shapeOutlineVisible, outlinePaint, outlineStroke, lineVisible, this.legendLine, lineStroke, linePaint); result.setLabelFont(lookupLegendTextFont(series)); Paint labelPaint = lookupLegendTextPaint(series); if (labelPaint != null) { result.setLabelPaint(labelPaint); } result.setSeriesKey(dataset.getSeriesKey(series)); result.setSeriesIndex(series); result.setDataset(dataset); result.setDatasetIndex(datasetIndex); return result; } /** * Returns a clone of the renderer. * * @return A clone. * * @throws CloneNotSupportedException if the clone cannot be created. */ @Override public Object clone() throws CloneNotSupportedException { XYLineAndShapeRenderer clone = (XYLineAndShapeRenderer) super.clone(); clone.seriesLinesVisible = (BooleanList) this.seriesLinesVisible.clone(); if (this.legendLine != null) { clone.legendLine = ShapeUtilities.clone(this.legendLine); } clone.seriesShapesVisible = (BooleanList) this.seriesShapesVisible.clone(); clone.seriesShapesFilled = (BooleanList) this.seriesShapesFilled.clone(); return clone; } /** * Tests this renderer for equality with an arbitrary object. * * @param obj the object (<code>null</code> permitted). * * @return <code>true</code> or <code>false</code>. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof XYLineAndShapeRenderer)) { return false; } if (!super.equals(obj)) { return false; } XYLineAndShapeRenderer that = (XYLineAndShapeRenderer) obj; if (!ObjectUtilities.equal(this.seriesLinesVisible, that.seriesLinesVisible)) { return false; } if (this.baseLinesVisible != that.baseLinesVisible) { return false; } if (!ShapeUtilities.equal(this.legendLine, that.legendLine)) { return false; } if (!ObjectUtilities.equal(this.seriesShapesVisible, that.seriesShapesVisible)) { return false; } if (this.baseShapesVisible != that.baseShapesVisible) { return false; } if (!ObjectUtilities.equal(this.seriesShapesFilled, that.seriesShapesFilled)) { return false; } if (this.baseShapesFilled != that.baseShapesFilled) { return false; } if (this.drawOutlines != that.drawOutlines) { return false; } if (this.useOutlinePaint != that.useOutlinePaint) { return false; } if (this.useFillPaint != that.useFillPaint) { return false; } if (this.drawSeriesLineAsPath != that.drawSeriesLineAsPath) { return false; } return true; } /** * Provides serialization support. * * @param stream the input stream. * * @throws IOException if there is an I/O error. * @throws ClassNotFoundException if there is a classpath problem. */ private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); this.legendLine = SerialUtilities.readShape(stream); } /** * Provides serialization support. * * @param stream the output stream. * * @throws IOException if there is an I/O error. */ private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); SerialUtilities.writeShape(this.legendLine, stream); } }
41,941
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
XYShapeRenderer.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/renderer/xy/XYShapeRenderer.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * -------------------- * XYShapeRenderer.java * -------------------- * (C) Copyright 2008-2012 by Andreas Haumer, xS+S and Contributors. * * Original Author: Martin Hoeller (x Software + Systeme xS+S - Andreas * Haumer); * Contributor(s): David Gilbert (for Object Refinery Limited); * * Changes: * -------- * 17-Sep-2008 : Version 1, based on a contribution from Martin Hoeller with * amendments by David Gilbert (DG); * 16-Feb-2010 : Added findZBounds() (patch 2952086) (MH); * 19-Oct-2011 : Fixed NPE in findRangeBounds() (bug 3026341) (DG); * 17-Jun-2012 : Removed JCommon dependencies (DG); * */ package org.jfree.chart.renderer.xy; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.Shape; import java.awt.Stroke; import java.awt.geom.Ellipse2D; import java.awt.geom.Line2D; import java.awt.geom.Rectangle2D; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.util.PublicCloneable; import org.jfree.chart.util.ShapeUtilities; import org.jfree.chart.entity.EntityCollection; import org.jfree.chart.event.RendererChangeEvent; import org.jfree.chart.plot.CrosshairState; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.PlotRenderingInfo; import org.jfree.chart.plot.XYPlot; import org.jfree.chart.renderer.LookupPaintScale; import org.jfree.chart.renderer.PaintScale; import org.jfree.chart.util.SerialUtilities; import org.jfree.data.Range; import org.jfree.data.general.DatasetUtilities; import org.jfree.data.xy.XYDataset; import org.jfree.data.xy.XYZDataset; /** * A renderer that draws shapes at (x, y) coordinates and, if the dataset * is an instance of {@link XYZDataset}, fills the shapes with a paint that * is based on the z-value (the paint is obtained from a lookup table). The * renderer also allows for optional guidelines, horizontal and vertical lines * connecting the shape to the edges of the plot. * <br><br> * The example shown here is generated by the * <code>XYShapeRendererDemo1.java</code> program included in the JFreeChart * demo collection: * <br><br> * <img src="../../../../../images/XYShapeRendererSample.png" * alt="XYShapeRendererSample.png" /> * <br><br> * This renderer has similarities to, but also differences from, the * {@link XYLineAndShapeRenderer}. * * @since 1.0.11 */ public class XYShapeRenderer extends AbstractXYItemRenderer implements XYItemRenderer, Cloneable, Serializable { /** Auto generated serial version id. */ private static final long serialVersionUID = 8320552104211173221L; /** The paint scale (never null). */ private PaintScale paintScale; /** A flag that controls whether or not the shape outlines are drawn. */ private boolean drawOutlines; /** * A flag that controls whether or not the outline paint is used (if not, * the regular paint is used). */ private boolean useOutlinePaint; /** * A flag that controls whether or not the fill paint is used (if not, * the fill paint is used). */ private boolean useFillPaint; /** Flag indicating if guide lines should be drawn for every item. */ private boolean guideLinesVisible; /** The paint used for drawing the guide lines (never null). */ private transient Paint guideLinePaint; /** The stroke used for drawing the guide lines (never null). */ private transient Stroke guideLineStroke; /** * Creates a new <code>XYShapeRenderer</code> instance with default * attributes. */ public XYShapeRenderer() { this.paintScale = new LookupPaintScale(); this.useFillPaint = false; this.drawOutlines = false; this.useOutlinePaint = true; this.guideLinesVisible = false; this.guideLinePaint = Color.DARK_GRAY; this.guideLineStroke = new BasicStroke(); setDefaultShape(new Ellipse2D.Double(-5.0, -5.0, 10.0, 10.0)); setAutoPopulateSeriesShape(false); } /** * Returns the paint scale used by the renderer. * * @return The paint scale (never <code>null</code>). * * @see #setPaintScale(PaintScale) */ public PaintScale getPaintScale() { return this.paintScale; } /** * Sets the paint scale used by the renderer and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param scale the scale (<code>null</code> not permitted). * * @see #getPaintScale() */ public void setPaintScale(PaintScale scale) { if (scale == null) { throw new IllegalArgumentException("Null 'scale' argument."); } this.paintScale = scale; notifyListeners(new RendererChangeEvent(this)); } /** * Returns <code>true</code> if outlines should be drawn for shapes, and * <code>false</code> otherwise. * * @return A boolean. * * @see #setDrawOutlines(boolean) */ public boolean getDrawOutlines() { return this.drawOutlines; } /** * Sets the flag that controls whether outlines are drawn for * shapes, and sends a {@link RendererChangeEvent} to all registered * listeners. * <P> * In some cases, shapes look better if they do NOT have an outline, but * this flag allows you to set your own preference. * * @param flag the flag. * * @see #getDrawOutlines() */ public void setDrawOutlines(boolean flag) { this.drawOutlines = flag; fireChangeEvent(); } /** * Returns <code>true</code> if the renderer should use the fill paint * setting to fill shapes, and <code>false</code> if it should just * use the regular paint. * <p> * Refer to <code>XYLineAndShapeRendererDemo2.java</code> to see the * effect of this flag. * * @return A boolean. * * @see #setUseFillPaint(boolean) * @see #getUseOutlinePaint() */ public boolean getUseFillPaint() { return this.useFillPaint; } /** * Sets the flag that controls whether the fill paint is used to fill * shapes, and sends a {@link RendererChangeEvent} to all * registered listeners. * * @param flag the flag. * * @see #getUseFillPaint() */ public void setUseFillPaint(boolean flag) { this.useFillPaint = flag; fireChangeEvent(); } /** * Returns the flag that controls whether the outline paint is used for * shape outlines. If not, the regular series paint is used. * * @return A boolean. * * @see #setUseOutlinePaint(boolean) */ public boolean getUseOutlinePaint() { return this.useOutlinePaint; } /** * Sets the flag that controls whether the outline paint is used for shape * outlines, and sends a {@link RendererChangeEvent} to all registered * listeners. * * @param use the flag. * * @see #getUseOutlinePaint() */ public void setUseOutlinePaint(boolean use) { this.useOutlinePaint = use; fireChangeEvent(); } /** * Returns a flag that controls whether or not guide lines are drawn for * each data item (the lines are horizontal and vertical "crosshairs" * linking the data point to the axes). * * @return A boolean. * * @see #setGuideLinesVisible(boolean) */ public boolean isGuideLinesVisible() { return this.guideLinesVisible; } /** * Sets the flag that controls whether or not guide lines are drawn for * each data item and sends a {@link RendererChangeEvent} to all registered * listeners. * * @param visible the new flag value. * * @see #isGuideLinesVisible() */ public void setGuideLinesVisible(boolean visible) { this.guideLinesVisible = visible; fireChangeEvent(); } /** * Returns the paint used to draw the guide lines. * * @return The paint (never <code>null</code>). * * @see #setGuideLinePaint(Paint) */ public Paint getGuideLinePaint() { return this.guideLinePaint; } /** * Sets the paint used to draw the guide lines and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param paint the paint (<code>null</code> not permitted). * * @see #getGuideLinePaint() */ public void setGuideLinePaint(Paint paint) { if (paint == null) { throw new IllegalArgumentException("Null 'paint' argument."); } this.guideLinePaint = paint; fireChangeEvent(); } /** * Returns the stroke used to draw the guide lines. * * @return The stroke. * * @see #setGuideLineStroke(Stroke) */ public Stroke getGuideLineStroke() { return this.guideLineStroke; } /** * Sets the stroke used to draw the guide lines and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param stroke the stroke (<code>null</code> not permitted). * * @see #getGuideLineStroke() */ public void setGuideLineStroke(Stroke stroke) { if (stroke == null) { throw new IllegalArgumentException("Null 'stroke' argument."); } this.guideLineStroke = stroke; fireChangeEvent(); } /** * Returns the lower and upper bounds (range) of the x-values in the * specified dataset. * * @param dataset the dataset (<code>null</code> permitted). * * @return The range (<code>null</code> if the dataset is <code>null</code> * or empty). */ @Override public Range findDomainBounds(XYDataset dataset) { if (dataset == null) { return null; } Range r = DatasetUtilities.findDomainBounds(dataset, false); if (r == null) { return null; } double offset = 0; // TODO getSeriesShape(n).getBounds().width / 2; return new Range(r.getLowerBound() + offset, r.getUpperBound() + offset); } /** * Returns the range of values the renderer requires to display all the * items from the specified dataset. * * @param dataset the dataset (<code>null</code> permitted). * * @return The range (<code>null</code> if the dataset is <code>null</code> * or empty). */ @Override public Range findRangeBounds(XYDataset dataset) { if (dataset == null) { return null; } Range r = DatasetUtilities.findRangeBounds(dataset, false); if (r == null) { return null; } double offset = 0; // TODO getSeriesShape(n).getBounds().height / 2; return new Range(r.getLowerBound() + offset, r.getUpperBound() + offset); } /** * Return the range of z-values in the specified dataset. * * @param dataset the dataset (<code>null</code> permitted). * * @return The range (<code>null</code> if the dataset is <code>null</code> * or empty). */ public Range findZBounds(XYZDataset dataset) { if (dataset != null) { return DatasetUtilities.findZBounds(dataset); } else { return null; } } /** * Returns the number of passes required by this renderer. * * @return <code>2</code>. */ @Override public int getPassCount() { return 2; } /** * Draws the block representing the specified item. * * @param g2 the graphics device. * @param state the state. * @param dataArea the data area. * @param info the plot rendering info. * @param plot the plot. * @param domainAxis the x-axis. * @param rangeAxis the y-axis. * @param dataset the dataset. * @param series the series index. * @param item the item index. * @param crosshairState the crosshair state. * @param pass the pass index. */ @Override public void drawItem(Graphics2D g2, XYItemRendererState state, Rectangle2D dataArea, PlotRenderingInfo info, XYPlot plot, ValueAxis domainAxis, ValueAxis rangeAxis, XYDataset dataset, int series, int item, CrosshairState crosshairState, int pass) { Shape hotspot = null; EntityCollection entities = null; if (info != null) { entities = info.getOwner().getEntityCollection(); } double x = dataset.getXValue(series, item); double y = dataset.getYValue(series, item); if (Double.isNaN(x) || Double.isNaN(y)) { // can't draw anything return; } double transX = domainAxis.valueToJava2D(x, dataArea, plot.getDomainAxisEdge()); double transY = rangeAxis.valueToJava2D(y, dataArea, plot.getRangeAxisEdge()); PlotOrientation orientation = plot.getOrientation(); // draw optional guide lines if ((pass == 0) && this.guideLinesVisible) { g2.setStroke(this.guideLineStroke); g2.setPaint(this.guideLinePaint); if (orientation == PlotOrientation.HORIZONTAL) { g2.draw(new Line2D.Double(transY, dataArea.getMinY(), transY, dataArea.getMaxY())); g2.draw(new Line2D.Double(dataArea.getMinX(), transX, dataArea.getMaxX(), transX)); } else { g2.draw(new Line2D.Double(transX, dataArea.getMinY(), transX, dataArea.getMaxY())); g2.draw(new Line2D.Double(dataArea.getMinX(), transY, dataArea.getMaxX(), transY)); } } else if (pass == 1) { Shape shape = getItemShape(series, item); if (orientation == PlotOrientation.HORIZONTAL) { shape = ShapeUtilities.createTranslatedShape(shape, transY, transX); } else if (orientation == PlotOrientation.VERTICAL) { shape = ShapeUtilities.createTranslatedShape(shape, transX, transY); } hotspot = shape; if (shape.intersects(dataArea)) { //if (getItemShapeFilled(series, item)) { g2.setPaint(getPaint(dataset, series, item)); g2.fill(shape); //} if (this.drawOutlines) { if (getUseOutlinePaint()) { g2.setPaint(getItemOutlinePaint(series, item)); } else { g2.setPaint(getItemPaint(series, item)); } g2.setStroke(getItemOutlineStroke(series, item)); g2.draw(shape); } } // add an entity for the item... if (entities != null) { addEntity(entities, hotspot, dataset, series, item, transX, transY); } } } /** * Get the paint for a given series and item from a dataset. * * @param dataset the dataset.. * @param series the series index. * @param item the item index. * * @return The paint. */ protected Paint getPaint(XYDataset dataset, int series, int item) { Paint p = null; if (dataset instanceof XYZDataset) { double z = ((XYZDataset) dataset).getZValue(series, item); p = this.paintScale.getPaint(z); } else { if (this.useFillPaint) { p = getItemFillPaint(series, item); } else { p = getItemPaint(series, item); } } return p; } /** * Tests this instance for equality with an arbitrary object. This method * returns <code>true</code> if and only if: * <ul> * <li><code>obj</code> is an instance of <code>XYShapeRenderer</code> (not * <code>null</code>);</li> * <li><code>obj</code> has the same field values as this * <code>XYShapeRenderer</code>;</li> * </ul> * * @param obj the object (<code>null</code> permitted). * * @return A boolean. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof XYShapeRenderer)) { return false; } XYShapeRenderer that = (XYShapeRenderer) obj; if (!this.paintScale.equals(that.paintScale)) { return false; } if (this.drawOutlines != that.drawOutlines) { return false; } if (this.useOutlinePaint != that.useOutlinePaint) { return false; } if (this.useFillPaint != that.useFillPaint) { return false; } if (this.guideLinesVisible != that.guideLinesVisible) { return false; } if (!this.guideLinePaint.equals(that.guideLinePaint)) { return false; } if (!this.guideLineStroke.equals(that.guideLineStroke)) { return false; } return super.equals(obj); } /** * Returns a clone of this renderer. * * @return A clone of this renderer. * * @throws CloneNotSupportedException if there is a problem creating the * clone. */ @Override public Object clone() throws CloneNotSupportedException { XYShapeRenderer clone = (XYShapeRenderer) super.clone(); if (this.paintScale instanceof PublicCloneable) { PublicCloneable pc = (PublicCloneable) this.paintScale; clone.paintScale = (PaintScale) pc.clone(); } return clone; } /** * Provides serialization support. * * @param stream the input stream. * * @throws IOException if there is an I/O error. * @throws ClassNotFoundException if there is a classpath problem. */ private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); this.guideLinePaint = SerialUtilities.readPaint(stream); this.guideLineStroke = SerialUtilities.readStroke(stream); } /** * Provides serialization support. * * @param stream the output stream. * * @throws IOException if there is an I/O error. */ private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); SerialUtilities.writePaint(this.guideLinePaint, stream); SerialUtilities.writeStroke(this.guideLineStroke, stream); } }
20,376
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
VectorRenderer.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/renderer/xy/VectorRenderer.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ------------------- * VectorRenderer.java * ------------------- * (C) Copyright 2007-2012, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 30-Jan-2007 : Version 1 (DG); * 24-May-2007 : Updated for method name changes (DG); * 25-May-2007 : Moved from experimental to the main source tree (DG); * 18-Feb-2008 : Fixed bug 1880114, arrows for horizontal plot * orientation (DG); * 22-Apr-2008 : Implemented PublicCloneable (DG); * 26-Sep-2008 : Added chart entity support (tooltips etc) (DG); * 17-Jun-2012 : Removed JCommon dependencies (DG); * */ package org.jfree.chart.renderer.xy; import java.awt.Graphics2D; import java.awt.geom.GeneralPath; import java.awt.geom.Line2D; import java.awt.geom.Rectangle2D; import java.io.Serializable; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.util.PublicCloneable; import org.jfree.chart.entity.EntityCollection; import org.jfree.chart.plot.CrosshairState; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.PlotRenderingInfo; import org.jfree.chart.plot.XYPlot; import org.jfree.data.Range; import org.jfree.data.xy.VectorXYDataset; import org.jfree.data.xy.XYDataset; /** * A renderer that represents data from an {@link VectorXYDataset} by drawing a * line with an arrow at each (x, y) point. * The example shown here is generated by the <code>VectorPlotDemo1.java</code> * program included in the JFreeChart demo collection: * <br><br> * <img src="../../../../../images/VectorRendererSample.png" * alt="VectorRendererSample.png" /> * * @since 1.0.6 */ public class VectorRenderer extends AbstractXYItemRenderer implements XYItemRenderer, Cloneable, PublicCloneable, Serializable { /** The length of the base. */ private double baseLength = 0.10; /** The length of the head. */ private double headLength = 0.14; /** * Creates a new <code>XYBlockRenderer</code> instance with default * attributes. */ public VectorRenderer() { } /** * Returns the lower and upper bounds (range) of the x-values in the * specified dataset. * * @param dataset the dataset (<code>null</code> permitted). * * @return The range (<code>null</code> if the dataset is <code>null</code> * or empty). */ @Override public Range findDomainBounds(XYDataset dataset) { if (dataset == null) { throw new IllegalArgumentException("Null 'dataset' argument."); } double minimum = Double.POSITIVE_INFINITY; double maximum = Double.NEGATIVE_INFINITY; int seriesCount = dataset.getSeriesCount(); double lvalue; double uvalue; if (dataset instanceof VectorXYDataset) { VectorXYDataset vdataset = (VectorXYDataset) dataset; for (int series = 0; series < seriesCount; series++) { int itemCount = dataset.getItemCount(series); for (int item = 0; item < itemCount; item++) { double delta = vdataset.getVectorXValue(series, item); if (delta < 0.0) { uvalue = vdataset.getXValue(series, item); lvalue = uvalue + delta; } else { lvalue = vdataset.getXValue(series, item); uvalue = lvalue + delta; } minimum = Math.min(minimum, lvalue); maximum = Math.max(maximum, uvalue); } } } else { for (int series = 0; series < seriesCount; series++) { int itemCount = dataset.getItemCount(series); for (int item = 0; item < itemCount; item++) { lvalue = dataset.getXValue(series, item); uvalue = lvalue; minimum = Math.min(minimum, lvalue); maximum = Math.max(maximum, uvalue); } } } if (minimum > maximum) { return null; } else { return new Range(minimum, maximum); } } /** * Returns the range of values the renderer requires to display all the * items from the specified dataset. * * @param dataset the dataset (<code>null</code> permitted). * * @return The range (<code>null</code> if the dataset is <code>null</code> * or empty). */ @Override public Range findRangeBounds(XYDataset dataset) { if (dataset == null) { throw new IllegalArgumentException("Null 'dataset' argument."); } double minimum = Double.POSITIVE_INFINITY; double maximum = Double.NEGATIVE_INFINITY; int seriesCount = dataset.getSeriesCount(); double lvalue; double uvalue; if (dataset instanceof VectorXYDataset) { VectorXYDataset vdataset = (VectorXYDataset) dataset; for (int series = 0; series < seriesCount; series++) { int itemCount = dataset.getItemCount(series); for (int item = 0; item < itemCount; item++) { double delta = vdataset.getVectorYValue(series, item); if (delta < 0.0) { uvalue = vdataset.getYValue(series, item); lvalue = uvalue + delta; } else { lvalue = vdataset.getYValue(series, item); uvalue = lvalue + delta; } minimum = Math.min(minimum, lvalue); maximum = Math.max(maximum, uvalue); } } } else { for (int series = 0; series < seriesCount; series++) { int itemCount = dataset.getItemCount(series); for (int item = 0; item < itemCount; item++) { lvalue = dataset.getYValue(series, item); uvalue = lvalue; minimum = Math.min(minimum, lvalue); maximum = Math.max(maximum, uvalue); } } } if (minimum > maximum) { return null; } else { return new Range(minimum, maximum); } } /** * Draws the block representing the specified item. * * @param g2 the graphics device. * @param state the state. * @param dataArea the data area. * @param info the plot rendering info. * @param plot the plot. * @param domainAxis the x-axis. * @param rangeAxis the y-axis. * @param dataset the dataset. * @param series the series index. * @param item the item index. * @param crosshairState the crosshair state. * @param pass the pass index. */ @Override public void drawItem(Graphics2D g2, XYItemRendererState state, Rectangle2D dataArea, PlotRenderingInfo info, XYPlot plot, ValueAxis domainAxis, ValueAxis rangeAxis, XYDataset dataset, int series, int item, CrosshairState crosshairState, int pass) { double x = dataset.getXValue(series, item); double y = dataset.getYValue(series, item); double dx = 0.0; double dy = 0.0; if (dataset instanceof VectorXYDataset) { dx = ((VectorXYDataset) dataset).getVectorXValue(series, item); dy = ((VectorXYDataset) dataset).getVectorYValue(series, item); } double xx0 = domainAxis.valueToJava2D(x, dataArea, plot.getDomainAxisEdge()); double yy0 = rangeAxis.valueToJava2D(y, dataArea, plot.getRangeAxisEdge()); double xx1 = domainAxis.valueToJava2D(x + dx, dataArea, plot.getDomainAxisEdge()); double yy1 = rangeAxis.valueToJava2D(y + dy, dataArea, plot.getRangeAxisEdge()); Line2D line; PlotOrientation orientation = plot.getOrientation(); if (orientation.equals(PlotOrientation.HORIZONTAL)) { line = new Line2D.Double(yy0, xx0, yy1, xx1); } else { line = new Line2D.Double(xx0, yy0, xx1, yy1); } g2.setPaint(getItemPaint(series, item)); g2.setStroke(getItemStroke(series, item)); g2.draw(line); // calculate the arrow head and draw it... double dxx = (xx1 - xx0); double dyy = (yy1 - yy0); double bx = xx0 + (1.0 - this.baseLength) * dxx; double by = yy0 + (1.0 - this.baseLength) * dyy; double cx = xx0 + (1.0 - this.headLength) * dxx; double cy = yy0 + (1.0 - this.headLength) * dyy; double angle = 0.0; if (dxx != 0.0) { angle = Math.PI / 2.0 - Math.atan(dyy / dxx); } double deltaX = 2.0 * Math.cos(angle); double deltaY = 2.0 * Math.sin(angle); double leftx = cx + deltaX; double lefty = cy - deltaY; double rightx = cx - deltaX; double righty = cy + deltaY; GeneralPath p = new GeneralPath(); if (orientation == PlotOrientation.VERTICAL) { p.moveTo((float) xx1, (float) yy1); p.lineTo((float) rightx, (float) righty); p.lineTo((float) bx, (float) by); p.lineTo((float) leftx, (float) lefty); } else { // orientation is HORIZONTAL p.moveTo((float) yy1, (float) xx1); p.lineTo((float) righty, (float) rightx); p.lineTo((float) by, (float) bx); p.lineTo((float) lefty, (float) leftx); } p.closePath(); g2.draw(p); // setup for collecting optional entity info... EntityCollection entities = null; if (info != null) { entities = info.getOwner().getEntityCollection(); if (entities != null) { addEntity(entities, line.getBounds(), dataset, series, item, 0.0, 0.0); } } } /** * Tests this <code>VectorRenderer</code> for equality with an arbitrary * object. This method returns <code>true</code> if and only if: * <ul> * <li><code>obj</code> is an instance of <code>VectorRenderer</code> (not * <code>null</code>);</li> * <li><code>obj</code> has the same field values as this * <code>VectorRenderer</code>;</li> * </ul> * * @param obj the object (<code>null</code> permitted). * * @return A boolean. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof VectorRenderer)) { return false; } VectorRenderer that = (VectorRenderer) obj; if (this.baseLength != that.baseLength) { return false; } if (this.headLength != that.headLength) { return false; } return super.equals(obj); } /** * Returns a clone of this renderer. * * @return A clone of this renderer. * * @throws CloneNotSupportedException if there is a problem creating the * clone. */ @Override public Object clone() throws CloneNotSupportedException { return super.clone(); } }
12,730
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
StandardXYItemRenderer.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/renderer/xy/StandardXYItemRenderer.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * --------------------------- * StandardXYItemRenderer.java * --------------------------- * (C) Copyright 2001-2012, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): Mark Watson (www.markwatson.com); * Jonathan Nash; * Andreas Schneider; * Norbert Kiesel (for TBD Networks); * Christian W. Zuckschwerdt; * Bill Kelemen; * Nicolas Brodu (for Astrium and EADS Corporate Research * Center); * * Changes: * -------- * 19-Oct-2001 : Version 1, based on code by Mark Watson (DG); * 22-Oct-2001 : Renamed DataSource.java --> Dataset.java etc. (DG); * 21-Dec-2001 : Added working line instance to improve performance (DG); * 22-Jan-2002 : Added code to lock crosshairs to data points. Based on code * by Jonathan Nash (DG); * 23-Jan-2002 : Added DrawInfo parameter to drawItem() method (DG); * 28-Mar-2002 : Added a property change listener mechanism so that the * renderer no longer needs to be immutable (DG); * 02-Apr-2002 : Modified to handle null values (DG); * 09-Apr-2002 : Modified draw method to return void. Removed the translated * zero from the drawItem method. Override the initialise() * method to calculate it (DG); * 13-May-2002 : Added code from Andreas Schneider to allow changing * shapes/colors per item (DG); * 24-May-2002 : Incorporated tooltips into chart entities (DG); * 25-Jun-2002 : Removed redundant code (DG); * 05-Aug-2002 : Incorporated URLs for HTML image maps into chart entities (RA); * 08-Aug-2002 : Added discontinuous lines option contributed by * Norbert Kiesel (DG); * 20-Aug-2002 : Added user definable default values to be returned by * protected methods unless overridden by a subclass (DG); * 23-Sep-2002 : Updated for changes in the XYItemRenderer interface (DG); * 02-Oct-2002 : Fixed errors reported by Checkstyle (DG); * 25-Mar-2003 : Implemented Serializable (DG); * 01-May-2003 : Modified drawItem() method signature (DG); * 15-May-2003 : Modified to take into account the plot orientation (DG); * 29-Jul-2003 : Amended code that doesn't compile with JDK 1.2.2 (DG); * 30-Jul-2003 : Modified entity constructor (CZ); * 20-Aug-2003 : Implemented Cloneable and PublicCloneable (DG); * 24-Aug-2003 : Added null/NaN checks in drawItem (BK); * 08-Sep-2003 : Fixed serialization (NB); * 16-Sep-2003 : Changed ChartRenderingInfo --> PlotRenderingInfo (DG); * 21-Jan-2004 : Override for getLegendItem() method (DG); * 27-Jan-2004 : Moved working line into state object (DG); * 10-Feb-2004 : Changed drawItem() method to make cut-and-paste overriding * easier (DG); * 25-Feb-2004 : Replaced CrosshairInfo with CrosshairState. Renamed * XYToolTipGenerator --> XYItemLabelGenerator (DG); * 08-Jun-2004 : Modified to use getX() and getY() methods (DG); * 15-Jul-2004 : Switched getX() with getXValue() and getY() with * getYValue() (DG); * 25-Aug-2004 : Created addEntity() method in superclass (DG); * 08-Oct-2004 : Added 'gapThresholdType' as suggested by Mike Watts (DG); * 11-Nov-2004 : Now uses ShapeUtilities to translate shapes (DG); * 23-Feb-2005 : Fixed getLegendItem() method to show lines. Fixed bug * 1077108 (shape not visible for first item in series) (DG); * 10-Apr-2005 : Fixed item label positioning with horizontal orientation (DG); * 20-Apr-2005 : Use generators for legend tooltips and URLs (DG); * 27-Apr-2005 : Use generator for series label in legend (DG); * ------------- JFREECHART 1.0.x --------------------------------------------- * 15-Jun-2006 : Fixed bug (1380480) for rendering series as path (DG); * 06-Feb-2007 : Fixed bug 1086307, crosshairs with multiple axes (DG); * 14-Mar-2007 : Fixed problems with the equals() and clone() methods (DG); * 23-Mar-2007 : Clean-up of shapesFilled attributes (DG); * 20-Apr-2007 : Updated getLegendItem() and drawItem() for renderer * change (DG); * 17-May-2007 : Set datasetIndex and seriesIndex in getLegendItem() * method (DG); * 18-May-2007 : Set dataset and seriesKey for LegendItem (DG); * 08-Jun-2007 : Fixed bug in entity creation (DG); * 21-Nov-2007 : Deprecated override flag methods (DG); * 02-Jun-2008 : Fixed tooltips for data items at lower edges of data area (DG); * 17-Jun-2008 : Apply legend shape, font and paint attributes (DG); * */ package org.jfree.chart.renderer.xy; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Paint; import java.awt.Point; import java.awt.Shape; import java.awt.Stroke; import java.awt.geom.GeneralPath; import java.awt.geom.Line2D; import java.awt.geom.Rectangle2D; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import org.jfree.chart.LegendItem; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.ui.RectangleEdge; import org.jfree.chart.util.BooleanList; import org.jfree.chart.util.PublicCloneable; import org.jfree.chart.util.ShapeUtilities; import org.jfree.chart.util.UnitType; import org.jfree.chart.entity.EntityCollection; import org.jfree.chart.event.RendererChangeEvent; import org.jfree.chart.labels.XYToolTipGenerator; import org.jfree.chart.plot.CrosshairState; import org.jfree.chart.plot.Plot; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.PlotRenderingInfo; import org.jfree.chart.plot.XYPlot; import org.jfree.chart.urls.XYURLGenerator; import org.jfree.chart.util.SerialUtilities; import org.jfree.data.xy.XYDataset; /** * Standard item renderer for an {@link XYPlot}. This class can draw (a) * shapes at each point, or (b) lines between points, or (c) both shapes and * lines. * <P> * This renderer has been retained for historical reasons and, in general, you * should use the {@link XYLineAndShapeRenderer} class instead. */ public class StandardXYItemRenderer extends AbstractXYItemRenderer implements XYItemRenderer, Cloneable, PublicCloneable, Serializable { /** For serialization. */ private static final long serialVersionUID = -3271351259436865995L; /** Constant for the type of rendering (shapes only). */ public static final int SHAPES = 1; /** Constant for the type of rendering (lines only). */ public static final int LINES = 2; /** Constant for the type of rendering (shapes and lines). */ public static final int SHAPES_AND_LINES = SHAPES | LINES; /** Constant for the type of rendering (images only). */ public static final int IMAGES = 4; /** Constant for the type of rendering (discontinuous lines). */ public static final int DISCONTINUOUS = 8; /** Constant for the type of rendering (discontinuous lines). */ public static final int DISCONTINUOUS_LINES = LINES | DISCONTINUOUS; /** A flag indicating whether or not shapes are drawn at each XY point. */ private boolean baseShapesVisible; /** A flag indicating whether or not lines are drawn between XY points. */ private boolean plotLines; /** A flag indicating whether or not images are drawn between XY points. */ private boolean plotImages; /** A flag controlling whether or not discontinuous lines are used. */ private boolean plotDiscontinuous; /** Specifies how the gap threshold value is interpreted. */ private UnitType gapThresholdType = UnitType.RELATIVE; /** Threshold for deciding when to discontinue a line. */ private double gapThreshold = 1.0; /** * A table of flags that control (per series) whether or not shapes are * filled. */ private BooleanList seriesShapesFilled; /** The default value returned by the getShapeFilled() method. */ private boolean baseShapesFilled; /** * A flag that controls whether or not each series is drawn as a single * path. */ private boolean drawSeriesLineAsPath; /** * The shape that is used to represent a line in the legend. * This should never be set to <code>null</code>. */ private transient Shape legendLine; /** * Constructs a new renderer. */ public StandardXYItemRenderer() { this(LINES, null); } /** * Constructs a new renderer. To specify the type of renderer, use one of * the constants: {@link #SHAPES}, {@link #LINES} or * {@link #SHAPES_AND_LINES}. * * @param type the type. */ public StandardXYItemRenderer(int type) { this(type, null); } /** * Constructs a new renderer. To specify the type of renderer, use one of * the constants: {@link #SHAPES}, {@link #LINES} or * {@link #SHAPES_AND_LINES}. * * @param type the type of renderer. * @param toolTipGenerator the item label generator (<code>null</code> * permitted). */ public StandardXYItemRenderer(int type, XYToolTipGenerator toolTipGenerator) { this(type, toolTipGenerator, null); } /** * Constructs a new renderer. To specify the type of renderer, use one of * the constants: {@link #SHAPES}, {@link #LINES} or * {@link #SHAPES_AND_LINES}. * * @param type the type of renderer. * @param toolTipGenerator the item label generator (<code>null</code> * permitted). * @param urlGenerator the URL generator. */ public StandardXYItemRenderer(int type, XYToolTipGenerator toolTipGenerator, XYURLGenerator urlGenerator) { super(); setDefaultToolTipGenerator(toolTipGenerator); setURLGenerator(urlGenerator); if ((type & SHAPES) != 0) { this.baseShapesVisible = true; } if ((type & LINES) != 0) { this.plotLines = true; } if ((type & IMAGES) != 0) { this.plotImages = true; } if ((type & DISCONTINUOUS) != 0) { this.plotDiscontinuous = true; } this.seriesShapesFilled = new BooleanList(); this.baseShapesFilled = true; this.legendLine = new Line2D.Double(-7.0, 0.0, 7.0, 0.0); this.drawSeriesLineAsPath = false; } /** * Returns true if shapes are being plotted by the renderer. * * @return <code>true</code> if shapes are being plotted by the renderer. * * @see #setBaseShapesVisible */ public boolean getBaseShapesVisible() { return this.baseShapesVisible; } /** * Sets the flag that controls whether or not a shape is plotted at each * data point. * * @param flag the flag. * * @see #getBaseShapesVisible */ public void setBaseShapesVisible(boolean flag) { if (this.baseShapesVisible != flag) { this.baseShapesVisible = flag; fireChangeEvent(); } } // SHAPES FILLED /** * Returns the flag used to control whether or not the shape for an item is * filled. * <p> * The default implementation passes control to the * <code>getSeriesShapesFilled</code> method. You can override this method * if you require different behaviour. * * @param series the series index (zero-based). * @param item the item index (zero-based). * * @return A boolean. * * @see #getSeriesShapesFilled(int) */ public boolean getItemShapeFilled(int series, int item) { Boolean flag = this.seriesShapesFilled.getBoolean(series); if (flag != null) { return flag; } else { return this.baseShapesFilled; } } /** * Returns the flag used to control whether or not the shapes for a series * are filled. * * @param series the series index (zero-based). * * @return A boolean. */ public Boolean getSeriesShapesFilled(int series) { return this.seriesShapesFilled.getBoolean(series); } /** * Sets the 'shapes filled' flag for a series and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param series the series index (zero-based). * @param flag the flag. * * @see #getSeriesShapesFilled(int) */ public void setSeriesShapesFilled(int series, Boolean flag) { this.seriesShapesFilled.setBoolean(series, flag); fireChangeEvent(); } /** * Returns the base 'shape filled' attribute. * * @return The base flag. * * @see #setBaseShapesFilled(boolean) */ public boolean getBaseShapesFilled() { return this.baseShapesFilled; } /** * Sets the base 'shapes filled' flag and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param flag the flag. * * @see #getBaseShapesFilled() */ public void setBaseShapesFilled(boolean flag) { this.baseShapesFilled = flag; } /** * Returns true if lines are being plotted by the renderer. * * @return <code>true</code> if lines are being plotted by the renderer. * * @see #setPlotLines(boolean) */ public boolean getPlotLines() { return this.plotLines; } /** * Sets the flag that controls whether or not a line is plotted between * each data point and sends a {@link RendererChangeEvent} to all * registered listeners. * * @param flag the flag. * * @see #getPlotLines() */ public void setPlotLines(boolean flag) { if (this.plotLines != flag) { this.plotLines = flag; fireChangeEvent(); } } /** * Returns the gap threshold type (relative or absolute). * * @return The type. * * @see #setGapThresholdType(UnitType) */ public UnitType getGapThresholdType() { return this.gapThresholdType; } /** * Sets the gap threshold type and sends a {@link RendererChangeEvent} to * all registered listeners. * * @param thresholdType the type (<code>null</code> not permitted). * * @see #getGapThresholdType() */ public void setGapThresholdType(UnitType thresholdType) { if (thresholdType == null) { throw new IllegalArgumentException( "Null 'thresholdType' argument."); } this.gapThresholdType = thresholdType; fireChangeEvent(); } /** * Returns the gap threshold for discontinuous lines. * * @return The gap threshold. * * @see #setGapThreshold(double) */ public double getGapThreshold() { return this.gapThreshold; } /** * Sets the gap threshold for discontinuous lines and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param t the threshold. * * @see #getGapThreshold() */ public void setGapThreshold(double t) { this.gapThreshold = t; fireChangeEvent(); } /** * Returns true if images are being plotted by the renderer. * * @return <code>true</code> if images are being plotted by the renderer. * * @see #setPlotImages(boolean) */ public boolean getPlotImages() { return this.plotImages; } /** * Sets the flag that controls whether or not an image is drawn at each * data point and sends a {@link RendererChangeEvent} to all registered * listeners. * * @param flag the flag. * * @see #getPlotImages() */ public void setPlotImages(boolean flag) { if (this.plotImages != flag) { this.plotImages = flag; fireChangeEvent(); } } /** * Returns a flag that controls whether or not the renderer shows * discontinuous lines. * * @return <code>true</code> if lines should be discontinuous. */ public boolean getPlotDiscontinuous() { return this.plotDiscontinuous; } /** * Sets the flag that controls whether or not the renderer shows * discontinuous lines, and sends a {@link RendererChangeEvent} to all * registered listeners. * * @param flag the new flag value. * * @since 1.0.5 */ public void setPlotDiscontinuous(boolean flag) { if (this.plotDiscontinuous != flag) { this.plotDiscontinuous = flag; fireChangeEvent(); } } /** * Returns a flag that controls whether or not each series is drawn as a * single path. * * @return A boolean. * * @see #setDrawSeriesLineAsPath(boolean) */ public boolean getDrawSeriesLineAsPath() { return this.drawSeriesLineAsPath; } /** * Sets the flag that controls whether or not each series is drawn as a * single path. * * @param flag the flag. * * @see #getDrawSeriesLineAsPath() */ public void setDrawSeriesLineAsPath(boolean flag) { this.drawSeriesLineAsPath = flag; } /** * Returns the shape used to represent a line in the legend. * * @return The legend line (never <code>null</code>). * * @see #setLegendLine(Shape) */ public Shape getLegendLine() { return this.legendLine; } /** * Sets the shape used as a line in each legend item and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param line the line (<code>null</code> not permitted). * * @see #getLegendLine() */ public void setLegendLine(Shape line) { if (line == null) { throw new IllegalArgumentException("Null 'line' argument."); } this.legendLine = line; fireChangeEvent(); } /** * Returns a legend item for a series. * * @param datasetIndex the dataset index (zero-based). * @param series the series index (zero-based). * * @return A legend item for the series. */ @Override public LegendItem getLegendItem(int datasetIndex, int series) { XYPlot plot = getPlot(); if (plot == null) { return null; } LegendItem result = null; XYDataset dataset = plot.getDataset(datasetIndex); if (dataset != null) { if (getItemVisible(series, 0)) { String label = getLegendItemLabelGenerator().generateLabel( dataset, series); String description = label; String toolTipText = null; if (getLegendItemToolTipGenerator() != null) { toolTipText = getLegendItemToolTipGenerator().generateLabel( dataset, series); } String urlText = null; if (getLegendItemURLGenerator() != null) { urlText = getLegendItemURLGenerator().generateLabel( dataset, series); } Shape shape = lookupLegendShape(series); boolean shapeFilled = getItemShapeFilled(series, 0); Paint paint = lookupSeriesPaint(series); Paint linePaint = paint; Stroke lineStroke = lookupSeriesStroke(series); result = new LegendItem(label, description, toolTipText, urlText, this.baseShapesVisible, shape, shapeFilled, paint, !shapeFilled, paint, lineStroke, this.plotLines, this.legendLine, lineStroke, linePaint); result.setLabelFont(lookupLegendTextFont(series)); Paint labelPaint = lookupLegendTextPaint(series); if (labelPaint != null) { result.setLabelPaint(labelPaint); } result.setDataset(dataset); result.setDatasetIndex(datasetIndex); result.setSeriesKey(dataset.getSeriesKey(series)); result.setSeriesIndex(series); } } return result; } /** * Records the state for the renderer. This is used to preserve state * information between calls to the drawItem() method for a single chart * drawing. */ public static class State extends XYItemRendererState { /** The path for the current series. */ public GeneralPath seriesPath; /** The series index. */ private int seriesIndex; /** * A flag that indicates if the last (x, y) point was 'good' * (non-null). */ private boolean lastPointGood; /** * Creates a new state instance. * * @param info the plot rendering info. */ public State(PlotRenderingInfo info) { super(info); } /** * Returns a flag that indicates if the last point drawn (in the * current series) was 'good' (non-null). * * @return A boolean. */ public boolean isLastPointGood() { return this.lastPointGood; } /** * Sets a flag that indicates if the last point drawn (in the current * series) was 'good' (non-null). * * @param good the flag. */ public void setLastPointGood(boolean good) { this.lastPointGood = good; } /** * Returns the series index for the current path. * * @return The series index for the current path. */ public int getSeriesIndex() { return this.seriesIndex; } /** * Sets the series index for the current path. * * @param index the index. */ public void setSeriesIndex(int index) { this.seriesIndex = index; } } /** * Initialises the renderer. * <P> * This method will be called before the first item is rendered, giving the * renderer an opportunity to initialise any state information it wants to * maintain. The renderer can do nothing if it chooses. * * @param g2 the graphics device. * @param dataArea the area inside the axes. * @param plot the plot. * @param data the data. * @param info an optional info collection object to return data back to * the caller. * * @return The renderer state. */ @Override public XYItemRendererState initialise(Graphics2D g2, Rectangle2D dataArea, XYPlot plot, XYDataset data, PlotRenderingInfo info) { State state = new State(info); state.seriesPath = new GeneralPath(); state.seriesIndex = -1; return state; } /** * Draws the visual representation of a single data item. * * @param g2 the graphics device. * @param state the renderer state. * @param dataArea the area within which the data is being drawn. * @param info collects information about the drawing. * @param plot the plot (can be used to obtain standard color information * etc). * @param domainAxis the domain axis. * @param rangeAxis the range axis. * @param dataset the dataset. * @param series the series index (zero-based). * @param item the item index (zero-based). * @param crosshairState crosshair information for the plot * (<code>null</code> permitted). * @param pass the pass index. */ @Override public void drawItem(Graphics2D g2, XYItemRendererState state, Rectangle2D dataArea, PlotRenderingInfo info, XYPlot plot, ValueAxis domainAxis, ValueAxis rangeAxis, XYDataset dataset, int series, int item, CrosshairState crosshairState, int pass) { boolean itemVisible = getItemVisible(series, item); // setup for collecting optional entity info... Shape entityArea = null; EntityCollection entities = null; if (info != null) { entities = info.getOwner().getEntityCollection(); } PlotOrientation orientation = plot.getOrientation(); Paint paint = getItemPaint(series, item); Stroke seriesStroke = getItemStroke(series, item); g2.setPaint(paint); g2.setStroke(seriesStroke); // get the data point... double x1 = dataset.getXValue(series, item); double y1 = dataset.getYValue(series, item); if (Double.isNaN(x1) || Double.isNaN(y1)) { itemVisible = false; } RectangleEdge xAxisLocation = plot.getDomainAxisEdge(); RectangleEdge yAxisLocation = plot.getRangeAxisEdge(); double transX1 = domainAxis.valueToJava2D(x1, dataArea, xAxisLocation); double transY1 = rangeAxis.valueToJava2D(y1, dataArea, yAxisLocation); if (getPlotLines()) { if (this.drawSeriesLineAsPath) { State s = (State) state; if (s.getSeriesIndex() != series) { // we are starting a new series path s.seriesPath.reset(); s.lastPointGood = false; s.setSeriesIndex(series); } // update path to reflect latest point if (itemVisible && !Double.isNaN(transX1) && !Double.isNaN(transY1)) { float x = (float) transX1; float y = (float) transY1; if (orientation == PlotOrientation.HORIZONTAL) { x = (float) transY1; y = (float) transX1; } if (s.isLastPointGood()) { // TODO: check threshold s.seriesPath.lineTo(x, y); } else { s.seriesPath.moveTo(x, y); } s.setLastPointGood(true); } else { s.setLastPointGood(false); } if (item == dataset.getItemCount(series) - 1) { if (s.seriesIndex == series) { // draw path g2.setStroke(lookupSeriesStroke(series)); g2.setPaint(lookupSeriesPaint(series)); g2.draw(s.seriesPath); } } } else if (item != 0 && itemVisible) { // get the previous data point... double x0 = dataset.getXValue(series, item - 1); double y0 = dataset.getYValue(series, item - 1); if (!Double.isNaN(x0) && !Double.isNaN(y0)) { boolean drawLine = true; if (getPlotDiscontinuous()) { // only draw a line if the gap between the current and // previous data point is within the threshold int numX = dataset.getItemCount(series); double minX = dataset.getXValue(series, 0); double maxX = dataset.getXValue(series, numX - 1); if (this.gapThresholdType == UnitType.ABSOLUTE) { drawLine = Math.abs(x1 - x0) <= this.gapThreshold; } else { drawLine = Math.abs(x1 - x0) <= ((maxX - minX) / numX * getGapThreshold()); } } if (drawLine) { double transX0 = domainAxis.valueToJava2D(x0, dataArea, xAxisLocation); double transY0 = rangeAxis.valueToJava2D(y0, dataArea, yAxisLocation); // only draw if we have good values if (Double.isNaN(transX0) || Double.isNaN(transY0) || Double.isNaN(transX1) || Double.isNaN(transY1)) { return; } if (orientation == PlotOrientation.HORIZONTAL) { state.workingLine.setLine(transY0, transX0, transY1, transX1); } else if (orientation == PlotOrientation.VERTICAL) { state.workingLine.setLine(transX0, transY0, transX1, transY1); } if (state.workingLine.intersects(dataArea)) { g2.draw(state.workingLine); } } } } } // we needed to get this far even for invisible items, to ensure that // seriesPath updates happened, but now there is nothing more we need // to do for non-visible items... if (!itemVisible) { return; } if (getBaseShapesVisible()) { Shape shape = getItemShape(series, item); if (orientation == PlotOrientation.HORIZONTAL) { shape = ShapeUtilities.createTranslatedShape(shape, transY1, transX1); } else if (orientation == PlotOrientation.VERTICAL) { shape = ShapeUtilities.createTranslatedShape(shape, transX1, transY1); } if (shape.intersects(dataArea)) { if (getItemShapeFilled(series, item)) { g2.fill(shape); } else { g2.draw(shape); } } entityArea = shape; } if (getPlotImages()) { Image image = getImage(plot, series, item, transX1, transY1); if (image != null) { Point hotspot = getImageHotspot(plot, series, item, transX1, transY1, image); g2.drawImage(image, (int) (transX1 - hotspot.getX()), (int) (transY1 - hotspot.getY()), null); entityArea = new Rectangle2D.Double(transX1 - hotspot.getX(), transY1 - hotspot.getY(), image.getWidth(null), image.getHeight(null)); } } double xx = transX1; double yy = transY1; if (orientation == PlotOrientation.HORIZONTAL) { xx = transY1; yy = transX1; } // draw the item label if there is one... if (isItemLabelVisible(series, item)) { drawItemLabel(g2, orientation, dataset, series, item, xx, yy, (y1 < 0.0)); } int domainAxisIndex = plot.getDomainAxisIndex(domainAxis); int rangeAxisIndex = plot.getRangeAxisIndex(rangeAxis); updateCrosshairValues(crosshairState, x1, y1, domainAxisIndex, rangeAxisIndex, transX1, transY1, orientation); // add an entity for the item... if (entities != null && isPointInRect(dataArea, xx, yy)) { addEntity(entities, entityArea, dataset, series, item, xx, yy); } } /** * Tests this renderer for equality with another object. * * @param obj the object (<code>null</code> permitted). * * @return A boolean. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof StandardXYItemRenderer)) { return false; } StandardXYItemRenderer that = (StandardXYItemRenderer) obj; if (this.baseShapesVisible != that.baseShapesVisible) { return false; } if (this.plotLines != that.plotLines) { return false; } if (this.plotImages != that.plotImages) { return false; } if (this.plotDiscontinuous != that.plotDiscontinuous) { return false; } if (this.gapThresholdType != that.gapThresholdType) { return false; } if (this.gapThreshold != that.gapThreshold) { return false; } if (!this.seriesShapesFilled.equals(that.seriesShapesFilled)) { return false; } if (this.baseShapesFilled != that.baseShapesFilled) { return false; } if (this.drawSeriesLineAsPath != that.drawSeriesLineAsPath) { return false; } if (!ShapeUtilities.equal(this.legendLine, that.legendLine)) { return false; } return super.equals(obj); } /** * Returns a clone of the renderer. * * @return A clone. * * @throws CloneNotSupportedException if the renderer cannot be cloned. */ @Override public Object clone() throws CloneNotSupportedException { StandardXYItemRenderer clone = (StandardXYItemRenderer) super.clone(); clone.seriesShapesFilled = (BooleanList) this.seriesShapesFilled.clone(); clone.legendLine = ShapeUtilities.clone(this.legendLine); return clone; } //////////////////////////////////////////////////////////////////////////// // PROTECTED METHODS // These provide the opportunity to subclass the standard renderer and // create custom effects. //////////////////////////////////////////////////////////////////////////// /** * Returns the image used to draw a single data item. * * @param plot the plot (can be used to obtain standard color information * etc). * @param series the series index. * @param item the item index. * @param x the x value of the item. * @param y the y value of the item. * * @return The image. * * @see #getPlotImages() */ protected Image getImage(Plot plot, int series, int item, double x, double y) { // this method must be overridden if you want to display images return null; } /** * Returns the hotspot of the image used to draw a single data item. * The hotspot is the point relative to the top left of the image * that should indicate the data item. The default is the center of the * image. * * @param plot the plot (can be used to obtain standard color information * etc). * @param image the image (can be used to get size information about the * image) * @param series the series index * @param item the item index * @param x the x value of the item * @param y the y value of the item * * @return The hotspot used to draw the data item. */ protected Point getImageHotspot(Plot plot, int series, int item, double x, double y, Image image) { int height = image.getHeight(null); int width = image.getWidth(null); return new Point(width / 2, height / 2); } /** * Provides serialization support. * * @param stream the input stream. * * @throws IOException if there is an I/O error. * @throws ClassNotFoundException if there is a classpath problem. */ private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); this.legendLine = SerialUtilities.readShape(stream); } /** * Provides serialization support. * * @param stream the output stream. * * @throws IOException if there is an I/O error. */ private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); SerialUtilities.writeShape(this.legendLine, stream); } }
38,100
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
WaterfallBarRenderer.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/renderer/category/WaterfallBarRenderer.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2013, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ------------------------- * WaterfallBarRenderer.java * ------------------------- * (C) Copyright 2003-2013, by Object Refinery Limited and Contributors. * * Original Author: Darshan Shah; * Contributor(s): David Gilbert (for Object Refinery Limited); * * Changes * ------- * 20-Oct-2003 : Version 1, contributed by Darshan Shah (DG); * 06-Nov-2003 : Changed order of parameters in constructor, and added support * for GradientPaint (DG); * 10-Feb-2004 : Updated drawItem() method to make cut-and-paste overriding * easier. Also fixed a bug that meant the minimum bar length * was being ignored (DG); * 04-Oct-2004 : Reworked equals() method and renamed PaintUtils * --> PaintUtilities (DG); * 05-Nov-2004 : Modified drawItem() signature (DG); * 07-Jan-2005 : Renamed getRangeExtent() --> findRangeBounds (DG); * 23-Feb-2005 : Added argument checking (DG); * 20-Apr-2005 : Renamed CategoryLabelGenerator * --> CategoryItemLabelGenerator (DG); * 09-Jun-2005 : Use addItemEntity() from superclass (DG); * 27-Mar-2008 : Fixed error in findRangeBounds() method (DG); * 26-Sep-2008 : Fixed bug with bar alignment when maximumBarWidth is * applied (DG); * 04-Feb-2009 : Updated findRangeBounds to handle null dataset consistently * with other renderers (DG); * 19-May-2009 : Fixed FindBugs warnings, patch by Michal Wozniak (DG); * 17-Jun-2012 : Removed JCommon dependencies (DG); * */ package org.jfree.chart.renderer.category; import java.awt.Color; import java.awt.GradientPaint; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.Stroke; import java.awt.geom.Rectangle2D; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import org.jfree.chart.axis.CategoryAxis; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.ui.GradientPaintTransformType; import org.jfree.chart.ui.RectangleEdge; import org.jfree.chart.ui.StandardGradientPaintTransformer; import org.jfree.chart.util.PaintUtilities; import org.jfree.chart.entity.EntityCollection; import org.jfree.chart.event.RendererChangeEvent; import org.jfree.chart.labels.CategoryItemLabelGenerator; import org.jfree.chart.plot.CategoryPlot; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.renderer.AbstractRenderer; import org.jfree.chart.util.ParamChecks; import org.jfree.chart.util.SerialUtilities; import org.jfree.data.Range; import org.jfree.data.category.CategoryDataset; /** * A renderer that handles the drawing of waterfall bar charts, for use with * the {@link CategoryPlot} class. Some quirks to note: * <ul> * <li>the value in the last category of the dataset should be (redundantly) * specified as the sum of the items in the preceding categories - otherwise * the final bar in the plot will be incorrectly plotted;</li> * <li>the bar colors are defined using special methods in this class - the * inherited methods (for example, * {@link AbstractRenderer#setSeriesPaint(int, Paint)}) are ignored;</li> * </ul> * The example shown here is generated by the * <code>WaterfallChartDemo1.java</code> program included in the JFreeChart * Demo Collection: * <br><br> * <img src="../../../../../images/WaterfallBarRendererSample.png" * alt="WaterfallBarRendererSample.png" /> */ public class WaterfallBarRenderer extends BarRenderer { /** For serialization. */ private static final long serialVersionUID = -2482910643727230911L; /** The paint used to draw the first bar. */ private transient Paint firstBarPaint; /** The paint used to draw the last bar. */ private transient Paint lastBarPaint; /** The paint used to draw bars having positive values. */ private transient Paint positiveBarPaint; /** The paint used to draw bars having negative values. */ private transient Paint negativeBarPaint; /** * Constructs a new renderer with default values for the bar colors. */ public WaterfallBarRenderer() { this(new GradientPaint(0.0f, 0.0f, new Color(0x22, 0x22, 0xFF), 0.0f, 0.0f, new Color(0x66, 0x66, 0xFF)), new GradientPaint(0.0f, 0.0f, new Color(0x22, 0xFF, 0x22), 0.0f, 0.0f, new Color(0x66, 0xFF, 0x66)), new GradientPaint(0.0f, 0.0f, new Color(0xFF, 0x22, 0x22), 0.0f, 0.0f, new Color(0xFF, 0x66, 0x66)), new GradientPaint(0.0f, 0.0f, new Color(0xFF, 0xFF, 0x22), 0.0f, 0.0f, new Color(0xFF, 0xFF, 0x66))); } /** * Constructs a new waterfall renderer. * * @param firstBarPaint the color of the first bar (<code>null</code> not * permitted). * @param positiveBarPaint the color for bars with positive values * (<code>null</code> not permitted). * @param negativeBarPaint the color for bars with negative values * (<code>null</code> not permitted). * @param lastBarPaint the color of the last bar (<code>null</code> not * permitted). */ public WaterfallBarRenderer(Paint firstBarPaint, Paint positiveBarPaint, Paint negativeBarPaint, Paint lastBarPaint) { super(); ParamChecks.nullNotPermitted(firstBarPaint, "firstBarPaint"); ParamChecks.nullNotPermitted(positiveBarPaint, "positiveBarPaint"); ParamChecks.nullNotPermitted(negativeBarPaint, "negativeBarPaint"); ParamChecks.nullNotPermitted(lastBarPaint, "lastBarPaint"); this.firstBarPaint = firstBarPaint; this.lastBarPaint = lastBarPaint; this.positiveBarPaint = positiveBarPaint; this.negativeBarPaint = negativeBarPaint; setGradientPaintTransformer(new StandardGradientPaintTransformer( GradientPaintTransformType.CENTER_VERTICAL)); setMinimumBarLength(1.0); } /** * Returns the paint used to draw the first bar. * * @return The paint (never <code>null</code>). */ public Paint getFirstBarPaint() { return this.firstBarPaint; } /** * Sets the paint that will be used to draw the first bar and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param paint the paint (<code>null</code> not permitted). */ public void setFirstBarPaint(Paint paint) { ParamChecks.nullNotPermitted(paint, "paint"); this.firstBarPaint = paint; fireChangeEvent(); } /** * Returns the paint used to draw the last bar. * * @return The paint (never <code>null</code>). */ public Paint getLastBarPaint() { return this.lastBarPaint; } /** * Sets the paint that will be used to draw the last bar and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param paint the paint (<code>null</code> not permitted). */ public void setLastBarPaint(Paint paint) { ParamChecks.nullNotPermitted(paint, "paint"); this.lastBarPaint = paint; fireChangeEvent(); } /** * Returns the paint used to draw bars with positive values. * * @return The paint (never <code>null</code>). */ public Paint getPositiveBarPaint() { return this.positiveBarPaint; } /** * Sets the paint that will be used to draw bars having positive values. * * @param paint the paint (<code>null</code> not permitted). */ public void setPositiveBarPaint(Paint paint) { ParamChecks.nullNotPermitted(paint, "paint"); this.positiveBarPaint = paint; fireChangeEvent(); } /** * Returns the paint used to draw bars with negative values. * * @return The paint (never <code>null</code>). */ public Paint getNegativeBarPaint() { return this.negativeBarPaint; } /** * Sets the paint that will be used to draw bars having negative values, * and sends a {@link RendererChangeEvent} to all registered listeners. * * @param paint the paint (<code>null</code> not permitted). */ public void setNegativeBarPaint(Paint paint) { ParamChecks.nullNotPermitted(paint, "paint"); this.negativeBarPaint = paint; fireChangeEvent(); } /** * Returns the range of values the renderer requires to display all the * items from the specified dataset. * * @param dataset the dataset (<code>null</code> not permitted). * * @return The range (or <code>null</code> if the dataset is empty). */ @Override public Range findRangeBounds(CategoryDataset dataset) { if (dataset == null) { return null; } boolean allItemsNull = true; // we'll set this to false if there is at // least one non-null data item... double minimum = 0.0; double maximum = 0.0; int columnCount = dataset.getColumnCount(); for (int row = 0; row < dataset.getRowCount(); row++) { double runningTotal = 0.0; for (int column = 0; column <= columnCount - 1; column++) { Number n = dataset.getValue(row, column); if (n != null) { allItemsNull = false; double value = n.doubleValue(); if (column == columnCount - 1) { // treat the last column value as an absolute runningTotal = value; } else { runningTotal = runningTotal + value; } minimum = Math.min(minimum, runningTotal); maximum = Math.max(maximum, runningTotal); } } } if (!allItemsNull) { return new Range(minimum, maximum); } else { return null; } } /** * Draws the bar for a single (series, category) data item. * * @param g2 the graphics device. * @param state the renderer state. * @param dataArea the data area. * @param plot the plot. * @param domainAxis the domain axis. * @param rangeAxis the range axis. * @param dataset the dataset. * @param row the row index (zero-based). * @param column the column index (zero-based). * @param pass the pass index. */ @Override public void drawItem(Graphics2D g2, CategoryItemRendererState state, Rectangle2D dataArea, CategoryPlot plot, CategoryAxis domainAxis, ValueAxis rangeAxis, CategoryDataset dataset, int row, int column, int pass) { double previous = state.getSeriesRunningTotal(); if (column == dataset.getColumnCount() - 1) { previous = 0.0; } double current = 0.0; Number n = dataset.getValue(row, column); if (n != null) { current = previous + n.doubleValue(); } state.setSeriesRunningTotal(current); int categoryCount = getColumnCount(); PlotOrientation orientation = plot.getOrientation(); double rectX = 0.0; double rectY = 0.0; RectangleEdge rangeAxisLocation = plot.getRangeAxisEdge(); // Y0 double j2dy0 = rangeAxis.valueToJava2D(previous, dataArea, rangeAxisLocation); // Y1 double j2dy1 = rangeAxis.valueToJava2D(current, dataArea, rangeAxisLocation); double valDiff = current - previous; if (j2dy1 < j2dy0) { double temp = j2dy1; j2dy1 = j2dy0; j2dy0 = temp; } // BAR WIDTH double rectWidth = state.getBarWidth(); // BAR HEIGHT double rectHeight = Math.max(getMinimumBarLength(), Math.abs(j2dy1 - j2dy0)); Comparable seriesKey = dataset.getRowKey(row); Comparable categoryKey = dataset.getColumnKey(column); if (orientation == PlotOrientation.HORIZONTAL) { rectY = domainAxis.getCategorySeriesMiddle(categoryKey, seriesKey, dataset, getItemMargin(), dataArea, RectangleEdge.LEFT); rectX = j2dy0; rectHeight = state.getBarWidth(); rectY = rectY - rectHeight / 2.0; rectWidth = Math.max(getMinimumBarLength(), Math.abs(j2dy1 - j2dy0)); } else if (orientation == PlotOrientation.VERTICAL) { rectX = domainAxis.getCategorySeriesMiddle(categoryKey, seriesKey, dataset, getItemMargin(), dataArea, RectangleEdge.TOP); rectX = rectX - rectWidth / 2.0; rectY = j2dy0; } Rectangle2D bar = new Rectangle2D.Double(rectX, rectY, rectWidth, rectHeight); Paint seriesPaint; if (column == 0) { seriesPaint = getFirstBarPaint(); } else if (column == categoryCount - 1) { seriesPaint = getLastBarPaint(); } else { if (valDiff >= 0.0) { seriesPaint = getPositiveBarPaint(); } else { seriesPaint = getNegativeBarPaint(); } } if (getGradientPaintTransformer() != null && seriesPaint instanceof GradientPaint) { GradientPaint gp = (GradientPaint) seriesPaint; seriesPaint = getGradientPaintTransformer().transform(gp, bar); } g2.setPaint(seriesPaint); g2.fill(bar); // draw the outline... if (isDrawBarOutline() && state.getBarWidth() > BAR_OUTLINE_WIDTH_THRESHOLD) { Stroke stroke = getItemOutlineStroke(row, column); Paint paint = getItemOutlinePaint(row, column); if (stroke != null && paint != null) { g2.setStroke(stroke); g2.setPaint(paint); g2.draw(bar); } } CategoryItemLabelGenerator generator = getItemLabelGenerator(row, column); if (generator != null && isItemLabelVisible(row, column)) { drawItemLabel(g2, dataset, row, column, plot, generator, bar, (valDiff < 0.0)); } // add an item entity, if this information is being collected EntityCollection entities = state.getEntityCollection(); if (entities != null) { addItemEntity(entities, dataset, row, column, bar); } } /** * Tests an object for equality with this instance. * * @param obj the object (<code>null</code> permitted). * * @return A boolean. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!super.equals(obj)) { return false; } if (!(obj instanceof WaterfallBarRenderer)) { return false; } WaterfallBarRenderer that = (WaterfallBarRenderer) obj; if (!PaintUtilities.equal(this.firstBarPaint, that.firstBarPaint)) { return false; } if (!PaintUtilities.equal(this.lastBarPaint, that.lastBarPaint)) { return false; } if (!PaintUtilities.equal(this.positiveBarPaint, that.positiveBarPaint)) { return false; } if (!PaintUtilities.equal(this.negativeBarPaint, that.negativeBarPaint)) { return false; } return true; } /** * Provides serialization support. * * @param stream the output stream. * * @throws IOException if there is an I/O error. */ private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); SerialUtilities.writePaint(this.firstBarPaint, stream); SerialUtilities.writePaint(this.lastBarPaint, stream); SerialUtilities.writePaint(this.positiveBarPaint, stream); SerialUtilities.writePaint(this.negativeBarPaint, stream); } /** * Provides serialization support. * * @param stream the input stream. * * @throws IOException if there is an I/O error. * @throws ClassNotFoundException if there is a classpath problem. */ private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); this.firstBarPaint = SerialUtilities.readPaint(stream); this.lastBarPaint = SerialUtilities.readPaint(stream); this.positiveBarPaint = SerialUtilities.readPaint(stream); this.negativeBarPaint = SerialUtilities.readPaint(stream); } }
18,173
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
GanttRenderer.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/renderer/category/GanttRenderer.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ------------------ * GanttRenderer.java * ------------------ * (C) Copyright 2003-2012, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 16-Sep-2003 : Version 1 (DG); * 23-Sep-2003 : Fixed Checkstyle issues (DG); * 21-Oct-2003 : Bar width moved into CategoryItemRendererState (DG); * 03-Feb-2004 : Added get/set methods for attributes (DG); * 12-Aug-2004 : Fixed rendering problem with maxBarWidth attribute (DG); * 05-Nov-2004 : Modified drawItem() signature (DG); * 20-Apr-2005 : Renamed CategoryLabelGenerator * --> CategoryItemLabelGenerator (DG); * 01-Dec-2005 : Fix for bug 1369954, drawBarOutline flag ignored (DG); * ------------- JFREECHART 1.0.x -------------------------------------------- * 17-Jan-2006 : Set includeBaseInRange flag to false (DG); * 20-Mar-2007 : Implemented equals() and fixed serialization (DG); * 24-Jun-2008 : Added new barPainter mechanism (DG); * 26-Jun-2008 : Added crosshair support (DG); * 19-May-2009 : Fixed FindBugs warnings, patch by Michal Wozniak (DG); * 17-Jun-2012 : Removed JCommon dependencies (DG); * */ package org.jfree.chart.renderer.category; import java.awt.Color; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.Stroke; import java.awt.geom.Rectangle2D; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import org.jfree.chart.axis.CategoryAxis; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.ui.RectangleEdge; import org.jfree.chart.util.PaintUtilities; import org.jfree.chart.entity.EntityCollection; import org.jfree.chart.event.RendererChangeEvent; import org.jfree.chart.labels.CategoryItemLabelGenerator; import org.jfree.chart.plot.CategoryPlot; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.util.SerialUtilities; import org.jfree.data.category.CategoryDataset; import org.jfree.data.gantt.GanttCategoryDataset; /** * A renderer for simple Gantt charts. The example shown * here is generated by the <code>GanttDemo1.java</code> program * included in the JFreeChart Demo Collection: * <br><br> * <img src="../../../../../images/GanttRendererSample.png" * alt="GanttRendererSample.png" /> */ public class GanttRenderer extends IntervalBarRenderer implements Serializable { /** For serialization. */ private static final long serialVersionUID = -4010349116350119512L; /** The paint for displaying the percentage complete. */ private transient Paint completePaint; /** The paint for displaying the incomplete part of a task. */ private transient Paint incompletePaint; /** * Controls the starting edge of the progress indicator (expressed as a * percentage of the overall bar width). */ private double startPercent; /** * Controls the ending edge of the progress indicator (expressed as a * percentage of the overall bar width). */ private double endPercent; /** * Creates a new renderer. */ public GanttRenderer() { super(); setIncludeBaseInRange(false); this.completePaint = Color.GREEN; this.incompletePaint = Color.RED; this.startPercent = 0.35; this.endPercent = 0.65; } /** * Returns the paint used to show the percentage complete. * * @return The paint (never <code>null</code>. * * @see #setCompletePaint(Paint) */ public Paint getCompletePaint() { return this.completePaint; } /** * Sets the paint used to show the percentage complete and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param paint the paint (<code>null</code> not permitted). * * @see #getCompletePaint() */ public void setCompletePaint(Paint paint) { if (paint == null) { throw new IllegalArgumentException("Null 'paint' argument."); } this.completePaint = paint; fireChangeEvent(); } /** * Returns the paint used to show the percentage incomplete. * * @return The paint (never <code>null</code>). * * @see #setCompletePaint(Paint) */ public Paint getIncompletePaint() { return this.incompletePaint; } /** * Sets the paint used to show the percentage incomplete and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param paint the paint (<code>null</code> not permitted). * * @see #getIncompletePaint() */ public void setIncompletePaint(Paint paint) { if (paint == null) { throw new IllegalArgumentException("Null 'paint' argument."); } this.incompletePaint = paint; fireChangeEvent(); } /** * Returns the position of the start of the progress indicator, as a * percentage of the bar width. * * @return The start percent. * * @see #setStartPercent(double) */ public double getStartPercent() { return this.startPercent; } /** * Sets the position of the start of the progress indicator, as a * percentage of the bar width, and sends a {@link RendererChangeEvent} to * all registered listeners. * * @param percent the percent. * * @see #getStartPercent() */ public void setStartPercent(double percent) { this.startPercent = percent; fireChangeEvent(); } /** * Returns the position of the end of the progress indicator, as a * percentage of the bar width. * * @return The end percent. * * @see #setEndPercent(double) */ public double getEndPercent() { return this.endPercent; } /** * Sets the position of the end of the progress indicator, as a percentage * of the bar width, and sends a {@link RendererChangeEvent} to all * registered listeners. * * @param percent the percent. * * @see #getEndPercent() */ public void setEndPercent(double percent) { this.endPercent = percent; fireChangeEvent(); } /** * Draws the bar for a single (series, category) data item. * * @param g2 the graphics device. * @param state the renderer state. * @param dataArea the data area. * @param plot the plot. * @param domainAxis the domain axis. * @param rangeAxis the range axis. * @param dataset the dataset. * @param row the row index (zero-based). * @param column the column index (zero-based). * @param pass the pass index. */ @Override public void drawItem(Graphics2D g2, CategoryItemRendererState state, Rectangle2D dataArea, CategoryPlot plot, CategoryAxis domainAxis, ValueAxis rangeAxis, CategoryDataset dataset, int row, int column, int pass) { if (dataset instanceof GanttCategoryDataset) { GanttCategoryDataset gcd = (GanttCategoryDataset) dataset; drawTasks(g2, state, dataArea, plot, domainAxis, rangeAxis, gcd, row, column); } else { // let the superclass handle it... super.drawItem(g2, state, dataArea, plot, domainAxis, rangeAxis, dataset, row, column, pass); } } /** * Draws the tasks/subtasks for one item. * * @param g2 the graphics device. * @param state the renderer state. * @param dataArea the data plot area. * @param plot the plot. * @param domainAxis the domain axis. * @param rangeAxis the range axis. * @param dataset the data. * @param row the row index (zero-based). * @param column the column index (zero-based). */ protected void drawTasks(Graphics2D g2, CategoryItemRendererState state, Rectangle2D dataArea, CategoryPlot plot, CategoryAxis domainAxis, ValueAxis rangeAxis, GanttCategoryDataset dataset, int row, int column) { int count = dataset.getSubIntervalCount(row, column); if (count == 0) { drawTask(g2, state, dataArea, plot, domainAxis, rangeAxis, dataset, row, column); } PlotOrientation orientation = plot.getOrientation(); for (int subinterval = 0; subinterval < count; subinterval++) { RectangleEdge rangeAxisLocation = plot.getRangeAxisEdge(); // value 0 Number value0 = dataset.getStartValue(row, column, subinterval); if (value0 == null) { return; } double translatedValue0 = rangeAxis.valueToJava2D( value0.doubleValue(), dataArea, rangeAxisLocation); // value 1 Number value1 = dataset.getEndValue(row, column, subinterval); if (value1 == null) { return; } double translatedValue1 = rangeAxis.valueToJava2D( value1.doubleValue(), dataArea, rangeAxisLocation); if (translatedValue1 < translatedValue0) { double temp = translatedValue1; translatedValue1 = translatedValue0; translatedValue0 = temp; } double rectStart = calculateBarW0(plot, plot.getOrientation(), dataArea, domainAxis, state, row, column); double rectLength = Math.abs(translatedValue1 - translatedValue0); double rectBreadth = state.getBarWidth(); // DRAW THE BARS... Rectangle2D bar = null; RectangleEdge barBase = null; if (plot.getOrientation() == PlotOrientation.HORIZONTAL) { bar = new Rectangle2D.Double(translatedValue0, rectStart, rectLength, rectBreadth); barBase = RectangleEdge.LEFT; } else if (plot.getOrientation() == PlotOrientation.VERTICAL) { bar = new Rectangle2D.Double(rectStart, translatedValue0, rectBreadth, rectLength); barBase = RectangleEdge.BOTTOM; } Rectangle2D completeBar = null; Rectangle2D incompleteBar = null; Number percent = dataset.getPercentComplete(row, column, subinterval); double start = getStartPercent(); double end = getEndPercent(); if (percent != null) { double p = percent.doubleValue(); if (orientation == PlotOrientation.HORIZONTAL) { completeBar = new Rectangle2D.Double(translatedValue0, rectStart + start * rectBreadth, rectLength * p, rectBreadth * (end - start)); incompleteBar = new Rectangle2D.Double(translatedValue0 + rectLength * p, rectStart + start * rectBreadth, rectLength * (1 - p), rectBreadth * (end - start)); } else if (orientation == PlotOrientation.VERTICAL) { completeBar = new Rectangle2D.Double(rectStart + start * rectBreadth, translatedValue0 + rectLength * (1 - p), rectBreadth * (end - start), rectLength * p); incompleteBar = new Rectangle2D.Double(rectStart + start * rectBreadth, translatedValue0, rectBreadth * (end - start), rectLength * (1 - p)); } } if (getShadowsVisible()) { getBarPainter().paintBarShadow(g2, this, row, column, bar, barBase, true); } getBarPainter().paintBar(g2, this, row, column, bar, barBase); if (completeBar != null) { g2.setPaint(getCompletePaint()); g2.fill(completeBar); } if (incompleteBar != null) { g2.setPaint(getIncompletePaint()); g2.fill(incompleteBar); } if (isDrawBarOutline() && state.getBarWidth() > BAR_OUTLINE_WIDTH_THRESHOLD) { g2.setStroke(getItemStroke(row, column)); g2.setPaint(getItemOutlinePaint(row, column)); g2.draw(bar); } if (subinterval == count - 1) { // submit the current data point as a crosshair candidate int datasetIndex = plot.indexOf(dataset); Comparable columnKey = dataset.getColumnKey(column); Comparable rowKey = dataset.getRowKey(row); double xx = domainAxis.getCategorySeriesMiddle(columnKey, rowKey, dataset, getItemMargin(), dataArea, plot.getDomainAxisEdge()); updateCrosshairValues(state.getCrosshairState(), dataset.getRowKey(row), dataset.getColumnKey(column), value1.doubleValue(), datasetIndex, xx, translatedValue1, orientation); } // collect entity and tool tip information... if (state.getInfo() != null) { EntityCollection entities = state.getEntityCollection(); if (entities != null) { addItemEntity(entities, dataset, row, column, bar); } } } } /** * Draws a single task. * * @param g2 the graphics device. * @param state the renderer state. * @param dataArea the data plot area. * @param plot the plot. * @param domainAxis the domain axis. * @param rangeAxis the range axis. * @param dataset the data. * @param row the row index (zero-based). * @param column the column index (zero-based). */ protected void drawTask(Graphics2D g2, CategoryItemRendererState state, Rectangle2D dataArea, CategoryPlot plot, CategoryAxis domainAxis, ValueAxis rangeAxis, GanttCategoryDataset dataset, int row, int column) { PlotOrientation orientation = plot.getOrientation(); RectangleEdge rangeAxisLocation = plot.getRangeAxisEdge(); // Y0 Number value0 = dataset.getEndValue(row, column); if (value0 == null) { return; } double java2dValue0 = rangeAxis.valueToJava2D(value0.doubleValue(), dataArea, rangeAxisLocation); // Y1 Number value1 = dataset.getStartValue(row, column); if (value1 == null) { return; } double java2dValue1 = rangeAxis.valueToJava2D(value1.doubleValue(), dataArea, rangeAxisLocation); if (java2dValue1 < java2dValue0) { double temp = java2dValue1; java2dValue1 = java2dValue0; java2dValue0 = temp; value1 = value0; } double rectStart = calculateBarW0(plot, orientation, dataArea, domainAxis, state, row, column); double rectBreadth = state.getBarWidth(); double rectLength = Math.abs(java2dValue1 - java2dValue0); Rectangle2D bar = null; RectangleEdge barBase = null; if (orientation == PlotOrientation.HORIZONTAL) { bar = new Rectangle2D.Double(java2dValue0, rectStart, rectLength, rectBreadth); barBase = RectangleEdge.LEFT; } else if (orientation == PlotOrientation.VERTICAL) { bar = new Rectangle2D.Double(rectStart, java2dValue1, rectBreadth, rectLength); barBase = RectangleEdge.BOTTOM; } Rectangle2D completeBar = null; Rectangle2D incompleteBar = null; Number percent = dataset.getPercentComplete(row, column); double start = getStartPercent(); double end = getEndPercent(); if (percent != null) { double p = percent.doubleValue(); if (plot.getOrientation() == PlotOrientation.HORIZONTAL) { completeBar = new Rectangle2D.Double(java2dValue0, rectStart + start * rectBreadth, rectLength * p, rectBreadth * (end - start)); incompleteBar = new Rectangle2D.Double(java2dValue0 + rectLength * p, rectStart + start * rectBreadth, rectLength * (1 - p), rectBreadth * (end - start)); } else if (plot.getOrientation() == PlotOrientation.VERTICAL) { completeBar = new Rectangle2D.Double(rectStart + start * rectBreadth, java2dValue1 + rectLength * (1 - p), rectBreadth * (end - start), rectLength * p); incompleteBar = new Rectangle2D.Double(rectStart + start * rectBreadth, java2dValue1, rectBreadth * (end - start), rectLength * (1 - p)); } } if (getShadowsVisible()) { getBarPainter().paintBarShadow(g2, this, row, column, bar, barBase, true); } getBarPainter().paintBar(g2, this, row, column, bar, barBase); if (completeBar != null) { g2.setPaint(getCompletePaint()); g2.fill(completeBar); } if (incompleteBar != null) { g2.setPaint(getIncompletePaint()); g2.fill(incompleteBar); } // draw the outline... if (isDrawBarOutline() && state.getBarWidth() > BAR_OUTLINE_WIDTH_THRESHOLD) { Stroke stroke = getItemOutlineStroke(row, column); Paint paint = getItemOutlinePaint(row, column); if (stroke != null && paint != null) { g2.setStroke(stroke); g2.setPaint(paint); g2.draw(bar); } } CategoryItemLabelGenerator generator = getItemLabelGenerator(row, column); if (generator != null && isItemLabelVisible(row, column)) { drawItemLabel(g2, dataset, row, column, plot, generator, bar, false); } // submit the current data point as a crosshair candidate int datasetIndex = plot.indexOf(dataset); Comparable columnKey = dataset.getColumnKey(column); Comparable rowKey = dataset.getRowKey(row); double xx = domainAxis.getCategorySeriesMiddle(columnKey, rowKey, dataset, getItemMargin(), dataArea, plot.getDomainAxisEdge()); updateCrosshairValues(state.getCrosshairState(), dataset.getRowKey(row), dataset.getColumnKey(column), value1.doubleValue(), datasetIndex, xx, java2dValue1, orientation); // collect entity and tool tip information... EntityCollection entities = state.getEntityCollection(); if (entities != null) { addItemEntity(entities, dataset, row, column, bar); } } /** * Returns the Java2D coordinate for the middle of the specified data item. * * @param rowKey the row key. * @param columnKey the column key. * @param dataset the dataset. * @param axis the axis. * @param area the drawing area. * @param edge the edge along which the axis lies. * * @return The Java2D coordinate. * * @since 1.0.11 */ @Override public double getItemMiddle(Comparable rowKey, Comparable columnKey, CategoryDataset dataset, CategoryAxis axis, Rectangle2D area, RectangleEdge edge) { return axis.getCategorySeriesMiddle(columnKey, rowKey, dataset, getItemMargin(), area, edge); } /** * Tests this renderer for equality with an arbitrary object. * * @param obj the object (<code>null</code> permitted). * * @return A boolean. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof GanttRenderer)) { return false; } GanttRenderer that = (GanttRenderer) obj; if (!PaintUtilities.equal(this.completePaint, that.completePaint)) { return false; } if (!PaintUtilities.equal(this.incompletePaint, that.incompletePaint)) { return false; } if (this.startPercent != that.startPercent) { return false; } if (this.endPercent != that.endPercent) { return false; } return super.equals(obj); } /** * Provides serialization support. * * @param stream the output stream. * * @throws IOException if there is an I/O error. */ private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); SerialUtilities.writePaint(this.completePaint, stream); SerialUtilities.writePaint(this.incompletePaint, stream); } /** * Provides serialization support. * * @param stream the input stream. * * @throws IOException if there is an I/O error. * @throws ClassNotFoundException if there is a classpath problem. */ private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); this.completePaint = SerialUtilities.readPaint(stream); this.incompletePaint = SerialUtilities.readPaint(stream); } }
23,666
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
AbstractCategoryItemRenderer.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/renderer/category/AbstractCategoryItemRenderer.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2014, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * --------------------------------- * AbstractCategoryItemRenderer.java * --------------------------------- * (C) Copyright 2002-2014, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): Richard Atkinson; * Peter Kolb (patch 2497611); * * Changes: * -------- * 29-May-2002 : Version 1 (DG); * 06-Jun-2002 : Added accessor methods for the tool tip generator (DG); * 11-Jun-2002 : Made constructors protected (DG); * 26-Jun-2002 : Added axis to initialise method (DG); * 05-Aug-2002 : Added urlGenerator member variable plus accessors (RA); * 22-Aug-2002 : Added categoriesPaint attribute, based on code submitted by * Janet Banks. This can be used when there is only one series, * and you want each category item to have a different color (DG); * 01-Oct-2002 : Fixed errors reported by Checkstyle (DG); * 29-Oct-2002 : Fixed bug where background image for plot was not being * drawn (DG); * 05-Nov-2002 : Replaced references to CategoryDataset with TableDataset (DG); * 26-Nov 2002 : Replaced the isStacked() method with getRangeType() (DG); * 09-Jan-2003 : Renamed grid-line methods (DG); * 17-Jan-2003 : Moved plot classes into separate package (DG); * 25-Mar-2003 : Implemented Serializable (DG); * 12-May-2003 : Modified to take into account the plot orientation (DG); * 12-Aug-2003 : Very minor javadoc corrections (DB) * 13-Aug-2003 : Implemented Cloneable (DG); * 16-Sep-2003 : Changed ChartRenderingInfo --> PlotRenderingInfo (DG); * 05-Nov-2003 : Fixed marker rendering bug (833623) (DG); * 21-Jan-2004 : Update for renamed method in ValueAxis (DG); * 11-Feb-2004 : Modified labelling for markers (DG); * 12-Feb-2004 : Updated clone() method (DG); * 15-Apr-2004 : Created a new CategoryToolTipGenerator interface (DG); * 05-May-2004 : Fixed bug (948310) where interval markers extend outside axis * range (DG); * 14-Jun-2004 : Fixed bug in drawRangeMarker() method - now uses 'paint' and * 'stroke' rather than 'outlinePaint' and 'outlineStroke' (DG); * 15-Jun-2004 : Interval markers can now use GradientPaint (DG); * 30-Sep-2004 : Moved drawRotatedString() from RefineryUtilities * --> TextUtilities (DG); * 01-Oct-2004 : Fixed bug 1029697, problem with label alignment in * drawRangeMarker() method (DG); * 07-Jan-2005 : Renamed getRangeExtent() --> findRangeBounds() (DG); * 21-Jan-2005 : Modified return type of calculateRangeMarkerTextAnchorPoint() * method (DG); * 08-Mar-2005 : Fixed positioning of marker labels (DG); * 20-Apr-2005 : Added legend label, tooltip and URL generators (DG); * 01-Jun-2005 : Handle one dimension of the marker label adjustment * automatically (DG); * 09-Jun-2005 : Added utility method for adding an item entity (DG); * ------------- JFREECHART 1.0.x --------------------------------------------- * 01-Mar-2006 : Updated getLegendItems() to check seriesVisibleInLegend * flags (DG); * 20-Jul-2006 : Set dataset and series indices in LegendItem (DG); * 23-Oct-2006 : Draw outlines for interval markers (DG); * 24-Oct-2006 : Respect alpha setting in markers, as suggested by Sergei * Ivanov in patch 1567843 (DG); * 30-Nov-2006 : Added a check for series visibility in the getLegendItem() * method (DG); * 07-Dec-2006 : Fix for equals() method (DG); * 22-Feb-2007 : Added createState() method (DG); * 01-Mar-2007 : Fixed interval marker drawing (patch 1670686 thanks to * Sergei Ivanov) (DG); * 20-Apr-2007 : Updated getLegendItem() for renderer change, and deprecated * itemLabelGenerator, toolTipGenerator and itemURLGenerator * override fields (DG); * 18-May-2007 : Set dataset and seriesKey for LegendItem (DG); * 17-Jun-2008 : Apply legend shape, font and paint attributes (DG); * 26-Jun-2008 : Added crosshair support (DG); * 25-Nov-2008 : Fixed bug in findRangeBounds() method (DG); * 14-Jan-2009 : Update initialise() to store visible series indices (PK); * 21-Jan-2009 : Added drawRangeLine() method (DG); * 27-Mar-2009 : Added new findRangeBounds() method to account for hidden * series (DG); * 01-Apr-2009 : Added new addEntity() method (DG); * 09-Feb-2010 : Fixed bug 2947660 (DG); * 15-Jun-2012 : Removed JCommon dependencies (DG); * 10-Mar-2014 : Removed LegendItemCollection (DG); * */ package org.jfree.chart.renderer.category; import java.awt.AlphaComposite; import java.awt.Composite; import java.awt.Font; import java.awt.GradientPaint; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.Shape; import java.awt.Stroke; import java.awt.geom.Ellipse2D; import java.awt.geom.Line2D; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import org.jfree.chart.LegendItem; import org.jfree.chart.axis.CategoryAxis; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.ui.GradientPaintTransformer; import org.jfree.chart.ui.LengthAdjustmentType; import org.jfree.chart.ui.RectangleAnchor; import org.jfree.chart.ui.RectangleEdge; import org.jfree.chart.ui.RectangleInsets; import org.jfree.chart.util.ObjectList; import org.jfree.chart.util.ObjectUtilities; import org.jfree.chart.util.PublicCloneable; import org.jfree.chart.util.SortOrder; import org.jfree.chart.entity.CategoryItemEntity; import org.jfree.chart.entity.EntityCollection; import org.jfree.chart.event.RendererChangeEvent; import org.jfree.chart.labels.CategoryItemLabelGenerator; import org.jfree.chart.labels.CategorySeriesLabelGenerator; import org.jfree.chart.labels.CategoryToolTipGenerator; import org.jfree.chart.labels.ItemLabelPosition; import org.jfree.chart.labels.StandardCategorySeriesLabelGenerator; import org.jfree.chart.plot.CategoryCrosshairState; import org.jfree.chart.plot.CategoryMarker; import org.jfree.chart.plot.CategoryPlot; import org.jfree.chart.plot.DrawingSupplier; import org.jfree.chart.plot.IntervalMarker; import org.jfree.chart.plot.Marker; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.PlotRenderingInfo; import org.jfree.chart.plot.ValueMarker; import org.jfree.chart.renderer.AbstractRenderer; import org.jfree.chart.text.TextUtilities; import org.jfree.chart.urls.CategoryURLGenerator; import org.jfree.chart.util.ParamChecks; import org.jfree.data.Range; import org.jfree.data.category.CategoryDataset; import org.jfree.data.general.DatasetUtilities; /** * An abstract base class that you can use to implement a new * {@link CategoryItemRenderer}. When you create a new * {@link CategoryItemRenderer} you are not required to extend this class, * but it makes the job easier. */ public abstract class AbstractCategoryItemRenderer extends AbstractRenderer implements CategoryItemRenderer, Cloneable, PublicCloneable, Serializable { /** For serialization. */ private static final long serialVersionUID = 1247553218442497391L; /** The plot that the renderer is assigned to. */ private CategoryPlot plot; /** A list of item label generators (one per series). */ private ObjectList<CategoryItemLabelGenerator> itemLabelGeneratorList; /** The default item label generator. */ private CategoryItemLabelGenerator defaultItemLabelGenerator; /** A list of tool tip generators (one per series). */ private ObjectList<CategoryToolTipGenerator> toolTipGeneratorList; /** The default tool tip generator. */ private CategoryToolTipGenerator defaultToolTipGenerator; /** A list of item label generators (one per series). */ private ObjectList<CategoryURLGenerator> itemURLGeneratorList; /** The default item label generator. */ private CategoryURLGenerator defaultItemURLGenerator; /** The legend item label generator. */ private CategorySeriesLabelGenerator legendItemLabelGenerator; /** The legend item tool tip generator. */ private CategorySeriesLabelGenerator legendItemToolTipGenerator; /** The legend item URL generator. */ private CategorySeriesLabelGenerator legendItemURLGenerator; /** The number of rows in the dataset (temporary record). */ private transient int rowCount; /** The number of columns in the dataset (temporary record). */ private transient int columnCount; /** * Creates a new renderer with no tool tip generator and no URL generator. * The defaults (no tool tip or URL generators) have been chosen to * minimise the processing required to generate a default chart. If you * require tool tips or URLs, then you can easily add the required * generators. */ protected AbstractCategoryItemRenderer() { this.itemLabelGeneratorList = new ObjectList<CategoryItemLabelGenerator>(); this.toolTipGeneratorList = new ObjectList<CategoryToolTipGenerator>(); this.itemURLGeneratorList = new ObjectList<CategoryURLGenerator>(); this.legendItemLabelGenerator = new StandardCategorySeriesLabelGenerator(); } /** * Returns the number of passes through the dataset required by the * renderer. This method returns <code>1</code>, subclasses should * override if they need more passes. * * @return The pass count. */ @Override public int getPassCount() { return 1; } /** * Returns the plot that the renderer has been assigned to (where * <code>null</code> indicates that the renderer is not currently assigned * to a plot). * * @return The plot (possibly <code>null</code>). * * @see #setPlot(CategoryPlot) */ @Override public CategoryPlot getPlot() { return this.plot; } /** * Sets the plot that the renderer has been assigned to. This method is * usually called by the {@link CategoryPlot}, in normal usage you * shouldn't need to call this method directly. * * @param plot the plot (<code>null</code> not permitted). * * @see #getPlot() */ @Override public void setPlot(CategoryPlot plot) { ParamChecks.nullNotPermitted(plot, "plot"); this.plot = plot; } // ITEM LABEL GENERATOR /** * Returns the item label generator for a data item. This implementation * simply passes control to the {@link #getSeriesItemLabelGenerator(int)} * method. If, for some reason, you want a different generator for * individual items, you can override this method. * * @param row the row index (zero based). * @param column the column index (zero based). * * @return The generator (possibly <code>null</code>). */ @Override public CategoryItemLabelGenerator getItemLabelGenerator(int row, int column) { return getSeriesItemLabelGenerator(row); } /** * Returns the item label generator for a series. * * @param series the series index (zero based). * * @return The generator (possibly <code>null</code>). * * @see #setSeriesItemLabelGenerator(int, CategoryItemLabelGenerator) */ @Override public CategoryItemLabelGenerator getSeriesItemLabelGenerator(int series) { CategoryItemLabelGenerator generator = this.itemLabelGeneratorList.get(series); if (generator == null) { generator = this.defaultItemLabelGenerator; } return generator; } /** * Sets the item label generator for a series and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param series the series index (zero based). * @param generator the generator (<code>null</code> permitted). * * @see #getSeriesItemLabelGenerator(int) */ @Override public void setSeriesItemLabelGenerator(int series, CategoryItemLabelGenerator generator) { setSeriesItemLabelGenerator(series, generator, true); } /** * Sets the item label generator for a series and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param series the series index (zero based). * @param generator the generator (<code>null</code> permitted). * @param notify notify listeners? * * @see #getSeriesItemLabelGenerator(int) */ @Override public void setSeriesItemLabelGenerator(int series, CategoryItemLabelGenerator generator, boolean notify) { this.itemLabelGeneratorList.set(series, generator); if (notify) { fireChangeEvent(); } } /** * Returns the default item label generator. * * @return The generator (possibly <code>null</code>). * * @see #setDefaultItemLabelGenerator(CategoryItemLabelGenerator) */ @Override public CategoryItemLabelGenerator getDefaultItemLabelGenerator() { return this.defaultItemLabelGenerator; } /** * Sets the default item label generator and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param generator the generator (<code>null</code> permitted). * * @see #getDefaultItemLabelGenerator() */ @Override public void setDefaultItemLabelGenerator( CategoryItemLabelGenerator generator) { setDefaultItemLabelGenerator(generator, true); } /** * Sets the default item label generator and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param generator the generator (<code>null</code> permitted). * @param notify notify listeners? * * @see #getDefaultItemLabelGenerator() */ @Override public void setDefaultItemLabelGenerator( CategoryItemLabelGenerator generator, boolean notify) { this.defaultItemLabelGenerator = generator; if (notify) { fireChangeEvent(); } } // TOOL TIP GENERATOR /** * Returns the tool tip generator that should be used for the specified * item. This method looks up the generator using the "three-layer" * approach outlined in the general description of this interface. You * can override this method if you want to return a different generator per * item. * * @param row the row index (zero-based). * @param column the column index (zero-based). * * @return The generator (possibly <code>null</code>). */ @Override public CategoryToolTipGenerator getToolTipGenerator(int row, int column) { CategoryToolTipGenerator result = getSeriesToolTipGenerator(row); if (result == null) { result = this.defaultToolTipGenerator; } return result; } /** * Returns the tool tip generator for the specified series (a "layer 1" * generator). * * @param series the series index (zero-based). * * @return The tool tip generator (possibly <code>null</code>). * * @see #setSeriesToolTipGenerator(int, CategoryToolTipGenerator) */ @Override public CategoryToolTipGenerator getSeriesToolTipGenerator(int series) { return this.toolTipGeneratorList.get(series); } /** * Sets the tool tip generator for a series and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param series the series index (zero-based). * @param generator the generator (<code>null</code> permitted). * * @see #getSeriesToolTipGenerator(int) */ @Override public void setSeriesToolTipGenerator(int series, CategoryToolTipGenerator generator) { setSeriesToolTipGenerator(series, generator, true); } /** * Sets the tool tip generator for a series and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param series the series index (zero-based). * @param generator the generator (<code>null</code> permitted). * @param notify notify listeners? * * @see #getSeriesToolTipGenerator(int) */ @Override public void setSeriesToolTipGenerator(int series, CategoryToolTipGenerator generator, boolean notify) { this.toolTipGeneratorList.set(series, generator); if (notify) { fireChangeEvent(); } } /** * Returns the default tool tip generator. * * @return The tool tip generator (possibly <code>null</code>). * * @see #setBaseToolTipGenerator(CategoryToolTipGenerator) */ @Override public CategoryToolTipGenerator getDefaultToolTipGenerator() { return this.defaultToolTipGenerator; } /** * Sets the default tool tip generator and sends a {@link RendererChangeEvent} * to all registered listeners. * * @param generator the generator (<code>null</code> permitted). * * @see #getDefaultToolTipGenerator() */ @Override public void setDefaultToolTipGenerator(CategoryToolTipGenerator generator) { setDefaultToolTipGenerator(generator, true); } /** * Sets the default tool tip generator and sends a change event to all * registered listeners. * * @param generator the generator (<code>null</code> permitted). * @param notify notify listeners? * * @see #getDefaultToolTipGenerator() */ @Override public void setDefaultToolTipGenerator(CategoryToolTipGenerator generator, boolean notify) { this.defaultToolTipGenerator = generator; if (notify) { fireChangeEvent(); } } // URL GENERATOR /** * Returns the URL generator for a data item. This method just calls the * getSeriesItemURLGenerator method, but you can override this behaviour if * you want to. * * @param row the row index (zero based). * @param column the column index (zero based). * * @return The URL generator. */ @Override public CategoryURLGenerator getItemURLGenerator(int row, int column) { return getSeriesItemURLGenerator(row); } /** * Returns the URL generator for a series. * * @param series the series index (zero based). * * @return The URL generator for the series. * * @see #setSeriesItemURLGenerator(int, CategoryURLGenerator) */ @Override public CategoryURLGenerator getSeriesItemURLGenerator(int series) { CategoryURLGenerator generator = this.itemURLGeneratorList.get(series); if (generator == null) { generator = this.defaultItemURLGenerator; } return generator; } /** * Sets the URL generator for a series and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param series the series index (zero based). * @param generator the generator. * * @see #getSeriesItemURLGenerator(int) */ @Override public void setSeriesItemURLGenerator(int series, CategoryURLGenerator generator) { setSeriesItemURLGenerator(series, generator, true); } /** * Sets the URL generator for a series and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param series the series index (zero based). * @param generator the generator. * @param notify notify listeners? * * @see #getSeriesItemURLGenerator(int) */ @Override public void setSeriesItemURLGenerator(int series, CategoryURLGenerator generator, boolean notify) { this.itemURLGeneratorList.set(series, generator); if (notify) { fireChangeEvent(); } } /** * Returns the default item URL generator. * * @return The item URL generator. * * @see #setDefaultItemURLGenerator(CategoryURLGenerator) */ @Override public CategoryURLGenerator getDefaultItemURLGenerator() { return this.defaultItemURLGenerator; } /** * Sets the default item URL generator and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param generator the item URL generator (<code>null</code> permitted). * * @see #getDefaultItemURLGenerator() */ @Override public void setDefaultItemURLGenerator(CategoryURLGenerator generator) { setDefaultItemURLGenerator(generator, true); } /** * Sets the default item URL generator and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param generator the item URL generator (<code>null</code> permitted). * @param notify notify listeners? * * @see #getDefaultItemURLGenerator() */ @Override public void setDefaultItemURLGenerator(CategoryURLGenerator generator, boolean notify) { this.defaultItemURLGenerator = generator; if (notify) { fireChangeEvent(); } } /** * Returns the number of rows in the dataset. This value is updated in the * {@link AbstractCategoryItemRenderer#initialise} method. * * @return The row count. */ public int getRowCount() { return this.rowCount; } /** * Returns the number of columns in the dataset. This value is updated in * the {@link AbstractCategoryItemRenderer#initialise} method. * * @return The column count. */ public int getColumnCount() { return this.columnCount; } /** * Creates a new state instance---this method is called from the * {@link #initialise(Graphics2D, Rectangle2D, CategoryPlot, int, * PlotRenderingInfo)} method. Subclasses can override this method if * they need to use a subclass of {@link CategoryItemRendererState}. * * @param info collects plot rendering info (<code>null</code> permitted). * * @return The new state instance (never <code>null</code>). * * @since 1.0.5 */ protected CategoryItemRendererState createState(PlotRenderingInfo info) { return new CategoryItemRendererState(info); } /** * Initialises the renderer and returns a state object that will be used * for the remainder of the drawing process for a single chart. The state * object allows for the fact that the renderer may be used simultaneously * by multiple threads (each thread will work with a separate state object). * * @param g2 the graphics device. * @param dataArea the data area. * @param plot the plot. * @param rendererIndex the renderer index. * @param info an object for returning information about the structure of * the plot (<code>null</code> permitted). * * @return The renderer state. */ @Override public CategoryItemRendererState initialise(Graphics2D g2, Rectangle2D dataArea, CategoryPlot plot, int rendererIndex, PlotRenderingInfo info) { setPlot(plot); CategoryDataset data = plot.getDataset(rendererIndex); if (data != null) { this.rowCount = data.getRowCount(); this.columnCount = data.getColumnCount(); } else { this.rowCount = 0; this.columnCount = 0; } CategoryItemRendererState state = createState(info); int[] visibleSeriesTemp = new int[this.rowCount]; int visibleSeriesCount = 0; for (int row = 0; row < this.rowCount; row++) { if (isSeriesVisible(row)) { visibleSeriesTemp[visibleSeriesCount] = row; visibleSeriesCount++; } } int[] visibleSeries = new int[visibleSeriesCount]; System.arraycopy(visibleSeriesTemp, 0, visibleSeries, 0, visibleSeriesCount); state.setVisibleSeriesArray(visibleSeries); return state; } /** * Returns the range of values the renderer requires to display all the * items from the specified dataset. * * @param dataset the dataset (<code>null</code> permitted). * * @return The range (or <code>null</code> if the dataset is * <code>null</code> or empty). */ @Override public Range findRangeBounds(CategoryDataset dataset) { return findRangeBounds(dataset, false); } /** * Returns the range of values the renderer requires to display all the * items from the specified dataset. * * @param dataset the dataset (<code>null</code> permitted). * @param includeInterval include the y-interval if the dataset has one. * * @return The range (<code>null</code> if the dataset is <code>null</code> * or empty). * * @since 1.0.13 */ protected Range findRangeBounds(CategoryDataset dataset, boolean includeInterval) { if (dataset == null) { return null; } if (getDataBoundsIncludesVisibleSeriesOnly()) { List<Comparable> visibleSeriesKeys = new ArrayList<Comparable>(); int seriesCount = dataset.getRowCount(); for (int s = 0; s < seriesCount; s++) { if (isSeriesVisible(s)) { visibleSeriesKeys.add(dataset.getRowKey(s)); } } return DatasetUtilities.findRangeBounds(dataset, visibleSeriesKeys, includeInterval); } else { return DatasetUtilities.findRangeBounds(dataset, includeInterval); } } /** * Returns the Java2D coordinate for the middle of the specified data item. * * @param rowKey the row key. * @param columnKey the column key. * @param dataset the dataset. * @param axis the axis. * @param area the data area. * @param edge the edge along which the axis lies. * * @return The Java2D coordinate for the middle of the item. * * @since 1.0.11 */ @Override public double getItemMiddle(Comparable rowKey, Comparable columnKey, CategoryDataset dataset, CategoryAxis axis, Rectangle2D area, RectangleEdge edge) { return axis.getCategoryMiddle(columnKey, dataset.getColumnKeys(), area, edge); } /** * Draws a background for the data area. The default implementation just * gets the plot to draw the background, but some renderers will override * this behaviour. * * @param g2 the graphics device. * @param plot the plot. * @param dataArea the data area. */ @Override public void drawBackground(Graphics2D g2, CategoryPlot plot, Rectangle2D dataArea) { plot.drawBackground(g2, dataArea); } /** * Draws an outline for the data area. The default implementation just * gets the plot to draw the outline, but some renderers will override this * behaviour. * * @param g2 the graphics device. * @param plot the plot. * @param dataArea the data area. */ @Override public void drawOutline(Graphics2D g2, CategoryPlot plot, Rectangle2D dataArea) { plot.drawOutline(g2, dataArea); } /** * Draws a grid line against the domain axis. * <P> * Note that this default implementation assumes that the horizontal axis * is the domain axis. If this is not the case, you will need to override * this method. * * @param g2 the graphics device. * @param plot the plot. * @param dataArea the area for plotting data (not yet adjusted for any * 3D effect). * @param value the Java2D value at which the grid line should be drawn. * * @see #drawRangeGridline(Graphics2D, CategoryPlot, ValueAxis, * Rectangle2D, double) */ @Override public void drawDomainGridline(Graphics2D g2, CategoryPlot plot, Rectangle2D dataArea, double value) { Line2D line = null; PlotOrientation orientation = plot.getOrientation(); if (orientation == PlotOrientation.HORIZONTAL) { line = new Line2D.Double(dataArea.getMinX(), value, dataArea.getMaxX(), value); } else if (orientation == PlotOrientation.VERTICAL) { line = new Line2D.Double(value, dataArea.getMinY(), value, dataArea.getMaxY()); } Paint paint = plot.getDomainGridlinePaint(); if (paint == null) { paint = CategoryPlot.DEFAULT_GRIDLINE_PAINT; } g2.setPaint(paint); Stroke stroke = plot.getDomainGridlineStroke(); if (stroke == null) { stroke = CategoryPlot.DEFAULT_GRIDLINE_STROKE; } g2.setStroke(stroke); g2.draw(line); } /** * Draws a grid line against the range axis. * * @param g2 the graphics device. * @param plot the plot. * @param axis the value axis. * @param dataArea the area for plotting data (not yet adjusted for any * 3D effect). * @param value the value at which the grid line should be drawn. * * @see #drawDomainGridline(Graphics2D, CategoryPlot, Rectangle2D, double) */ @Override public void drawRangeGridline(Graphics2D g2, CategoryPlot plot, ValueAxis axis, Rectangle2D dataArea, double value) { Range range = axis.getRange(); if (!range.contains(value)) { return; } PlotOrientation orientation = plot.getOrientation(); double v = axis.valueToJava2D(value, dataArea, plot.getRangeAxisEdge()); Line2D line = null; if (orientation == PlotOrientation.HORIZONTAL) { line = new Line2D.Double(v, dataArea.getMinY(), v, dataArea.getMaxY()); } else if (orientation == PlotOrientation.VERTICAL) { line = new Line2D.Double(dataArea.getMinX(), v, dataArea.getMaxX(), v); } Paint paint = plot.getRangeGridlinePaint(); if (paint == null) { paint = CategoryPlot.DEFAULT_GRIDLINE_PAINT; } g2.setPaint(paint); Stroke stroke = plot.getRangeGridlineStroke(); if (stroke == null) { stroke = CategoryPlot.DEFAULT_GRIDLINE_STROKE; } g2.setStroke(stroke); g2.draw(line); } /** * Draws a line perpendicular to the range axis. * * @param g2 the graphics device. * @param plot the plot. * @param axis the value axis. * @param dataArea the area for plotting data (not yet adjusted for any 3D * effect). * @param value the value at which the grid line should be drawn. * @param paint the paint (<code>null</code> not permitted). * @param stroke the stroke (<code>null</code> not permitted). * * @see #drawRangeGridline * * @since 1.0.13 */ public void drawRangeGridline(Graphics2D g2, CategoryPlot plot, ValueAxis axis, Rectangle2D dataArea, double value, Paint paint, Stroke stroke) { // TODO: In JFreeChart 1.2.0, put this method in the // CategoryItemRenderer interface Range range = axis.getRange(); if (!range.contains(value)) { return; } PlotOrientation orientation = plot.getOrientation(); Line2D line = null; double v = axis.valueToJava2D(value, dataArea, plot.getRangeAxisEdge()); if (orientation == PlotOrientation.HORIZONTAL) { line = new Line2D.Double(v, dataArea.getMinY(), v, dataArea.getMaxY()); } else if (orientation == PlotOrientation.VERTICAL) { line = new Line2D.Double(dataArea.getMinX(), v, dataArea.getMaxX(), v); } g2.setPaint(paint); g2.setStroke(stroke); g2.draw(line); } /** * Draws a marker for the domain axis. * * @param g2 the graphics device (not <code>null</code>). * @param plot the plot (not <code>null</code>). * @param axis the range axis (not <code>null</code>). * @param marker the marker to be drawn (not <code>null</code>). * @param dataArea the area inside the axes (not <code>null</code>). * * @see #drawRangeMarker(Graphics2D, CategoryPlot, ValueAxis, Marker, * Rectangle2D) */ @Override public void drawDomainMarker(Graphics2D g2, CategoryPlot plot, CategoryAxis axis, CategoryMarker marker, Rectangle2D dataArea) { Comparable category = marker.getKey(); CategoryDataset dataset = plot.getDataset(plot.getIndexOf(this)); int columnIndex = dataset.getColumnIndex(category); if (columnIndex < 0) { return; } final Composite savedComposite = g2.getComposite(); g2.setComposite(AlphaComposite.getInstance( AlphaComposite.SRC_OVER, marker.getAlpha())); PlotOrientation orientation = plot.getOrientation(); Rectangle2D bounds; if (marker.getDrawAsLine()) { double v = axis.getCategoryMiddle(columnIndex, dataset.getColumnCount(), dataArea, plot.getDomainAxisEdge()); Line2D line; if (orientation == PlotOrientation.HORIZONTAL) { line = new Line2D.Double(dataArea.getMinX(), v, dataArea.getMaxX(), v); } else if (orientation == PlotOrientation.VERTICAL) { line = new Line2D.Double(v, dataArea.getMinY(), v, dataArea.getMaxY()); } else { throw new IllegalStateException("Unrecognised orientation: " + orientation); } g2.setPaint(marker.getPaint()); g2.setStroke(marker.getStroke()); g2.draw(line); bounds = line.getBounds2D(); } else { double v0 = axis.getCategoryStart(columnIndex, dataset.getColumnCount(), dataArea, plot.getDomainAxisEdge()); double v1 = axis.getCategoryEnd(columnIndex, dataset.getColumnCount(), dataArea, plot.getDomainAxisEdge()); Rectangle2D area = null; if (orientation == PlotOrientation.HORIZONTAL) { area = new Rectangle2D.Double(dataArea.getMinX(), v0, dataArea.getWidth(), (v1 - v0)); } else if (orientation == PlotOrientation.VERTICAL) { area = new Rectangle2D.Double(v0, dataArea.getMinY(), (v1 - v0), dataArea.getHeight()); } g2.setPaint(marker.getPaint()); g2.fill(area); bounds = area; } String label = marker.getLabel(); RectangleAnchor anchor = marker.getLabelAnchor(); if (label != null) { Font labelFont = marker.getLabelFont(); g2.setFont(labelFont); g2.setPaint(marker.getLabelPaint()); Point2D coordinates = calculateDomainMarkerTextAnchorPoint( g2, orientation, dataArea, bounds, marker.getLabelOffset(), marker.getLabelOffsetType(), anchor); TextUtilities.drawAlignedString(label, g2, (float) coordinates.getX(), (float) coordinates.getY(), marker.getLabelTextAnchor()); } g2.setComposite(savedComposite); } /** * Draws a marker for the range axis. * * @param g2 the graphics device (not <code>null</code>). * @param plot the plot (not <code>null</code>). * @param axis the range axis (not <code>null</code>). * @param marker the marker to be drawn (not <code>null</code>). * @param dataArea the area inside the axes (not <code>null</code>). * * @see #drawDomainMarker(Graphics2D, CategoryPlot, CategoryAxis, * CategoryMarker, Rectangle2D) */ @Override public void drawRangeMarker(Graphics2D g2, CategoryPlot plot, ValueAxis axis, Marker marker, Rectangle2D dataArea) { if (marker instanceof ValueMarker) { ValueMarker vm = (ValueMarker) marker; double value = vm.getValue(); Range range = axis.getRange(); if (!range.contains(value)) { return; } final Composite savedComposite = g2.getComposite(); g2.setComposite(AlphaComposite.getInstance( AlphaComposite.SRC_OVER, marker.getAlpha())); PlotOrientation orientation = plot.getOrientation(); double v = axis.valueToJava2D(value, dataArea, plot.getRangeAxisEdge()); Line2D line = null; if (orientation == PlotOrientation.HORIZONTAL) { line = new Line2D.Double(v, dataArea.getMinY(), v, dataArea.getMaxY()); } else if (orientation == PlotOrientation.VERTICAL) { line = new Line2D.Double(dataArea.getMinX(), v, dataArea.getMaxX(), v); } else { throw new IllegalStateException("Unrecognised orientation: " + orientation); } g2.setPaint(marker.getPaint()); g2.setStroke(marker.getStroke()); g2.draw(line); String label = marker.getLabel(); RectangleAnchor anchor = marker.getLabelAnchor(); if (label != null) { Font labelFont = marker.getLabelFont(); g2.setFont(labelFont); g2.setPaint(marker.getLabelPaint()); Point2D coordinates = calculateRangeMarkerTextAnchorPoint( g2, orientation, dataArea, line.getBounds2D(), marker.getLabelOffset(), LengthAdjustmentType.EXPAND, anchor); TextUtilities.drawAlignedString(label, g2, (float) coordinates.getX(), (float) coordinates.getY(), marker.getLabelTextAnchor()); } g2.setComposite(savedComposite); } else if (marker instanceof IntervalMarker) { IntervalMarker im = (IntervalMarker) marker; double start = im.getStartValue(); double end = im.getEndValue(); Range range = axis.getRange(); if (!(range.intersects(start, end))) { return; } final Composite savedComposite = g2.getComposite(); g2.setComposite(AlphaComposite.getInstance( AlphaComposite.SRC_OVER, marker.getAlpha())); double start2d = axis.valueToJava2D(start, dataArea, plot.getRangeAxisEdge()); double end2d = axis.valueToJava2D(end, dataArea, plot.getRangeAxisEdge()); double low = Math.min(start2d, end2d); double high = Math.max(start2d, end2d); PlotOrientation orientation = plot.getOrientation(); Rectangle2D rect = null; if (orientation == PlotOrientation.HORIZONTAL) { // clip left and right bounds to data area low = Math.max(low, dataArea.getMinX()); high = Math.min(high, dataArea.getMaxX()); rect = new Rectangle2D.Double(low, dataArea.getMinY(), high - low, dataArea.getHeight()); } else if (orientation == PlotOrientation.VERTICAL) { // clip top and bottom bounds to data area low = Math.max(low, dataArea.getMinY()); high = Math.min(high, dataArea.getMaxY()); rect = new Rectangle2D.Double(dataArea.getMinX(), low, dataArea.getWidth(), high - low); } Paint p = marker.getPaint(); if (p instanceof GradientPaint) { GradientPaint gp = (GradientPaint) p; GradientPaintTransformer t = im.getGradientPaintTransformer(); if (t != null) { gp = t.transform(gp, rect); } g2.setPaint(gp); } else { g2.setPaint(p); } g2.fill(rect); // now draw the outlines, if visible... if (im.getOutlinePaint() != null && im.getOutlineStroke() != null) { if (orientation == PlotOrientation.VERTICAL) { Line2D line = new Line2D.Double(); double x0 = dataArea.getMinX(); double x1 = dataArea.getMaxX(); g2.setPaint(im.getOutlinePaint()); g2.setStroke(im.getOutlineStroke()); if (range.contains(start)) { line.setLine(x0, start2d, x1, start2d); g2.draw(line); } if (range.contains(end)) { line.setLine(x0, end2d, x1, end2d); g2.draw(line); } } else { // PlotOrientation.HORIZONTAL Line2D line = new Line2D.Double(); double y0 = dataArea.getMinY(); double y1 = dataArea.getMaxY(); g2.setPaint(im.getOutlinePaint()); g2.setStroke(im.getOutlineStroke()); if (range.contains(start)) { line.setLine(start2d, y0, start2d, y1); g2.draw(line); } if (range.contains(end)) { line.setLine(end2d, y0, end2d, y1); g2.draw(line); } } } String label = marker.getLabel(); RectangleAnchor anchor = marker.getLabelAnchor(); if (label != null) { Font labelFont = marker.getLabelFont(); g2.setFont(labelFont); g2.setPaint(marker.getLabelPaint()); Point2D coordinates = calculateRangeMarkerTextAnchorPoint( g2, orientation, dataArea, rect, marker.getLabelOffset(), marker.getLabelOffsetType(), anchor); TextUtilities.drawAlignedString(label, g2, (float) coordinates.getX(), (float) coordinates.getY(), marker.getLabelTextAnchor()); } g2.setComposite(savedComposite); } } /** * Calculates the (x, y) coordinates for drawing the label for a marker on * the range axis. * * @param g2 the graphics device. * @param orientation the plot orientation. * @param dataArea the data area. * @param markerArea the rectangle surrounding the marker. * @param markerOffset the marker offset. * @param labelOffsetType the label offset type. * @param anchor the label anchor. * * @return The coordinates for drawing the marker label. */ protected Point2D calculateDomainMarkerTextAnchorPoint(Graphics2D g2, PlotOrientation orientation, Rectangle2D dataArea, Rectangle2D markerArea, RectangleInsets markerOffset, LengthAdjustmentType labelOffsetType, RectangleAnchor anchor) { Rectangle2D anchorRect = null; if (orientation == PlotOrientation.HORIZONTAL) { anchorRect = markerOffset.createAdjustedRectangle(markerArea, LengthAdjustmentType.CONTRACT, labelOffsetType); } else if (orientation == PlotOrientation.VERTICAL) { anchorRect = markerOffset.createAdjustedRectangle(markerArea, labelOffsetType, LengthAdjustmentType.CONTRACT); } return RectangleAnchor.coordinates(anchorRect, anchor); } /** * Calculates the (x, y) coordinates for drawing a marker label. * * @param g2 the graphics device. * @param orientation the plot orientation. * @param dataArea the data area. * @param markerArea the rectangle surrounding the marker. * @param markerOffset the marker offset. * @param labelOffsetType the label offset type. * @param anchor the label anchor. * * @return The coordinates for drawing the marker label. */ protected Point2D calculateRangeMarkerTextAnchorPoint(Graphics2D g2, PlotOrientation orientation, Rectangle2D dataArea, Rectangle2D markerArea, RectangleInsets markerOffset, LengthAdjustmentType labelOffsetType, RectangleAnchor anchor) { Rectangle2D anchorRect = null; if (orientation == PlotOrientation.HORIZONTAL) { anchorRect = markerOffset.createAdjustedRectangle(markerArea, labelOffsetType, LengthAdjustmentType.CONTRACT); } else if (orientation == PlotOrientation.VERTICAL) { anchorRect = markerOffset.createAdjustedRectangle(markerArea, LengthAdjustmentType.CONTRACT, labelOffsetType); } return RectangleAnchor.coordinates(anchorRect, anchor); } /** * Returns a legend item for a series. This default implementation will * return <code>null</code> if {@link #isSeriesVisible(int)} or * {@link #isSeriesVisibleInLegend(int)} returns <code>false</code>. * * @param datasetIndex the dataset index (zero-based). * @param series the series index (zero-based). * * @return The legend item (possibly <code>null</code>). * * @see #getLegendItems() */ @Override public LegendItem getLegendItem(int datasetIndex, int series) { CategoryPlot p = getPlot(); if (p == null) { return null; } // check that a legend item needs to be displayed... if (!isSeriesVisible(series) || !isSeriesVisibleInLegend(series)) { return null; } CategoryDataset dataset = p.getDataset(datasetIndex); String label = this.legendItemLabelGenerator.generateLabel(dataset, series); String description = label; String toolTipText = null; if (this.legendItemToolTipGenerator != null) { toolTipText = this.legendItemToolTipGenerator.generateLabel( dataset, series); } String urlText = null; if (this.legendItemURLGenerator != null) { urlText = this.legendItemURLGenerator.generateLabel(dataset, series); } Shape shape = lookupLegendShape(series); Paint paint = lookupSeriesPaint(series); Paint outlinePaint = lookupSeriesOutlinePaint(series); Stroke outlineStroke = lookupSeriesOutlineStroke(series); LegendItem item = new LegendItem(label, description, toolTipText, urlText, shape, paint, outlineStroke, outlinePaint); item.setLabelFont(lookupLegendTextFont(series)); Paint labelPaint = lookupLegendTextPaint(series); if (labelPaint != null) { item.setLabelPaint(labelPaint); } item.setSeriesKey(dataset.getRowKey(series)); item.setSeriesIndex(series); item.setDataset(dataset); item.setDatasetIndex(datasetIndex); return item; } /** * Tests this renderer for equality with another object. * * @param obj the object. * * @return <code>true</code> or <code>false</code>. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof AbstractCategoryItemRenderer)) { return false; } AbstractCategoryItemRenderer that = (AbstractCategoryItemRenderer) obj; if (!ObjectUtilities.equal(this.itemLabelGeneratorList, that.itemLabelGeneratorList)) { return false; } if (!ObjectUtilities.equal(this.defaultItemLabelGenerator, that.defaultItemLabelGenerator)) { return false; } if (!ObjectUtilities.equal(this.toolTipGeneratorList, that.toolTipGeneratorList)) { return false; } if (!ObjectUtilities.equal(this.defaultToolTipGenerator, that.defaultToolTipGenerator)) { return false; } if (!ObjectUtilities.equal(this.itemURLGeneratorList, that.itemURLGeneratorList)) { return false; } if (!ObjectUtilities.equal(this.defaultItemURLGenerator, that.defaultItemURLGenerator)) { return false; } if (!ObjectUtilities.equal(this.legendItemLabelGenerator, that.legendItemLabelGenerator)) { return false; } if (!ObjectUtilities.equal(this.legendItemToolTipGenerator, that.legendItemToolTipGenerator)) { return false; } if (!ObjectUtilities.equal(this.legendItemURLGenerator, that.legendItemURLGenerator)) { return false; } return super.equals(obj); } /** * Returns a hash code for the renderer. * * @return The hash code. */ @Override public int hashCode() { int result = super.hashCode(); return result; } /** * Returns the drawing supplier from the plot. * * @return The drawing supplier (possibly <code>null</code>). */ @Override public DrawingSupplier getDrawingSupplier() { DrawingSupplier result = null; CategoryPlot cp = getPlot(); if (cp != null) { result = cp.getDrawingSupplier(); } return result; } /** * Considers the current (x, y) coordinate and updates the crosshair point * if it meets the criteria (usually means the (x, y) coordinate is the * closest to the anchor point so far). * * @param crosshairState the crosshair state (<code>null</code> permitted, * but the method does nothing in that case). * @param rowKey the row key. * @param columnKey the column key. * @param value the data value. * @param datasetIndex the dataset index. * @param transX the x-value translated to Java2D space. * @param transY the y-value translated to Java2D space. * @param orientation the plot orientation (<code>null</code> not * permitted). * * @since 1.0.11 */ protected void updateCrosshairValues(CategoryCrosshairState crosshairState, Comparable rowKey, Comparable columnKey, double value, int datasetIndex, double transX, double transY, PlotOrientation orientation) { if (orientation == null) { throw new IllegalArgumentException("Null 'orientation' argument."); } if (crosshairState != null) { if (this.plot.isRangeCrosshairLockedOnData()) { // both axes crosshairState.updateCrosshairPoint(rowKey, columnKey, value, datasetIndex, transX, transY, orientation); } else { crosshairState.updateCrosshairX(rowKey, columnKey, datasetIndex, transX, orientation); } } } /** * Draws an item label. * * @param g2 the graphics device. * @param orientation the orientation. * @param dataset the dataset. * @param row the row. * @param column the column. * @param x the x coordinate (in Java2D space). * @param y the y coordinate (in Java2D space). * @param negative indicates a negative value (which affects the item * label position). */ protected void drawItemLabel(Graphics2D g2, PlotOrientation orientation, CategoryDataset dataset, int row, int column, double x, double y, boolean negative) { CategoryItemLabelGenerator generator = getItemLabelGenerator(row, column); if (generator != null) { Font labelFont = getItemLabelFont(row, column); Paint paint = getItemLabelPaint(row, column); g2.setFont(labelFont); g2.setPaint(paint); String label = generator.generateLabel(dataset, row, column); ItemLabelPosition position; if (!negative) { position = getPositiveItemLabelPosition(row, column); } else { position = getNegativeItemLabelPosition(row, column); } Point2D anchorPoint = calculateLabelAnchorPoint( position.getItemLabelAnchor(), x, y, orientation); TextUtilities.drawRotatedString(label, g2, (float) anchorPoint.getX(), (float) anchorPoint.getY(), position.getTextAnchor(), position.getAngle(), position.getRotationAnchor()); } } /** * Returns an independent copy of the renderer. The <code>plot</code> * reference is shallow copied. * * @return A clone. * * @throws CloneNotSupportedException can be thrown if one of the objects * belonging to the renderer does not support cloning (for example, * an item label generator). */ @Override public Object clone() throws CloneNotSupportedException { AbstractCategoryItemRenderer clone = (AbstractCategoryItemRenderer) super.clone(); if (this.itemLabelGeneratorList != null) { clone.itemLabelGeneratorList = (ObjectList<CategoryItemLabelGenerator>) this.itemLabelGeneratorList.clone(); } if (this.defaultItemLabelGenerator != null) { if (this.defaultItemLabelGenerator instanceof PublicCloneable) { PublicCloneable pc = (PublicCloneable) this.defaultItemLabelGenerator; clone.defaultItemLabelGenerator = (CategoryItemLabelGenerator) pc.clone(); } else { throw new CloneNotSupportedException( "ItemLabelGenerator not cloneable."); } } if (this.toolTipGeneratorList != null) { clone.toolTipGeneratorList = (ObjectList<CategoryToolTipGenerator>) this.toolTipGeneratorList.clone(); } if (this.defaultToolTipGenerator != null) { if (this.defaultToolTipGenerator instanceof PublicCloneable) { PublicCloneable pc = (PublicCloneable) this.defaultToolTipGenerator; clone.defaultToolTipGenerator = (CategoryToolTipGenerator) pc.clone(); } else { throw new CloneNotSupportedException( "Base tool tip generator not cloneable."); } } if (this.itemURLGeneratorList != null) { clone.itemURLGeneratorList = (ObjectList<CategoryURLGenerator>) this.itemURLGeneratorList.clone(); } if (this.defaultItemURLGenerator != null) { if (this.defaultItemURLGenerator instanceof PublicCloneable) { PublicCloneable pc = (PublicCloneable) this.defaultItemURLGenerator; clone.defaultItemURLGenerator = (CategoryURLGenerator) pc.clone(); } else { throw new CloneNotSupportedException( "Base item URL generator not cloneable."); } } if (this.legendItemLabelGenerator instanceof PublicCloneable) { clone.legendItemLabelGenerator = ObjectUtilities.clone(this.legendItemLabelGenerator); } if (this.legendItemToolTipGenerator instanceof PublicCloneable) { clone.legendItemToolTipGenerator = ObjectUtilities.clone(this.legendItemToolTipGenerator); } if (this.legendItemURLGenerator instanceof PublicCloneable) { clone.legendItemURLGenerator = ObjectUtilities.clone(this.legendItemURLGenerator); } return clone; } /** * Returns a domain axis for a plot. * * @param plot the plot. * @param index the axis index. * * @return A domain axis. */ protected CategoryAxis getDomainAxis(CategoryPlot plot, int index) { CategoryAxis result = plot.getDomainAxis(index); if (result == null) { result = plot.getDomainAxis(); } return result; } /** * Returns a range axis for a plot. * * @param plot the plot. * @param index the axis index. * * @return A range axis. */ protected ValueAxis getRangeAxis(CategoryPlot plot, int index) { ValueAxis result = plot.getRangeAxis(index); if (result == null) { result = plot.getRangeAxis(); } return result; } /** * Returns a (possibly empty) collection of legend items for the series * that this renderer is responsible for drawing. * * @return The legend item collection (never <code>null</code>). * * @see #getLegendItem(int, int) */ @Override public List<LegendItem> getLegendItems() { List<LegendItem> result = new ArrayList<LegendItem>(); if (this.plot == null) { return result; } int index = this.plot.getIndexOf(this); CategoryDataset dataset = this.plot.getDataset(index); if (dataset == null) { return result; } int seriesCount = dataset.getRowCount(); if (plot.getRowRenderingOrder().equals(SortOrder.ASCENDING)) { for (int i = 0; i < seriesCount; i++) { if (isSeriesVisibleInLegend(i)) { LegendItem item = getLegendItem(index, i); if (item != null) { result.add(item); } } } } else { for (int i = seriesCount - 1; i >= 0; i--) { if (isSeriesVisibleInLegend(i)) { LegendItem item = getLegendItem(index, i); if (item != null) { result.add(item); } } } } return result; } /** * Returns the legend item label generator. * * @return The label generator (never <code>null</code>). * * @see #setLegendItemLabelGenerator(CategorySeriesLabelGenerator) */ public CategorySeriesLabelGenerator getLegendItemLabelGenerator() { return this.legendItemLabelGenerator; } /** * Sets the legend item label generator and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param generator the generator (<code>null</code> not permitted). * * @see #getLegendItemLabelGenerator() */ public void setLegendItemLabelGenerator( CategorySeriesLabelGenerator generator) { ParamChecks.nullNotPermitted(generator, "generator"); this.legendItemLabelGenerator = generator; fireChangeEvent(); } /** * Returns the legend item tool tip generator. * * @return The tool tip generator (possibly <code>null</code>). * * @see #setLegendItemToolTipGenerator(CategorySeriesLabelGenerator) */ public CategorySeriesLabelGenerator getLegendItemToolTipGenerator() { return this.legendItemToolTipGenerator; } /** * Sets the legend item tool tip generator and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param generator the generator (<code>null</code> permitted). * * @see #setLegendItemToolTipGenerator(CategorySeriesLabelGenerator) */ public void setLegendItemToolTipGenerator( CategorySeriesLabelGenerator generator) { this.legendItemToolTipGenerator = generator; fireChangeEvent(); } /** * Returns the legend item URL generator. * * @return The URL generator (possibly <code>null</code>). * * @see #setLegendItemURLGenerator(CategorySeriesLabelGenerator) */ public CategorySeriesLabelGenerator getLegendItemURLGenerator() { return this.legendItemURLGenerator; } /** * Sets the legend item URL generator and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param generator the generator (<code>null</code> permitted). * * @see #getLegendItemURLGenerator() */ public void setLegendItemURLGenerator( CategorySeriesLabelGenerator generator) { this.legendItemURLGenerator = generator; fireChangeEvent(); } /** * Adds an entity with the specified hotspot. * * @param entities the entity collection. * @param dataset the dataset. * @param row the row index. * @param column the column index. * @param hotspot the hotspot (<code>null</code> not permitted). */ protected void addItemEntity(EntityCollection entities, CategoryDataset dataset, int row, int column, Shape hotspot) { ParamChecks.nullNotPermitted(hotspot, "hotspot"); if (!getItemCreateEntity(row, column)) { return; } String tip = null; CategoryToolTipGenerator tipster = getToolTipGenerator(row, column); if (tipster != null) { tip = tipster.generateToolTip(dataset, row, column); } String url = null; CategoryURLGenerator urlster = getItemURLGenerator(row, column); if (urlster != null) { url = urlster.generateURL(dataset, row, column); } CategoryItemEntity entity = new CategoryItemEntity(hotspot, tip, url, dataset, dataset.getRowKey(row), dataset.getColumnKey(column)); entities.add(entity); } /** * Adds an entity to the collection. * * @param entities the entity collection being populated. * @param hotspot the entity area (if <code>null</code> a default will be * used). * @param dataset the dataset. * @param row the series. * @param column the item. * @param entityX the entity's center x-coordinate in user space (only * used if <code>area</code> is <code>null</code>). * @param entityY the entity's center y-coordinate in user space (only * used if <code>area</code> is <code>null</code>). * * @since 1.0.13 */ protected void addEntity(EntityCollection entities, Shape hotspot, CategoryDataset dataset, int row, int column, double entityX, double entityY) { if (!getItemCreateEntity(row, column)) { return; } Shape s = hotspot; if (hotspot == null) { double r = getDefaultEntityRadius(); double w = r * 2; if (getPlot().getOrientation() == PlotOrientation.VERTICAL) { s = new Ellipse2D.Double(entityX - r, entityY - r, w, w); } else { s = new Ellipse2D.Double(entityY - r, entityX - r, w, w); } } String tip = null; CategoryToolTipGenerator generator = getToolTipGenerator(row, column); if (generator != null) { tip = generator.generateToolTip(dataset, row, column); } String url = null; CategoryURLGenerator urlster = getItemURLGenerator(row, column); if (urlster != null) { url = urlster.generateURL(dataset, row, column); } CategoryItemEntity entity = new CategoryItemEntity(s, tip, url, dataset, dataset.getRowKey(row), dataset.getColumnKey(column)); entities.add(entity); } }
66,756
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
IntervalBarRenderer.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/renderer/category/IntervalBarRenderer.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ------------------------ * IntervalBarRenderer.java * ------------------------ * (C) Copyright 2002-2012, by Jeremy Bowman. * * Original Author: Jeremy Bowman; * Contributor(s): David Gilbert (for Object Refinery Limited); * Christian W. Zuckschwerdt; * Peter Kolb (patch 2497611, 2791407); * * Changes * ------- * 29-Apr-2002 : Version 1, contributed by Jeremy Bowman (DG); * 11-May-2002 : Use CategoryPlot.getLabelsVisible() (JB); * 29-May-2002 : Added constructors (DG); * 26-Jun-2002 : Added axis to initialise method (DG); * 20-Sep-2002 : Added basic support for chart entities (DG); * 24-Oct-2002 : Amendments for changes in CategoryDataset interface and * CategoryToolTipGenerator interface (DG); * 05-Nov-2002 : Base dataset is now TableDataset not CategoryDataset (DG); * 25-Mar-2003 : Implemented Serializable (DG); * 30-Jul-2003 : Modified entity constructor (CZ); * 19-Aug-2003 : Implemented Cloneable and PublicCloneable (DG); * 08-Sep-2003 : Added checks for null values (DG); * 07-Oct-2003 : Added renderer state (DG); * 21-Oct-2003 : Bar width moved into renderer state (DG); * 23-Dec-2003 : Removed the deprecated MultiIntervalCategoryDataset * interface (DG); * 05-Nov-2004 : Modified drawItem() signature (DG); * 20-Apr-2005 : Renamed CategoryLabelGenerator * --> CategoryItemLabelGenerator (DG); * 02-Feb-2007 : Removed author tags all over JFreeChart sources (DG); * 24-Jun-2008 : Added new barPainter mechanism (DG); * 07-Oct-2008 : Override equals() method to fix minor bug (DG); * 14-Jan-2009 : Added support for seriesVisible flags (PK); * 16-May-2009 : The findRangeBounds() method needs to include the dataset * interval (DG); * 19-May-2009 : Fixed FindBugs warnings, patch by Michal Wozniak (DG); * 30-Oct-2011 : Fixed alignment when setMaximumBarWidth is applied (DG); * 17-Jun-2012 : Removed JCommon dependencies (DG); * */ package org.jfree.chart.renderer.category; import java.awt.Graphics2D; import java.awt.geom.Rectangle2D; import org.jfree.chart.axis.CategoryAxis; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.ui.RectangleEdge; import org.jfree.chart.entity.EntityCollection; import org.jfree.chart.labels.CategoryItemLabelGenerator; import org.jfree.chart.plot.CategoryPlot; import org.jfree.chart.plot.PlotOrientation; import org.jfree.data.Range; import org.jfree.data.category.CategoryDataset; import org.jfree.data.category.IntervalCategoryDataset; /** * A renderer that handles the drawing of bars for a bar plot where * each bar has a high and low value. This renderer is for use with the * {@link CategoryPlot} class. The example shown here is generated by the * <code>IntervalBarChartDemo1.java</code> program included in the JFreeChart * Demo Collection: * <br><br> * <img src="../../../../../images/IntervalBarRendererSample.png" * alt="IntervalBarRendererSample.png" /> */ public class IntervalBarRenderer extends BarRenderer { /** For serialization. */ private static final long serialVersionUID = -5068857361615528725L; /** * Constructs a new renderer. */ public IntervalBarRenderer() { super(); } /** * Returns the range of values from the specified dataset. For this * renderer, this is equivalent to calling * <code>findRangeBounds(dataset, true)</code>. * * @param dataset the dataset (<code>null</code> permitted). * * @return The range (or <code>null</code> if the dataset is * <code>null</code> or empty). */ @Override public Range findRangeBounds(CategoryDataset dataset) { return findRangeBounds(dataset, true); } /** * Draws the bar for a single (series, category) data item. * * @param g2 the graphics device. * @param state the renderer state. * @param dataArea the data area. * @param plot the plot. * @param domainAxis the domain axis. * @param rangeAxis the range axis. * @param dataset the dataset. * @param row the row index (zero-based). * @param column the column index (zero-based). * @param pass the pass index. */ @Override public void drawItem(Graphics2D g2, CategoryItemRendererState state, Rectangle2D dataArea, CategoryPlot plot, CategoryAxis domainAxis, ValueAxis rangeAxis, CategoryDataset dataset, int row, int column, int pass) { if (dataset instanceof IntervalCategoryDataset) { IntervalCategoryDataset d = (IntervalCategoryDataset) dataset; drawInterval(g2, state, dataArea, plot, domainAxis, rangeAxis, d, row, column); } else { super.drawItem(g2, state, dataArea, plot, domainAxis, rangeAxis, dataset, row, column, pass); } } /** * Draws a single interval. * * @param g2 the graphics device. * @param state the renderer state. * @param dataArea the data plot area. * @param plot the plot. * @param domainAxis the domain axis. * @param rangeAxis the range axis. * @param dataset the data. * @param row the row index (zero-based). * @param column the column index (zero-based). */ protected void drawInterval(Graphics2D g2, CategoryItemRendererState state, Rectangle2D dataArea, CategoryPlot plot, CategoryAxis domainAxis, ValueAxis rangeAxis, IntervalCategoryDataset dataset, int row, int column) { int visibleRow = state.getVisibleSeriesIndex(row); if (visibleRow < 0) { return; } PlotOrientation orientation = plot.getOrientation(); double rectX = 0.0; double rectY = 0.0; RectangleEdge rangeAxisLocation = plot.getRangeAxisEdge(); // Y0 Number value0 = dataset.getEndValue(row, column); if (value0 == null) { return; } double java2dValue0 = rangeAxis.valueToJava2D(value0.doubleValue(), dataArea, rangeAxisLocation); // Y1 Number value1 = dataset.getStartValue(row, column); if (value1 == null) { return; } double java2dValue1 = rangeAxis.valueToJava2D( value1.doubleValue(), dataArea, rangeAxisLocation); if (java2dValue1 < java2dValue0) { double temp = java2dValue1; java2dValue1 = java2dValue0; java2dValue0 = temp; } // BAR WIDTH double rectWidth = state.getBarWidth(); // BAR HEIGHT double rectHeight = Math.abs(java2dValue1 - java2dValue0); RectangleEdge barBase = RectangleEdge.LEFT; if (orientation == PlotOrientation.HORIZONTAL) { // BAR Y rectX = java2dValue0; rectY = calculateBarW0(getPlot(), orientation, dataArea, domainAxis, state, visibleRow, column); rectHeight = state.getBarWidth(); rectWidth = Math.abs(java2dValue1 - java2dValue0); barBase = RectangleEdge.LEFT; } else if (orientation == PlotOrientation.VERTICAL) { // BAR X rectX = calculateBarW0(getPlot(), orientation, dataArea, domainAxis, state, visibleRow, column); rectY = java2dValue0; barBase = RectangleEdge.BOTTOM; } Rectangle2D bar = new Rectangle2D.Double(rectX, rectY, rectWidth, rectHeight); BarPainter painter = getBarPainter(); if (getShadowsVisible()) { painter.paintBarShadow(g2, this, row, column, bar, barBase, false); } getBarPainter().paintBar(g2, this, row, column, bar, barBase); CategoryItemLabelGenerator generator = getItemLabelGenerator(row, column); if (generator != null && isItemLabelVisible(row, column)) { drawItemLabel(g2, dataset, row, column, plot, generator, bar, false); } // add an item entity, if this information is being collected EntityCollection entities = state.getEntityCollection(); if (entities != null) { addItemEntity(entities, dataset, row, column, bar); } } /** * Tests this renderer for equality with an arbitrary object. * * @param obj the object (<code>null</code> permitted). * * @return A boolean. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof IntervalBarRenderer)) { return false; } // there are no fields to check return super.equals(obj); } }
10,535
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
package-info.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/renderer/category/package-info.java
/** * Plug-in renderers for the {@link org.jfree.chart.plot.CategoryPlot} class. */ package org.jfree.chart.renderer.category;
129
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
StackedBarRenderer.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/renderer/category/StackedBarRenderer.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ----------------------- * StackedBarRenderer.java * ----------------------- * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): Richard Atkinson; * Thierry Saura; * Christian W. Zuckschwerdt; * Peter Kolb (patch 2511330); * * Changes * ------- * 19-Oct-2001 : Version 1 (DG); * 22-Oct-2001 : Renamed DataSource.java --> Dataset.java etc. (DG); * 23-Oct-2001 : Changed intro and trail gaps on bar plots to use percentage of * available space rather than a fixed number of units (DG); * 15-Nov-2001 : Modified to allow for null data values (DG); * 22-Nov-2001 : Modified to allow for negative data values (DG); * 13-Dec-2001 : Added tooltips (DG); * 16-Jan-2002 : Fixed bug for single category datasets (DG); * 15-Feb-2002 : Added isStacked() method (DG); * 14-Mar-2002 : Modified to implement the CategoryItemRenderer interface (DG); * 24-May-2002 : Incorporated tooltips into chart entities (DG); * 11-Jun-2002 : Added check for (permitted) null info object, bug and fix * reported by David Basten. Also updated Javadocs. (DG); * 25-Jun-2002 : Removed redundant import (DG); * 26-Jun-2002 : Small change to entity (DG); * 05-Aug-2002 : Small modification to drawCategoryItem method to support URLs * for HTML image maps (RA); * 08-Aug-2002 : Added optional linking lines, contributed by Thierry * Saura (DG); * 26-Sep-2002 : Fixed errors reported by Checkstyle (DG); * 24-Oct-2002 : Amendments for changes in CategoryDataset interface and * CategoryToolTipGenerator interface (DG); * 05-Nov-2002 : Replaced references to CategoryDataset with TableDataset (DG); * 26-Nov-2002 : Replaced isStacked() method with getRangeType() method (DG); * 17-Jan-2003 : Moved plot classes to a separate package (DG); * 25-Mar-2003 : Implemented Serializable (DG); * 12-May-2003 : Merged horizontal and vertical stacked bar renderers (DG); * 30-Jul-2003 : Modified entity constructor (CZ); * 08-Sep-2003 : Fixed bug 799668 (isBarOutlineDrawn() ignored) (DG); * 16-Sep-2003 : Changed ChartRenderingInfo --> PlotRenderingInfo (DG); * 21-Oct-2003 : Moved bar width into renderer state (DG); * 26-Nov-2003 : Added code to respect maxBarWidth attribute (DG); * 05-Nov-2004 : Changed to a two-pass renderer so that item labels are not * overwritten by other bars (DG); * 07-Jan-2005 : Renamed getRangeExtent() --> findRangeBounds() (DG); * 29-Mar-2005 : Modified drawItem() method so that a zero value is handled * within the code for positive rather than negative values (DG); * 20-Apr-2005 : Renamed CategoryLabelGenerator * --> CategoryItemLabelGenerator (DG); * 17-May-2005 : Added flag to allow rendering values as percentages - inspired * by patch 1200886 submitted by John Xiao (DG); * 09-Jun-2005 : Added accessor methods for the renderAsPercentages flag, * provided equals() method, and use addItemEntity from * superclass (DG); * 09-Jun-2005 : Added support for GradientPaint - see bug report 1215670 (DG); * 22-Sep-2005 : Renamed getMaxBarWidth() --> getMaximumBarWidth() (DG); * 29-Sep-2005 : Use outline stroke in drawItem method - see bug report * 1304139 (DG); * ------------- JFREECHART 1.0.x --------------------------------------------- * 11-Oct-2006 : Source reformatting (DG); * 24-Jun-2008 : Added new barPainter mechanism (DG); * 04-Feb-2009 : Added support for hidden series (PK); * 17-Jun-2012 : Removed JCommon dependencies (DG); * */ package org.jfree.chart.renderer.category; import java.awt.Graphics2D; import java.awt.geom.Rectangle2D; import java.io.Serializable; import org.jfree.chart.axis.CategoryAxis; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.ui.RectangleEdge; import org.jfree.chart.ui.TextAnchor; import org.jfree.chart.util.PublicCloneable; import org.jfree.chart.entity.EntityCollection; import org.jfree.chart.event.RendererChangeEvent; import org.jfree.chart.labels.CategoryItemLabelGenerator; import org.jfree.chart.labels.ItemLabelAnchor; import org.jfree.chart.labels.ItemLabelPosition; import org.jfree.chart.plot.CategoryPlot; import org.jfree.chart.plot.PlotOrientation; import org.jfree.data.DataUtilities; import org.jfree.data.Range; import org.jfree.data.category.CategoryDataset; import org.jfree.data.general.DatasetUtilities; /** * A stacked bar renderer for use with the {@link CategoryPlot} class. * The example shown here is generated by the * <code>StackedBarChartDemo1.java</code> program included in the * JFreeChart Demo Collection: * <br><br> * <img src="../../../../../images/StackedBarRendererSample.png" * alt="StackedBarRendererSample.png" /> */ public class StackedBarRenderer extends BarRenderer implements Cloneable, PublicCloneable, Serializable { /** For serialization. */ static final long serialVersionUID = 6402943811500067531L; /** A flag that controls whether the bars display values or percentages. */ private boolean renderAsPercentages; /** * Creates a new renderer. By default, the renderer has no tool tip * generator and no URL generator. These defaults have been chosen to * minimise the processing required to generate a default chart. If you * require tool tips or URLs, then you can easily add the required * generators. */ public StackedBarRenderer() { this(false); } /** * Creates a new renderer. * * @param renderAsPercentages a flag that controls whether the data values * are rendered as percentages. */ public StackedBarRenderer(boolean renderAsPercentages) { super(); this.renderAsPercentages = renderAsPercentages; // set the default item label positions, which will only be used if // the user requests visible item labels... ItemLabelPosition p = new ItemLabelPosition(ItemLabelAnchor.CENTER, TextAnchor.CENTER); setDefaultPositiveItemLabelPosition(p); setDefaultNegativeItemLabelPosition(p); setPositiveItemLabelPositionFallback(null); setNegativeItemLabelPositionFallback(null); } /** * Returns <code>true</code> if the renderer displays each item value as * a percentage (so that the stacked bars add to 100%), and * <code>false</code> otherwise. * * @return A boolean. * * @see #setRenderAsPercentages(boolean) */ public boolean getRenderAsPercentages() { return this.renderAsPercentages; } /** * Sets the flag that controls whether the renderer displays each item * value as a percentage (so that the stacked bars add to 100%), and sends * a {@link RendererChangeEvent} to all registered listeners. * * @param asPercentages the flag. * * @see #getRenderAsPercentages() */ public void setRenderAsPercentages(boolean asPercentages) { this.renderAsPercentages = asPercentages; fireChangeEvent(); } /** * Returns the number of passes (<code>3</code>) required by this renderer. * The first pass is used to draw the bar shadows, the second pass is used * to draw the bars, and the third pass is used to draw the item labels * (if visible). * * @return The number of passes required by the renderer. */ @Override public int getPassCount() { return 3; } /** * Returns the range of values the renderer requires to display all the * items from the specified dataset. * * @param dataset the dataset (<code>null</code> permitted). * * @return The range (or <code>null</code> if the dataset is empty). */ @Override public Range findRangeBounds(CategoryDataset dataset) { if (dataset == null) { return null; } if (this.renderAsPercentages) { return new Range(0.0, 1.0); } else { return DatasetUtilities.findStackedRangeBounds(dataset, getBase()); } } /** * Calculates the bar width and stores it in the renderer state. * * @param plot the plot. * @param dataArea the data area. * @param rendererIndex the renderer index. * @param state the renderer state. */ @Override protected void calculateBarWidth(CategoryPlot plot, Rectangle2D dataArea, int rendererIndex, CategoryItemRendererState state) { // calculate the bar width CategoryAxis xAxis = plot.getDomainAxisForDataset(rendererIndex); CategoryDataset data = plot.getDataset(rendererIndex); if (data != null) { PlotOrientation orientation = plot.getOrientation(); double space = 0.0; if (orientation == PlotOrientation.HORIZONTAL) { space = dataArea.getHeight(); } else if (orientation == PlotOrientation.VERTICAL) { space = dataArea.getWidth(); } double maxWidth = space * getMaximumBarWidth(); int columns = data.getColumnCount(); double categoryMargin = 0.0; if (columns > 1) { categoryMargin = xAxis.getCategoryMargin(); } double used = space * (1 - xAxis.getLowerMargin() - xAxis.getUpperMargin() - categoryMargin); if (columns > 0) { state.setBarWidth(Math.min(used / columns, maxWidth)); } else { state.setBarWidth(Math.min(used, maxWidth)); } } } /** * Draws a stacked bar for a specific item. * * @param g2 the graphics device. * @param state the renderer state. * @param dataArea the plot area. * @param plot the plot. * @param domainAxis the domain (category) axis. * @param rangeAxis the range (value) axis. * @param dataset the data. * @param row the row index (zero-based). * @param column the column index (zero-based). * @param pass the pass index. */ @Override public void drawItem(Graphics2D g2, CategoryItemRendererState state, Rectangle2D dataArea, CategoryPlot plot, CategoryAxis domainAxis, ValueAxis rangeAxis, CategoryDataset dataset, int row, int column, int pass) { if (!isSeriesVisible(row)) { return; } // nothing is drawn for null values... Number dataValue = dataset.getValue(row, column); if (dataValue == null) { return; } double value = dataValue.doubleValue(); double total = 0.0; // only needed if calculating percentages if (this.renderAsPercentages) { total = DataUtilities.calculateColumnTotal(dataset, column, state.getVisibleSeriesArray()); value = value / total; } PlotOrientation orientation = plot.getOrientation(); double barW0 = domainAxis.getCategoryMiddle(column, getColumnCount(), dataArea, plot.getDomainAxisEdge()) - state.getBarWidth() / 2.0; double positiveBase = getBase(); double negativeBase = positiveBase; for (int i = 0; i < row; i++) { Number v = dataset.getValue(i, column); if (v != null && isSeriesVisible(i)) { double d = v.doubleValue(); if (this.renderAsPercentages) { d = d / total; } if (d > 0) { positiveBase = positiveBase + d; } else { negativeBase = negativeBase + d; } } } double translatedBase; double translatedValue; boolean positive = (value > 0.0); boolean inverted = rangeAxis.isInverted(); RectangleEdge barBase; if (orientation == PlotOrientation.HORIZONTAL) { if (positive && inverted || !positive && !inverted) { barBase = RectangleEdge.RIGHT; } else { barBase = RectangleEdge.LEFT; } } else { if (positive && !inverted || !positive && inverted) { barBase = RectangleEdge.BOTTOM; } else { barBase = RectangleEdge.TOP; } } RectangleEdge location = plot.getRangeAxisEdge(); if (positive) { translatedBase = rangeAxis.valueToJava2D(positiveBase, dataArea, location); translatedValue = rangeAxis.valueToJava2D(positiveBase + value, dataArea, location); } else { translatedBase = rangeAxis.valueToJava2D(negativeBase, dataArea, location); translatedValue = rangeAxis.valueToJava2D(negativeBase + value, dataArea, location); } double barL0 = Math.min(translatedBase, translatedValue); double barLength = Math.max(Math.abs(translatedValue - translatedBase), getMinimumBarLength()); Rectangle2D bar = null; if (orientation == PlotOrientation.HORIZONTAL) { bar = new Rectangle2D.Double(barL0, barW0, barLength, state.getBarWidth()); } else { bar = new Rectangle2D.Double(barW0, barL0, state.getBarWidth(), barLength); } if (pass == 0) { if (getShadowsVisible()) { boolean pegToBase = (positive && (positiveBase == getBase())) || (!positive && (negativeBase == getBase())); getBarPainter().paintBarShadow(g2, this, row, column, bar, barBase, pegToBase); } } else if (pass == 1) { getBarPainter().paintBar(g2, this, row, column, bar, barBase); // add an item entity, if this information is being collected EntityCollection entities = state.getEntityCollection(); if (entities != null) { addItemEntity(entities, dataset, row, column, bar); } } else if (pass == 2) { CategoryItemLabelGenerator generator = getItemLabelGenerator(row, column); if (generator != null && isItemLabelVisible(row, column)) { drawItemLabel(g2, dataset, row, column, plot, generator, bar, (value < 0.0)); } } } /** * Tests this renderer for equality with an arbitrary object. * * @param obj the object (<code>null</code> permitted). * * @return A boolean. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof StackedBarRenderer)) { return false; } StackedBarRenderer that = (StackedBarRenderer) obj; if (this.renderAsPercentages != that.renderAsPercentages) { return false; } return super.equals(obj); } }
17,068
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
BoxAndWhiskerRenderer.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/renderer/category/BoxAndWhiskerRenderer.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * -------------------------- * BoxAndWhiskerRenderer.java * -------------------------- * (C) Copyright 2003-2012, by David Browning and Contributors. * * Original Author: David Browning (for the Australian Institute of Marine * Science); * Contributor(s): David Gilbert (for Object Refinery Limited); * Tim Bardzil; * Rob Van der Sanden (patches 1866446 and 1888422); * Peter Becker (patches 2868585 and 2868608); * Martin Krauskopf (patch 3421088); * Martin Hoeller; * * Changes * ------- * 21-Aug-2003 : Version 1, contributed by David Browning (for the Australian * Institute of Marine Science); * 01-Sep-2003 : Incorporated outlier and farout symbols for low values * also (DG); * 08-Sep-2003 : Changed ValueAxis API (DG); * 16-Sep-2003 : Changed ChartRenderingInfo --> PlotRenderingInfo (DG); * 07-Oct-2003 : Added renderer state (DG); * 12-Nov-2003 : Fixed casting bug reported by Tim Bardzil (DG); * 13-Nov-2003 : Added drawHorizontalItem() method contributed by Tim * Bardzil (DG); * 25-Apr-2004 : Added fillBox attribute, equals() method and added * serialization code (DG); * 29-Apr-2004 : Changed drawing of upper and lower shadows - see bug report * 944011 (DG); * 05-Nov-2004 : Modified drawItem() signature (DG); * 09-Mar-2005 : Override getLegendItem() method so that legend item shapes * are shown as blocks (DG); * 20-Apr-2005 : Generate legend labels, tooltips and URLs (DG); * 09-Jun-2005 : Updated equals() to handle GradientPaint (DG); * ------------- JFREECHART 1.0.x --------------------------------------------- * 12-Oct-2006 : Source reformatting and API doc updates (DG); * 12-Oct-2006 : Fixed bug 1572478, potential NullPointerException (DG); * 05-Feb-2006 : Added event notifications to a couple of methods (DG); * 20-Apr-2007 : Updated getLegendItem() for renderer change (DG); * 11-May-2007 : Added check for visibility in getLegendItem() (DG); * 17-May-2007 : Set datasetIndex and seriesIndex in getLegendItem() (DG); * 18-May-2007 : Set dataset and seriesKey for LegendItem (DG); * 03-Jan-2008 : Check visibility of average marker before drawing it (DG); * 15-Jan-2008 : Add getMaximumBarWidth() and setMaximumBarWidth() * methods (RVdS); * 14-Feb-2008 : Fix bar position for horizontal chart, see patch * 1888422 (RVdS); * 27-Mar-2008 : Boxes should use outlinePaint/Stroke settings (DG); * 17-Jun-2008 : Apply legend shape, font and paint attributes (DG); * 02-Oct-2008 : Check item visibility in drawItem() method (DG); * 21-Jan-2009 : Added flags to control visibility of mean and median * indicators (DG); * 28-Sep-2009 : Added fireChangeEvent() to setMedianVisible (DG); * 28-Sep-2009 : Added useOutlinePaintForWhiskers flag, see patch 2868585 * by Peter Becker (DG); * 28-Sep-2009 : Added whiskerWidth attribute, see patch 2868608 by Peter * Becker (DG); * 11-Oct-2011 : applied patch #3421088 from Martin Krauskopf to fix bug (MH); * 16-Jun-2012 : Removed JCommon dependencies (DG); * */ package org.jfree.chart.renderer.category; import java.awt.Color; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.Shape; import java.awt.Stroke; import java.awt.geom.Ellipse2D; import java.awt.geom.Line2D; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.jfree.chart.LegendItem; import org.jfree.chart.axis.CategoryAxis; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.ui.RectangleEdge; import org.jfree.chart.util.PaintUtilities; import org.jfree.chart.util.PublicCloneable; import org.jfree.chart.entity.EntityCollection; import org.jfree.chart.event.RendererChangeEvent; import org.jfree.chart.plot.CategoryPlot; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.PlotRenderingInfo; import org.jfree.chart.renderer.Outlier; import org.jfree.chart.renderer.OutlierList; import org.jfree.chart.renderer.OutlierListCollection; import org.jfree.chart.util.SerialUtilities; import org.jfree.data.Range; import org.jfree.data.category.CategoryDataset; import org.jfree.data.statistics.BoxAndWhiskerCategoryDataset; /** * A box-and-whisker renderer. This renderer requires a * {@link BoxAndWhiskerCategoryDataset} and is for use with the * {@link CategoryPlot} class. The example shown here is generated * by the <code>BoxAndWhiskerChartDemo1.java</code> program included in the * JFreeChart Demo Collection: * <br><br> * <img src="../../../../../images/BoxAndWhiskerRendererSample.png" * alt="BoxAndWhiskerRendererSample.png" /> */ public class BoxAndWhiskerRenderer extends AbstractCategoryItemRenderer implements Cloneable, PublicCloneable, Serializable { /** For serialization. */ private static final long serialVersionUID = 632027470694481177L; /** The color used to paint the median line and average marker. */ private transient Paint artifactPaint; /** A flag that controls whether or not the box is filled. */ private boolean fillBox; /** The margin between items (boxes) within a category. */ private double itemMargin; /** * The maximum bar width as percentage of the available space in the plot. * Take care with the encoding - for example, 0.05 is five percent. */ private double maximumBarWidth; /** * A flag that controls whether or not the median indicator is drawn. * * @since 1.0.13 */ private boolean medianVisible; /** * A flag that controls whether or not the mean indicator is drawn. * * @since 1.0.13 */ private boolean meanVisible; /** * A flag that, if <code>true</code>, causes the whiskers to be drawn * using the outline paint for the series. The default value is * <code>false</code> and in that case the regular series paint is used. * * @since 1.0.14 */ private boolean useOutlinePaintForWhiskers; /** * The width of the whiskers as fraction of the bar width. * * @since 1.0.14 */ private double whiskerWidth; /** * Default constructor. */ public BoxAndWhiskerRenderer() { this.artifactPaint = Color.BLACK; this.fillBox = true; this.itemMargin = 0.20; this.maximumBarWidth = 1.0; this.medianVisible = true; this.meanVisible = true; this.useOutlinePaintForWhiskers = false; this.whiskerWidth = 1.0; setDefaultLegendShape(new Rectangle2D.Double(-4.0, -4.0, 8.0, 8.0)); } /** * Returns the paint used to color the median and average markers. * * @return The paint used to draw the median and average markers (never * <code>null</code>). * * @see #setArtifactPaint(Paint) */ public Paint getArtifactPaint() { return this.artifactPaint; } /** * Sets the paint used to color the median and average markers and sends * a {@link RendererChangeEvent} to all registered listeners. * * @param paint the paint (<code>null</code> not permitted). * * @see #getArtifactPaint() */ public void setArtifactPaint(Paint paint) { if (paint == null) { throw new IllegalArgumentException("Null 'paint' argument."); } this.artifactPaint = paint; fireChangeEvent(); } /** * Returns the flag that controls whether or not the box is filled. * * @return A boolean. * * @see #setFillBox(boolean) */ public boolean getFillBox() { return this.fillBox; } /** * Sets the flag that controls whether or not the box is filled and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param flag the flag. * * @see #getFillBox() */ public void setFillBox(boolean flag) { this.fillBox = flag; fireChangeEvent(); } /** * Returns the item margin. This is a percentage of the available space * that is allocated to the space between items in the chart. * * @return The margin. * * @see #setItemMargin(double) */ public double getItemMargin() { return this.itemMargin; } /** * Sets the item margin and sends a {@link RendererChangeEvent} to all * registered listeners. * * @param margin the margin (a percentage). * * @see #getItemMargin() */ public void setItemMargin(double margin) { this.itemMargin = margin; fireChangeEvent(); } /** * Returns the maximum bar width as a percentage of the available drawing * space. Take care with the encoding, for example 0.10 is ten percent. * * @return The maximum bar width. * * @see #setMaximumBarWidth(double) * * @since 1.0.10 */ public double getMaximumBarWidth() { return this.maximumBarWidth; } /** * Sets the maximum bar width, which is specified as a percentage of the * available space for all bars, and sends a {@link RendererChangeEvent} * to all registered listeners. * * @param percent the maximum bar width (a percentage, where 0.10 is ten * percent). * * @see #getMaximumBarWidth() * * @since 1.0.10 */ public void setMaximumBarWidth(double percent) { this.maximumBarWidth = percent; fireChangeEvent(); } /** * Returns the flag that controls whether or not the mean indicator is * draw for each item. * * @return A boolean. * * @see #setMeanVisible(boolean) * * @since 1.0.13 */ public boolean isMeanVisible() { return this.meanVisible; } /** * Sets the flag that controls whether or not the mean indicator is drawn * for each item, and sends a {@link RendererChangeEvent} to all * registered listeners. * * @param visible the new flag value. * * @see #isMeanVisible() * * @since 1.0.13 */ public void setMeanVisible(boolean visible) { if (this.meanVisible == visible) { return; } this.meanVisible = visible; fireChangeEvent(); } /** * Returns the flag that controls whether or not the median indicator is * draw for each item. * * @return A boolean. * * @see #setMedianVisible(boolean) * * @since 1.0.13 */ public boolean isMedianVisible() { return this.medianVisible; } /** * Sets the flag that controls whether or not the median indicator is drawn * for each item, and sends a {@link RendererChangeEvent} to all * registered listeners. * * @param visible the new flag value. * * @see #isMedianVisible() * * @since 1.0.13 */ public void setMedianVisible(boolean visible) { if (this.medianVisible == visible) { return; } this.medianVisible = visible; fireChangeEvent(); } /** * Returns the flag that, if <code>true</code>, causes the whiskers to * be drawn using the series outline paint. * * @return A boolean. * * @since 1.0.14 */ public boolean getUseOutlinePaintForWhiskers() { return this.useOutlinePaintForWhiskers; } /** * Sets the flag that, if <code>true</code>, causes the whiskers to * be drawn using the series outline paint, and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param flag the new flag value. * * @since 1.0.14 */ public void setUseOutlinePaintForWhiskers(boolean flag) { if (this.useOutlinePaintForWhiskers == flag) { return; } this.useOutlinePaintForWhiskers = flag; fireChangeEvent(); } /** * Returns the width of the whiskers as fraction of the bar width. * * @return The width of the whiskers. * * @see #setWhiskerWidth(double) * * @since 1.0.14 */ public double getWhiskerWidth() { return this.whiskerWidth; } /** * Sets the width of the whiskers as a fraction of the bar width and sends * a {@link RendererChangeEvent} to all registered listeners. * * @param width a value between 0 and 1 indicating how wide the * whisker is supposed to be compared to the bar. * @see #getWhiskerWidth() * @see CategoryItemRendererState#getBarWidth() * * @since 1.0.14 */ public void setWhiskerWidth(double width) { if (width < 0 || width > 1) { throw new IllegalArgumentException( "Value for whisker width out of range"); } if (width == this.whiskerWidth) { return; } this.whiskerWidth = width; fireChangeEvent(); } /** * Returns a legend item for a series. * * @param datasetIndex the dataset index (zero-based). * @param series the series index (zero-based). * * @return The legend item (possibly <code>null</code>). */ @Override public LegendItem getLegendItem(int datasetIndex, int series) { CategoryPlot cp = getPlot(); if (cp == null) { return null; } // check that a legend item needs to be displayed... if (!isSeriesVisible(series) || !isSeriesVisibleInLegend(series)) { return null; } CategoryDataset dataset = cp.getDataset(datasetIndex); String label = getLegendItemLabelGenerator().generateLabel(dataset, series); String description = label; String toolTipText = null; if (getLegendItemToolTipGenerator() != null) { toolTipText = getLegendItemToolTipGenerator().generateLabel( dataset, series); } String urlText = null; if (getLegendItemURLGenerator() != null) { urlText = getLegendItemURLGenerator().generateLabel(dataset, series); } Shape shape = lookupLegendShape(series); Paint paint = lookupSeriesPaint(series); Paint outlinePaint = lookupSeriesOutlinePaint(series); Stroke outlineStroke = lookupSeriesOutlineStroke(series); LegendItem result = new LegendItem(label, description, toolTipText, urlText, shape, paint, outlineStroke, outlinePaint); result.setLabelFont(lookupLegendTextFont(series)); Paint labelPaint = lookupLegendTextPaint(series); if (labelPaint != null) { result.setLabelPaint(labelPaint); } result.setDataset(dataset); result.setDatasetIndex(datasetIndex); result.setSeriesKey(dataset.getRowKey(series)); result.setSeriesIndex(series); return result; } /** * Returns the range of values from the specified dataset that the * renderer will require to display all the data. * * @param dataset the dataset. * * @return The range. */ @Override public Range findRangeBounds(CategoryDataset dataset) { return super.findRangeBounds(dataset, true); } /** * Initialises the renderer. This method gets called once at the start of * the process of drawing a chart. * * @param g2 the graphics device. * @param dataArea the area in which the data is to be plotted. * @param plot the plot. * @param rendererIndex the renderer index. * @param info collects chart rendering information for return to caller. * * @return The renderer state. */ @Override public CategoryItemRendererState initialise(Graphics2D g2, Rectangle2D dataArea, CategoryPlot plot, int rendererIndex, PlotRenderingInfo info) { CategoryItemRendererState state = super.initialise(g2, dataArea, plot, rendererIndex, info); // calculate the box width CategoryAxis domainAxis = getDomainAxis(plot, rendererIndex); CategoryDataset dataset = plot.getDataset(rendererIndex); if (dataset != null) { int columns = dataset.getColumnCount(); int rows = dataset.getRowCount(); double space = 0.0; PlotOrientation orientation = plot.getOrientation(); if (orientation == PlotOrientation.HORIZONTAL) { space = dataArea.getHeight(); } else if (orientation == PlotOrientation.VERTICAL) { space = dataArea.getWidth(); } double maxWidth = space * getMaximumBarWidth(); double categoryMargin = 0.0; double currentItemMargin = 0.0; if (columns > 1) { categoryMargin = domainAxis.getCategoryMargin(); } if (rows > 1) { currentItemMargin = getItemMargin(); } double used = space * (1 - domainAxis.getLowerMargin() - domainAxis.getUpperMargin() - categoryMargin - currentItemMargin); if ((rows * columns) > 0) { state.setBarWidth(Math.min(used / (dataset.getColumnCount() * dataset.getRowCount()), maxWidth)); } else { state.setBarWidth(Math.min(used, maxWidth)); } } return state; } /** * Draw a single data item. * * @param g2 the graphics device. * @param state the renderer state. * @param dataArea the area in which the data is drawn. * @param plot the plot. * @param domainAxis the domain axis. * @param rangeAxis the range axis. * @param dataset the data (must be an instance of * {@link BoxAndWhiskerCategoryDataset}). * @param row the row index (zero-based). * @param column the column index (zero-based). * @param pass the pass index. */ @Override public void drawItem(Graphics2D g2, CategoryItemRendererState state, Rectangle2D dataArea, CategoryPlot plot, CategoryAxis domainAxis, ValueAxis rangeAxis, CategoryDataset dataset, int row, int column, int pass) { // do nothing if item is not visible if (!getItemVisible(row, column)) { return; } if (!(dataset instanceof BoxAndWhiskerCategoryDataset)) { throw new IllegalArgumentException( "BoxAndWhiskerRenderer.drawItem() : the data should be " + "of type BoxAndWhiskerCategoryDataset only."); } PlotOrientation orientation = plot.getOrientation(); if (orientation == PlotOrientation.HORIZONTAL) { drawHorizontalItem(g2, state, dataArea, plot, domainAxis, rangeAxis, dataset, row, column); } else if (orientation == PlotOrientation.VERTICAL) { drawVerticalItem(g2, state, dataArea, plot, domainAxis, rangeAxis, dataset, row, column); } } /** * Draws the visual representation of a single data item when the plot has * a horizontal orientation. * * @param g2 the graphics device. * @param state the renderer state. * @param dataArea the area within which the plot is being drawn. * @param plot the plot (can be used to obtain standard color * information etc). * @param domainAxis the domain axis. * @param rangeAxis the range axis. * @param dataset the dataset (must be an instance of * {@link BoxAndWhiskerCategoryDataset}). * @param row the row index (zero-based). * @param column the column index (zero-based). */ public void drawHorizontalItem(Graphics2D g2, CategoryItemRendererState state, Rectangle2D dataArea, CategoryPlot plot, CategoryAxis domainAxis, ValueAxis rangeAxis, CategoryDataset dataset, int row, int column) { BoxAndWhiskerCategoryDataset bawDataset = (BoxAndWhiskerCategoryDataset) dataset; double categoryEnd = domainAxis.getCategoryEnd(column, getColumnCount(), dataArea, plot.getDomainAxisEdge()); double categoryStart = domainAxis.getCategoryStart(column, getColumnCount(), dataArea, plot.getDomainAxisEdge()); double categoryWidth = Math.abs(categoryEnd - categoryStart); double yy = categoryStart; int seriesCount = getRowCount(); int categoryCount = getColumnCount(); if (seriesCount > 1) { double seriesGap = dataArea.getHeight() * getItemMargin() / (categoryCount * (seriesCount - 1)); double usedWidth = (state.getBarWidth() * seriesCount) + (seriesGap * (seriesCount - 1)); // offset the start of the boxes if the total width used is smaller // than the category width double offset = (categoryWidth - usedWidth) / 2; yy = yy + offset + (row * (state.getBarWidth() + seriesGap)); } else { // offset the start of the box if the box width is smaller than // the category width double offset = (categoryWidth - state.getBarWidth()) / 2; yy = yy + offset; } g2.setPaint(getItemPaint(row, column)); Stroke s = getItemStroke(row, column); g2.setStroke(s); RectangleEdge location = plot.getRangeAxisEdge(); Number xQ1 = bawDataset.getQ1Value(row, column); Number xQ3 = bawDataset.getQ3Value(row, column); Number xMax = bawDataset.getMaxRegularValue(row, column); Number xMin = bawDataset.getMinRegularValue(row, column); Shape box = null; if (xQ1 != null && xQ3 != null && xMax != null && xMin != null) { double xxQ1 = rangeAxis.valueToJava2D(xQ1.doubleValue(), dataArea, location); double xxQ3 = rangeAxis.valueToJava2D(xQ3.doubleValue(), dataArea, location); double xxMax = rangeAxis.valueToJava2D(xMax.doubleValue(), dataArea, location); double xxMin = rangeAxis.valueToJava2D(xMin.doubleValue(), dataArea, location); double yymid = yy + state.getBarWidth() / 2.0; double halfW = (state.getBarWidth() / 2.0) * this.whiskerWidth; // draw the box... box = new Rectangle2D.Double(Math.min(xxQ1, xxQ3), yy, Math.abs(xxQ1 - xxQ3), state.getBarWidth()); if (this.fillBox) { g2.fill(box); } Paint outlinePaint = getItemOutlinePaint(row, column); if (this.useOutlinePaintForWhiskers) { g2.setPaint(outlinePaint); } // draw the upper shadow... g2.draw(new Line2D.Double(xxMax, yymid, xxQ3, yymid)); g2.draw(new Line2D.Double(xxMax, yymid - halfW, xxMax, yymid + halfW)); // draw the lower shadow... g2.draw(new Line2D.Double(xxMin, yymid, xxQ1, yymid)); g2.draw(new Line2D.Double(xxMin, yymid - halfW, xxMin, yy + halfW)); g2.setStroke(getItemOutlineStroke(row, column)); g2.setPaint(outlinePaint); g2.draw(box); } // draw mean - SPECIAL AIMS REQUIREMENT... g2.setPaint(this.artifactPaint); double aRadius; // average radius if (this.meanVisible) { Number xMean = bawDataset.getMeanValue(row, column); if (xMean != null) { double xxMean = rangeAxis.valueToJava2D(xMean.doubleValue(), dataArea, location); aRadius = state.getBarWidth() / 4; // here we check that the average marker will in fact be // visible before drawing it... if ((xxMean > (dataArea.getMinX() - aRadius)) && (xxMean < (dataArea.getMaxX() + aRadius))) { Ellipse2D.Double avgEllipse = new Ellipse2D.Double(xxMean - aRadius, yy + aRadius, aRadius * 2, aRadius * 2); g2.fill(avgEllipse); g2.draw(avgEllipse); } } } // draw median... if (this.medianVisible) { Number xMedian = bawDataset.getMedianValue(row, column); if (xMedian != null) { double xxMedian = rangeAxis.valueToJava2D(xMedian.doubleValue(), dataArea, location); g2.draw(new Line2D.Double(xxMedian, yy, xxMedian, yy + state.getBarWidth())); } } // collect entity and tool tip information... if (state.getInfo() != null && box != null) { EntityCollection entities = state.getEntityCollection(); if (entities != null) { addItemEntity(entities, dataset, row, column, box); } } } /** * Draws the visual representation of a single data item when the plot has * a vertical orientation. * * @param g2 the graphics device. * @param state the renderer state. * @param dataArea the area within which the plot is being drawn. * @param plot the plot (can be used to obtain standard color information * etc). * @param domainAxis the domain axis. * @param rangeAxis the range axis. * @param dataset the dataset (must be an instance of * {@link BoxAndWhiskerCategoryDataset}). * @param row the row index (zero-based). * @param column the column index (zero-based). */ public void drawVerticalItem(Graphics2D g2, CategoryItemRendererState state, Rectangle2D dataArea, CategoryPlot plot, CategoryAxis domainAxis, ValueAxis rangeAxis, CategoryDataset dataset, int row, int column) { BoxAndWhiskerCategoryDataset bawDataset = (BoxAndWhiskerCategoryDataset) dataset; double categoryEnd = domainAxis.getCategoryEnd(column, getColumnCount(), dataArea, plot.getDomainAxisEdge()); double categoryStart = domainAxis.getCategoryStart(column, getColumnCount(), dataArea, plot.getDomainAxisEdge()); double categoryWidth = categoryEnd - categoryStart; double xx = categoryStart; int seriesCount = getRowCount(); int categoryCount = getColumnCount(); if (seriesCount > 1) { double seriesGap = dataArea.getWidth() * getItemMargin() / (categoryCount * (seriesCount - 1)); double usedWidth = (state.getBarWidth() * seriesCount) + (seriesGap * (seriesCount - 1)); // offset the start of the boxes if the total width used is smaller // than the category width double offset = (categoryWidth - usedWidth) / 2; xx = xx + offset + (row * (state.getBarWidth() + seriesGap)); } else { // offset the start of the box if the box width is smaller than the // category width double offset = (categoryWidth - state.getBarWidth()) / 2; xx = xx + offset; } double yyAverage; double yyOutlier; Paint itemPaint = getItemPaint(row, column); g2.setPaint(itemPaint); Stroke s = getItemStroke(row, column); g2.setStroke(s); double aRadius = 0; // average radius RectangleEdge location = plot.getRangeAxisEdge(); Number yQ1 = bawDataset.getQ1Value(row, column); Number yQ3 = bawDataset.getQ3Value(row, column); Number yMax = bawDataset.getMaxRegularValue(row, column); Number yMin = bawDataset.getMinRegularValue(row, column); Shape box = null; if (yQ1 != null && yQ3 != null && yMax != null && yMin != null) { double yyQ1 = rangeAxis.valueToJava2D(yQ1.doubleValue(), dataArea, location); double yyQ3 = rangeAxis.valueToJava2D(yQ3.doubleValue(), dataArea, location); double yyMax = rangeAxis.valueToJava2D(yMax.doubleValue(), dataArea, location); double yyMin = rangeAxis.valueToJava2D(yMin.doubleValue(), dataArea, location); double xxmid = xx + state.getBarWidth() / 2.0; double halfW = (state.getBarWidth() / 2.0) * this.whiskerWidth; // draw the body... box = new Rectangle2D.Double(xx, Math.min(yyQ1, yyQ3), state.getBarWidth(), Math.abs(yyQ1 - yyQ3)); if (this.fillBox) { g2.fill(box); } Paint outlinePaint = getItemOutlinePaint(row, column); if (this.useOutlinePaintForWhiskers) { g2.setPaint(outlinePaint); } // draw the upper shadow... g2.draw(new Line2D.Double(xxmid, yyMax, xxmid, yyQ3)); g2.draw(new Line2D.Double(xxmid - halfW, yyMax, xxmid + halfW, yyMax)); // draw the lower shadow... g2.draw(new Line2D.Double(xxmid, yyMin, xxmid, yyQ1)); g2.draw(new Line2D.Double(xxmid - halfW, yyMin, xxmid + halfW, yyMin)); g2.setStroke(getItemOutlineStroke(row, column)); g2.setPaint(outlinePaint); g2.draw(box); } g2.setPaint(this.artifactPaint); // draw mean - SPECIAL AIMS REQUIREMENT... if (this.meanVisible) { Number yMean = bawDataset.getMeanValue(row, column); if (yMean != null) { yyAverage = rangeAxis.valueToJava2D(yMean.doubleValue(), dataArea, location); aRadius = state.getBarWidth() / 4; // here we check that the average marker will in fact be // visible before drawing it... if ((yyAverage > (dataArea.getMinY() - aRadius)) && (yyAverage < (dataArea.getMaxY() + aRadius))) { Ellipse2D.Double avgEllipse = new Ellipse2D.Double( xx + aRadius, yyAverage - aRadius, aRadius * 2, aRadius * 2); g2.fill(avgEllipse); g2.draw(avgEllipse); } } } // draw median... if (this.medianVisible) { Number yMedian = bawDataset.getMedianValue(row, column); if (yMedian != null) { double yyMedian = rangeAxis.valueToJava2D( yMedian.doubleValue(), dataArea, location); g2.draw(new Line2D.Double(xx, yyMedian, xx + state.getBarWidth(), yyMedian)); } } // draw yOutliers... double maxAxisValue = rangeAxis.valueToJava2D( rangeAxis.getUpperBound(), dataArea, location) + aRadius; double minAxisValue = rangeAxis.valueToJava2D( rangeAxis.getLowerBound(), dataArea, location) - aRadius; g2.setPaint(itemPaint); // draw outliers double oRadius = state.getBarWidth() / 3; // outlier radius List<Outlier> outliers = new ArrayList<Outlier>(); OutlierListCollection outlierListCollection = new OutlierListCollection(); // From outlier array sort out which are outliers and put these into a // list If there are any farouts, set the flag on the // OutlierListCollection List<Number> yOutliers = bawDataset.getOutliers(row, column); if (yOutliers != null) { for (Number yOutlier : yOutliers) { double outlier = ((Number) yOutlier).doubleValue(); Number minOutlier = bawDataset.getMinOutlier(row, column); Number maxOutlier = bawDataset.getMaxOutlier(row, column); Number minRegular = bawDataset.getMinRegularValue(row, column); Number maxRegular = bawDataset.getMaxRegularValue(row, column); if (outlier > maxOutlier.doubleValue()) { outlierListCollection.setHighFarOut(true); } else if (outlier < minOutlier.doubleValue()) { outlierListCollection.setLowFarOut(true); } else if (outlier > maxRegular.doubleValue()) { yyOutlier = rangeAxis.valueToJava2D(outlier, dataArea, location); outliers.add(new Outlier(xx + state.getBarWidth() / 2.0, yyOutlier, oRadius)); } else if (outlier < minRegular.doubleValue()) { yyOutlier = rangeAxis.valueToJava2D(outlier, dataArea, location); outliers.add(new Outlier(xx + state.getBarWidth() / 2.0, yyOutlier, oRadius)); } Collections.sort(outliers); } // Process outliers. Each outlier is either added to the // appropriate outlier list or a new outlier list is made for (Outlier outlier : outliers) { outlierListCollection.add(outlier); } for (OutlierList list : outlierListCollection) { Outlier outlier = list.getAveragedOutlier(); Point2D point = outlier.getPoint(); if (list.isMultiple()) { drawMultipleEllipse(point, state.getBarWidth(), oRadius, g2); } else { drawEllipse(point, oRadius, g2); } } // draw farout indicators if (outlierListCollection.isHighFarOut()) { drawHighFarOut(aRadius / 2.0, g2, xx + state.getBarWidth() / 2.0, maxAxisValue); } if (outlierListCollection.isLowFarOut()) { drawLowFarOut(aRadius / 2.0, g2, xx + state.getBarWidth() / 2.0, minAxisValue); } } // collect entity and tool tip information... if (state.getInfo() != null && box != null) { EntityCollection entities = state.getEntityCollection(); if (entities != null) { addItemEntity(entities, dataset, row, column, box); } } } /** * Draws a dot to represent an outlier. * * @param point the location. * @param oRadius the radius. * @param g2 the graphics device. */ private void drawEllipse(Point2D point, double oRadius, Graphics2D g2) { Ellipse2D dot = new Ellipse2D.Double(point.getX() + oRadius / 2, point.getY(), oRadius, oRadius); g2.draw(dot); } /** * Draws two dots to represent the average value of more than one outlier. * * @param point the location * @param boxWidth the box width. * @param oRadius the radius. * @param g2 the graphics device. */ private void drawMultipleEllipse(Point2D point, double boxWidth, double oRadius, Graphics2D g2) { Ellipse2D dot1 = new Ellipse2D.Double(point.getX() - (boxWidth / 2) + oRadius, point.getY(), oRadius, oRadius); Ellipse2D dot2 = new Ellipse2D.Double(point.getX() + (boxWidth / 2), point.getY(), oRadius, oRadius); g2.draw(dot1); g2.draw(dot2); } /** * Draws a triangle to indicate the presence of far-out values. * * @param aRadius the radius. * @param g2 the graphics device. * @param xx the x coordinate. * @param m the y coordinate. */ private void drawHighFarOut(double aRadius, Graphics2D g2, double xx, double m) { double side = aRadius * 2; g2.draw(new Line2D.Double(xx - side, m + side, xx + side, m + side)); g2.draw(new Line2D.Double(xx - side, m + side, xx, m)); g2.draw(new Line2D.Double(xx + side, m + side, xx, m)); } /** * Draws a triangle to indicate the presence of far-out values. * * @param aRadius the radius. * @param g2 the graphics device. * @param xx the x coordinate. * @param m the y coordinate. */ private void drawLowFarOut(double aRadius, Graphics2D g2, double xx, double m) { double side = aRadius * 2; g2.draw(new Line2D.Double(xx - side, m - side, xx + side, m - side)); g2.draw(new Line2D.Double(xx - side, m - side, xx, m)); g2.draw(new Line2D.Double(xx + side, m - side, xx, m)); } /** * Tests this renderer for equality with an arbitrary object. * * @param obj the object (<code>null</code> permitted). * * @return <code>true</code> or <code>false</code>. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof BoxAndWhiskerRenderer)) { return false; } BoxAndWhiskerRenderer that = (BoxAndWhiskerRenderer) obj; if (this.fillBox != that.fillBox) { return false; } if (this.itemMargin != that.itemMargin) { return false; } if (this.maximumBarWidth != that.maximumBarWidth) { return false; } if (this.meanVisible != that.meanVisible) { return false; } if (this.medianVisible != that.medianVisible) { return false; } if (this.useOutlinePaintForWhiskers != that.useOutlinePaintForWhiskers) { return false; } if (this.whiskerWidth != that.whiskerWidth) { return false; } if (!PaintUtilities.equal(this.artifactPaint, that.artifactPaint)) { return false; } return super.equals(obj); } /** * Provides serialization support. * * @param stream the output stream. * * @throws IOException if there is an I/O error. */ private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); SerialUtilities.writePaint(this.artifactPaint, stream); } /** * Provides serialization support. * * @param stream the input stream. * * @throws IOException if there is an I/O error. * @throws ClassNotFoundException if there is a classpath problem. */ private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); this.artifactPaint = SerialUtilities.readPaint(stream); } }
41,130
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
StatisticalLineAndShapeRenderer.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/renderer/category/StatisticalLineAndShapeRenderer.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ------------------------------------ * StatisticalLineAndShapeRenderer.java * ------------------------------------ * (C) Copyright 2005-2012, by Object Refinery Limited and Contributors. * * Original Author: Mofeed Shahin; * Contributor(s): David Gilbert (for Object Refinery Limited); * Peter Kolb (patch 2497611); * * Changes * ------- * 01-Feb-2005 : Version 1, contributed by Mofeed Shahin (DG); * 16-Jun-2005 : Added errorIndicatorPaint to be consistent with * StatisticalBarRenderer (DG); * ------------- JFREECHART 1.0.x --------------------------------------------- * 11-Apr-2006 : Fixed bug 1468794, error bars drawn incorrectly when rendering * plots with horizontal orientation (DG); * 25-Sep-2006 : Fixed bug 1562759, constructor ignoring arguments (DG); * 01-Jun-2007 : Return early from drawItem() method if item is not * visible (DG); * 14-Jun-2007 : If the dataset is not a StatisticalCategoryDataset, revert * to the drawing behaviour of LineAndShapeRenderer (DG); * 27-Sep-2007 : Added offset option to match new option in * LineAndShapeRenderer (DG); * 14-Jan-2009 : Added support for seriesVisible flags (PK); * 23-Jan-2009 : Observe useFillPaint and drawOutlines flags (PK); * 23-Jan-2009 : In drawItem, divide code into passes (DG); * 05-Feb-2009 : Added errorIndicatorStroke field (DG); * 01-Apr-2009 : Added override for findRangeBounds(), and fixed NPE in * creating item entities (DG); * 17-Jun-2012 : Removed JCommon dependencies (DG); * */ package org.jfree.chart.renderer.category; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.Shape; import java.awt.Stroke; import java.awt.geom.Line2D; import java.awt.geom.Rectangle2D; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import org.jfree.chart.HashUtilities; import org.jfree.chart.axis.CategoryAxis; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.ui.RectangleEdge; import org.jfree.chart.util.ObjectUtilities; import org.jfree.chart.util.PaintUtilities; import org.jfree.chart.util.PublicCloneable; import org.jfree.chart.util.ShapeUtilities; import org.jfree.chart.entity.EntityCollection; import org.jfree.chart.event.RendererChangeEvent; import org.jfree.chart.plot.CategoryPlot; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.util.SerialUtilities; import org.jfree.data.Range; import org.jfree.data.category.CategoryDataset; import org.jfree.data.statistics.StatisticalCategoryDataset; /** * A renderer that draws shapes for each data item, and lines between data * items. Each point has a mean value and a standard deviation line. For use * with the {@link CategoryPlot} class. The example shown * here is generated by the <code>StatisticalLineChartDemo1.java</code> program * included in the JFreeChart Demo Collection: * <br><br> * <img src="../../../../../images/StatisticalLineRendererSample.png" * alt="StatisticalLineRendererSample.png" /> */ public class StatisticalLineAndShapeRenderer extends LineAndShapeRenderer implements Cloneable, PublicCloneable, Serializable { /** For serialization. */ private static final long serialVersionUID = -3557517173697777579L; /** The paint used to show the error indicator. */ private transient Paint errorIndicatorPaint; /** * The stroke used to draw the error indicators. If null, the renderer * will use the itemOutlineStroke. * * @since 1.0.13 */ private transient Stroke errorIndicatorStroke; /** * Constructs a default renderer (draws shapes and lines). */ public StatisticalLineAndShapeRenderer() { this(true, true); } /** * Constructs a new renderer. * * @param linesVisible draw lines? * @param shapesVisible draw shapes? */ public StatisticalLineAndShapeRenderer(boolean linesVisible, boolean shapesVisible) { super(linesVisible, shapesVisible); this.errorIndicatorPaint = null; this.errorIndicatorStroke = null; } /** * Returns the paint used for the error indicators. * * @return The paint used for the error indicators (possibly * <code>null</code>). * * @see #setErrorIndicatorPaint(Paint) */ public Paint getErrorIndicatorPaint() { return this.errorIndicatorPaint; } /** * Sets the paint used for the error indicators (if <code>null</code>, * the item paint is used instead) and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param paint the paint (<code>null</code> permitted). * * @see #getErrorIndicatorPaint() */ public void setErrorIndicatorPaint(Paint paint) { this.errorIndicatorPaint = paint; fireChangeEvent(); } /** * Returns the stroke used for the error indicators. * * @return The stroke used for the error indicators (possibly * <code>null</code>). * * @see #setErrorIndicatorStroke(Stroke) * * @since 1.0.13 */ public Stroke getErrorIndicatorStroke() { return this.errorIndicatorStroke; } /** * Sets the stroke used for the error indicators (if <code>null</code>, * the item outline stroke is used instead) and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param stroke the stroke (<code>null</code> permitted). * * @see #getErrorIndicatorStroke() * * @since 1.0.13 */ public void setErrorIndicatorStroke(Stroke stroke) { this.errorIndicatorStroke = stroke; fireChangeEvent(); } /** * Returns the range of values the renderer requires to display all the * items from the specified dataset. * * @param dataset the dataset (<code>null</code> permitted). * * @return The range (or <code>null</code> if the dataset is * <code>null</code> or empty). */ @Override public Range findRangeBounds(CategoryDataset dataset) { return findRangeBounds(dataset, true); } /** * Draw a single data item. * * @param g2 the graphics device. * @param state the renderer state. * @param dataArea the area in which the data is drawn. * @param plot the plot. * @param domainAxis the domain axis. * @param rangeAxis the range axis. * @param dataset the dataset (a {@link StatisticalCategoryDataset} is * required). * @param row the row index (zero-based). * @param column the column index (zero-based). * @param pass the pass. */ @Override public void drawItem(Graphics2D g2, CategoryItemRendererState state, Rectangle2D dataArea, CategoryPlot plot, CategoryAxis domainAxis, ValueAxis rangeAxis, CategoryDataset dataset, int row, int column, int pass) { // do nothing if item is not visible if (!getItemVisible(row, column)) { return; } // if the dataset is not a StatisticalCategoryDataset then just revert // to the superclass (LineAndShapeRenderer) behaviour... if (!(dataset instanceof StatisticalCategoryDataset)) { super.drawItem(g2, state, dataArea, plot, domainAxis, rangeAxis, dataset, row, column, pass); return; } int visibleRow = state.getVisibleSeriesIndex(row); if (visibleRow < 0) { return; } int visibleRowCount = state.getVisibleSeriesCount(); StatisticalCategoryDataset statDataset = (StatisticalCategoryDataset) dataset; Number meanValue = statDataset.getMeanValue(row, column); if (meanValue == null) { return; } PlotOrientation orientation = plot.getOrientation(); // current data point... double x1; if (getUseSeriesOffset()) { x1 = domainAxis.getCategorySeriesMiddle(column, dataset.getColumnCount(), visibleRow, visibleRowCount, getItemMargin(), dataArea, plot.getDomainAxisEdge()); } else { x1 = domainAxis.getCategoryMiddle(column, getColumnCount(), dataArea, plot.getDomainAxisEdge()); } double y1 = rangeAxis.valueToJava2D(meanValue.doubleValue(), dataArea, plot.getRangeAxisEdge()); // draw the standard deviation lines *before* the shapes (if they're // visible) - it looks better if the shape fill colour is different to // the line colour Number sdv = statDataset.getStdDevValue(row, column); if (pass == 1 && sdv != null) { //standard deviation lines RectangleEdge yAxisLocation = plot.getRangeAxisEdge(); double valueDelta = sdv.doubleValue(); double highVal, lowVal; if ((meanValue.doubleValue() + valueDelta) > rangeAxis.getRange().getUpperBound()) { highVal = rangeAxis.valueToJava2D( rangeAxis.getRange().getUpperBound(), dataArea, yAxisLocation); } else { highVal = rangeAxis.valueToJava2D(meanValue.doubleValue() + valueDelta, dataArea, yAxisLocation); } if ((meanValue.doubleValue() + valueDelta) < rangeAxis.getRange().getLowerBound()) { lowVal = rangeAxis.valueToJava2D( rangeAxis.getRange().getLowerBound(), dataArea, yAxisLocation); } else { lowVal = rangeAxis.valueToJava2D(meanValue.doubleValue() - valueDelta, dataArea, yAxisLocation); } if (this.errorIndicatorPaint != null) { g2.setPaint(this.errorIndicatorPaint); } else { g2.setPaint(getItemPaint(row, column)); } if (this.errorIndicatorStroke != null) { g2.setStroke(this.errorIndicatorStroke); } else { g2.setStroke(getItemOutlineStroke(row, column)); } Line2D line = new Line2D.Double(); if (orientation == PlotOrientation.HORIZONTAL) { line.setLine(lowVal, x1, highVal, x1); g2.draw(line); line.setLine(lowVal, x1 - 5.0d, lowVal, x1 + 5.0d); g2.draw(line); line.setLine(highVal, x1 - 5.0d, highVal, x1 + 5.0d); g2.draw(line); } else { // PlotOrientation.VERTICAL line.setLine(x1, lowVal, x1, highVal); g2.draw(line); line.setLine(x1 - 5.0d, highVal, x1 + 5.0d, highVal); g2.draw(line); line.setLine(x1 - 5.0d, lowVal, x1 + 5.0d, lowVal); g2.draw(line); } } Shape hotspot = null; if (pass == 1 && getItemShapeVisible(row, column)) { Shape shape = getItemShape(row, column); if (orientation == PlotOrientation.HORIZONTAL) { shape = ShapeUtilities.createTranslatedShape(shape, y1, x1); } else if (orientation == PlotOrientation.VERTICAL) { shape = ShapeUtilities.createTranslatedShape(shape, x1, y1); } hotspot = shape; if (getItemShapeFilled(row, column)) { if (getUseFillPaint()) { g2.setPaint(getItemFillPaint(row, column)); } else { g2.setPaint(getItemPaint(row, column)); } g2.fill(shape); } if (getDrawOutlines()) { if (getUseOutlinePaint()) { g2.setPaint(getItemOutlinePaint(row, column)); } else { g2.setPaint(getItemPaint(row, column)); } g2.setStroke(getItemOutlineStroke(row, column)); g2.draw(shape); } // draw the item label if there is one... if (isItemLabelVisible(row, column)) { if (orientation == PlotOrientation.HORIZONTAL) { drawItemLabel(g2, orientation, dataset, row, column, y1, x1, (meanValue.doubleValue() < 0.0)); } else if (orientation == PlotOrientation.VERTICAL) { drawItemLabel(g2, orientation, dataset, row, column, x1, y1, (meanValue.doubleValue() < 0.0)); } } } if (pass == 0 && getItemLineVisible(row, column)) { if (column != 0) { Number previousValue = statDataset.getValue(row, column - 1); if (previousValue != null) { // previous data point... double previous = previousValue.doubleValue(); double x0; if (getUseSeriesOffset()) { x0 = domainAxis.getCategorySeriesMiddle( column - 1, dataset.getColumnCount(), visibleRow, visibleRowCount, getItemMargin(), dataArea, plot.getDomainAxisEdge()); } else { x0 = domainAxis.getCategoryMiddle(column - 1, getColumnCount(), dataArea, plot.getDomainAxisEdge()); } double y0 = rangeAxis.valueToJava2D(previous, dataArea, plot.getRangeAxisEdge()); Line2D line = null; if (orientation == PlotOrientation.HORIZONTAL) { line = new Line2D.Double(y0, x0, y1, x1); } else if (orientation == PlotOrientation.VERTICAL) { line = new Line2D.Double(x0, y0, x1, y1); } g2.setPaint(getItemPaint(row, column)); g2.setStroke(getItemStroke(row, column)); g2.draw(line); } } } if (pass == 1) { // add an item entity, if this information is being collected EntityCollection entities = state.getEntityCollection(); if (entities != null) { addEntity(entities, hotspot, dataset, row, column, x1, y1); } } } /** * Tests this renderer for equality with an arbitrary object. * * @param obj the object (<code>null</code> permitted). * * @return A boolean. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof StatisticalLineAndShapeRenderer)) { return false; } StatisticalLineAndShapeRenderer that = (StatisticalLineAndShapeRenderer) obj; if (!PaintUtilities.equal(this.errorIndicatorPaint, that.errorIndicatorPaint)) { return false; } if (!ObjectUtilities.equal(this.errorIndicatorStroke, that.errorIndicatorStroke)) { return false; } return super.equals(obj); } /** * Returns a hash code for this instance. * * @return A hash code. */ @Override public int hashCode() { int hash = super.hashCode(); hash = HashUtilities.hashCode(hash, this.errorIndicatorPaint); return hash; } /** * Provides serialization support. * * @param stream the output stream. * * @throws IOException if there is an I/O error. */ private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); SerialUtilities.writePaint(this.errorIndicatorPaint, stream); SerialUtilities.writeStroke(this.errorIndicatorStroke, stream); } /** * Provides serialization support. * * @param stream the input stream. * * @throws IOException if there is an I/O error. * @throws ClassNotFoundException if there is a classpath problem. */ private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); this.errorIndicatorPaint = SerialUtilities.readPaint(stream); this.errorIndicatorStroke = SerialUtilities.readStroke(stream); } }
18,529
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
StandardBarPainter.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/renderer/category/StandardBarPainter.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ----------------------- * StandardBarPainter.java * ----------------------- * (C) Copyright 2008-2012, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes: * -------- * 19-Jun-2008 : Version 1 (DG); * 15-Aug-2008 : Use renderer's shadow paint (DG); * 17-Jun-2012 : Remove JCommon dependencies (DG); * */ package org.jfree.chart.renderer.category; import java.awt.Color; import java.awt.GradientPaint; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.Stroke; import java.awt.geom.Rectangle2D; import java.awt.geom.RectangularShape; import java.io.Serializable; import org.jfree.chart.ui.GradientPaintTransformer; import org.jfree.chart.ui.RectangleEdge; /** * An implementation of the {@link BarPainter} interface that preserves the * behaviour of bar painting that existed prior to the introduction of the * {@link BarPainter} interface. * * @see GradientBarPainter * * @since 1.0.11 */ public class StandardBarPainter implements BarPainter, Serializable { /** * Creates a new instance. */ public StandardBarPainter() { } /** * Paints a single bar instance. * * @param g2 the graphics target. * @param renderer the renderer. * @param row the row index. * @param column the column index. * @param bar the bar * @param base indicates which side of the rectangle is the base of the * bar. */ @Override public void paintBar(Graphics2D g2, BarRenderer renderer, int row, int column, RectangularShape bar, RectangleEdge base) { Paint itemPaint = renderer.getItemPaint(row, column); GradientPaintTransformer t = renderer.getGradientPaintTransformer(); if (t != null && itemPaint instanceof GradientPaint) { itemPaint = t.transform((GradientPaint) itemPaint, bar); } g2.setPaint(itemPaint); g2.fill(bar); // draw the outline... if (renderer.isDrawBarOutline()) { // && state.getBarWidth() > BAR_OUTLINE_WIDTH_THRESHOLD) { Stroke stroke = renderer.getItemOutlineStroke(row, column); Paint paint = renderer.getItemOutlinePaint(row, column); if (stroke != null && paint != null) { g2.setStroke(stroke); g2.setPaint(paint); g2.draw(bar); } } } /** * Paints a single bar instance. * * @param g2 the graphics target. * @param renderer the renderer. * @param row the row index. * @param column the column index. * @param bar the bar * @param base indicates which side of the rectangle is the base of the * bar. * @param pegShadow peg the shadow to the base of the bar? */ @Override public void paintBarShadow(Graphics2D g2, BarRenderer renderer, int row, int column, RectangularShape bar, RectangleEdge base, boolean pegShadow) { // handle a special case - if the bar colour has alpha == 0, it is // invisible so we shouldn't draw any shadow Paint itemPaint = renderer.getItemPaint(row, column); if (itemPaint instanceof Color) { Color c = (Color) itemPaint; if (c.getAlpha() == 0) { return; } } RectangularShape shadow = createShadow(bar, renderer.getShadowXOffset(), renderer.getShadowYOffset(), base, pegShadow); g2.setPaint(renderer.getShadowPaint()); g2.fill(shadow); } /** * Creates a shadow for the bar. * * @param bar the bar shape. * @param xOffset the x-offset for the shadow. * @param yOffset the y-offset for the shadow. * @param base the edge that is the base of the bar. * @param pegShadow peg the shadow to the base? * * @return A rectangle for the shadow. */ private Rectangle2D createShadow(RectangularShape bar, double xOffset, double yOffset, RectangleEdge base, boolean pegShadow) { double x0 = bar.getMinX(); double x1 = bar.getMaxX(); double y0 = bar.getMinY(); double y1 = bar.getMaxY(); if (base == RectangleEdge.TOP) { x0 += xOffset; x1 += xOffset; if (!pegShadow) { y0 += yOffset; } y1 += yOffset; } else if (base == RectangleEdge.BOTTOM) { x0 += xOffset; x1 += xOffset; y0 += yOffset; if (!pegShadow) { y1 += yOffset; } } else if (base == RectangleEdge.LEFT) { if (!pegShadow) { x0 += xOffset; } x1 += xOffset; y0 += yOffset; y1 += yOffset; } else if (base == RectangleEdge.RIGHT) { x0 += xOffset; if (!pegShadow) { x1 += xOffset; } y0 += yOffset; y1 += yOffset; } return new Rectangle2D.Double(x0, y0, (x1 - x0), (y1 - y0)); } /** * Tests this instance for equality with an arbitrary object. * * @param obj the obj (<code>null</code> permitted). * * @return A boolean. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof StandardBarPainter)) { return false; } return true; } /** * Returns a hash code for this instance. * * @return A hash code. */ @Override public int hashCode() { int hash = 37; // no fields to compute... return hash; } }
7,086
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
DefaultCategoryItemRenderer.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/renderer/category/DefaultCategoryItemRenderer.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * -------------------------------- * DefaultCategoryItemRenderer.java * -------------------------------- * (C) Copyright 2003-2008, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 29-Apr-2003 : Version 1 (DG); * */ package org.jfree.chart.renderer.category; import java.io.Serializable; import org.jfree.chart.plot.CategoryPlot; /** * A default renderer for the {@link CategoryPlot} class. This is simply an * alias for the {@link LineAndShapeRenderer} class. */ public class DefaultCategoryItemRenderer extends LineAndShapeRenderer implements Serializable { /** For serialization. */ private static final long serialVersionUID = -7793786349384231896L; // no new methods }
2,085
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
AreaRenderer.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/renderer/category/AreaRenderer.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ----------------- * AreaRenderer.java * ----------------- * (C) Copyright 2002-2012, by Jon Iles and Contributors. * * Original Author: Jon Iles; * Contributor(s): David Gilbert (for Object Refinery Limited); * Christian W. Zuckschwerdt; * * Changes: * -------- * 21-May-2002 : Version 1, contributed by John Iles (DG); * 29-May-2002 : Now extends AbstractCategoryItemRenderer (DG); * 11-Jun-2002 : Updated Javadoc comments (DG); * 25-Jun-2002 : Removed unnecessary imports (DG); * 01-Oct-2002 : Fixed errors reported by Checkstyle (DG); * 10-Oct-2002 : Added constructors and basic entity support (DG); * 24-Oct-2002 : Amendments for changes in CategoryDataset interface and * CategoryToolTipGenerator interface (DG); * 05-Nov-2002 : Replaced references to CategoryDataset with TableDataset (DG); * 06-Nov-2002 : Renamed drawCategoryItem() --> drawItem() and now using axis * for category spacing. Renamed AreaCategoryItemRenderer * --> AreaRenderer (DG); * 17-Jan-2003 : Moved plot classes into a separate package (DG); * 25-Mar-2003 : Implemented Serializable (DG); * 10-Apr-2003 : Changed CategoryDataset to KeyedValues2DDataset in * drawItem() method (DG); * 12-May-2003 : Modified to take into account the plot orientation (DG); * 30-Jul-2003 : Modified entity constructor (CZ); * 13-Aug-2003 : Implemented Cloneable (DG); * 07-Oct-2003 : Added renderer state (DG); * 05-Nov-2004 : Modified drawItem() signature (DG); * 20-Apr-2005 : Apply tooltips and URLs to legend items (DG); * 09-Jun-2005 : Use addItemEntity() method from superclass (DG); * ------------- JFREECHART 1.0.x --------------------------------------------- * 11-Oct-2006 : Fixed bug in equals() method (DG); * 30-Nov-2006 : Added checks for series visibility (DG); * 20-Apr-2007 : Updated getLegendItem() for renderer change (DG); * 17-May-2007 : Set datasetIndex and seriesIndex in getLegendItem() (DG); * 18-May-2007 : Set dataset and seriesKey for LegendItem (DG); * 17-Jun-2008 : Apply legend shape, font and paint attributes (DG); * 26-Jun-2008 : Added crosshair support (DG); * 26-May-2009 : Support AreaRendererEndType.LEVEL (DG); * 27-May-2009 : Fixed item label anchor for horizontal orientation (DG); * 16-Jun-2012 : Removed JCommon dependencies (DG); * */ package org.jfree.chart.renderer.category; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.Shape; import java.awt.Stroke; import java.awt.geom.GeneralPath; import java.awt.geom.Rectangle2D; import java.io.Serializable; import org.jfree.chart.LegendItem; import org.jfree.chart.axis.CategoryAxis; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.ui.RectangleEdge; import org.jfree.chart.util.PublicCloneable; import org.jfree.chart.entity.EntityCollection; import org.jfree.chart.event.RendererChangeEvent; import org.jfree.chart.plot.CategoryPlot; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.renderer.AreaRendererEndType; import org.jfree.data.category.CategoryDataset; /** * A category item renderer that draws area charts. You can use this renderer * with the {@link CategoryPlot} class. The example shown here is generated * by the <code>AreaChartDemo1.java</code> program included in the JFreeChart * Demo Collection: * <br><br> * <img src="../../../../../images/AreaRendererSample.png" * alt="AreaRendererSample.png" /> */ public class AreaRenderer extends AbstractCategoryItemRenderer implements Cloneable, PublicCloneable, Serializable { /** For serialization. */ private static final long serialVersionUID = -4231878281385812757L; /** A flag that controls how the ends of the areas are drawn. */ private AreaRendererEndType endType; /** * Creates a new renderer. */ public AreaRenderer() { super(); this.endType = AreaRendererEndType.TAPER; setDefaultLegendShape(new Rectangle2D.Double(-4.0, -4.0, 8.0, 8.0)); } /** * Returns a token that controls how the renderer draws the end points. * The default value is {@link AreaRendererEndType#TAPER}. * * @return The end type (never <code>null</code>). * * @see #setEndType */ public AreaRendererEndType getEndType() { return this.endType; } /** * Sets a token that controls how the renderer draws the end points, and * sends a {@link RendererChangeEvent} to all registered listeners. * * @param type the end type (<code>null</code> not permitted). * * @see #getEndType() */ public void setEndType(AreaRendererEndType type) { if (type == null) { throw new IllegalArgumentException("Null 'type' argument."); } this.endType = type; fireChangeEvent(); } /** * Returns a legend item for a series. * * @param datasetIndex the dataset index (zero-based). * @param series the series index (zero-based). * * @return The legend item. */ @Override public LegendItem getLegendItem(int datasetIndex, int series) { // if there is no plot, there is no dataset to access... CategoryPlot cp = getPlot(); if (cp == null) { return null; } // check that a legend item needs to be displayed... if (!isSeriesVisible(series) || !isSeriesVisibleInLegend(series)) { return null; } CategoryDataset dataset = cp.getDataset(datasetIndex); String label = getLegendItemLabelGenerator().generateLabel(dataset, series); String description = label; String toolTipText = null; if (getLegendItemToolTipGenerator() != null) { toolTipText = getLegendItemToolTipGenerator().generateLabel( dataset, series); } String urlText = null; if (getLegendItemURLGenerator() != null) { urlText = getLegendItemURLGenerator().generateLabel(dataset, series); } Shape shape = lookupLegendShape(series); Paint paint = lookupSeriesPaint(series); Paint outlinePaint = lookupSeriesOutlinePaint(series); Stroke outlineStroke = lookupSeriesOutlineStroke(series); LegendItem result = new LegendItem(label, description, toolTipText, urlText, shape, paint, outlineStroke, outlinePaint); result.setLabelFont(lookupLegendTextFont(series)); Paint labelPaint = lookupLegendTextPaint(series); if (labelPaint != null) { result.setLabelPaint(labelPaint); } result.setDataset(dataset); result.setDatasetIndex(datasetIndex); result.setSeriesKey(dataset.getRowKey(series)); result.setSeriesIndex(series); return result; } /** * Draw a single data item. * * @param g2 the graphics device. * @param state the renderer state. * @param dataArea the data plot area. * @param plot the plot. * @param domainAxis the domain axis. * @param rangeAxis the range axis. * @param dataset the dataset. * @param row the row index (zero-based). * @param column the column index (zero-based). * @param pass the pass index. */ @Override public void drawItem(Graphics2D g2, CategoryItemRendererState state, Rectangle2D dataArea, CategoryPlot plot, CategoryAxis domainAxis, ValueAxis rangeAxis, CategoryDataset dataset, int row, int column, int pass) { // do nothing if item is not visible or null if (!getItemVisible(row, column)) { return; } Number value = dataset.getValue(row, column); if (value == null) { return; } PlotOrientation orientation = plot.getOrientation(); RectangleEdge axisEdge = plot.getDomainAxisEdge(); int count = dataset.getColumnCount(); float x0 = (float) domainAxis.getCategoryStart(column, count, dataArea, axisEdge); float x1 = (float) domainAxis.getCategoryMiddle(column, count, dataArea, axisEdge); float x2 = (float) domainAxis.getCategoryEnd(column, count, dataArea, axisEdge); x0 = Math.round(x0); x1 = Math.round(x1); x2 = Math.round(x2); if (this.endType == AreaRendererEndType.TRUNCATE) { if (column == 0) { x0 = x1; } else if (column == getColumnCount() - 1) { x2 = x1; } } double yy1 = value.doubleValue(); double yy0 = 0.0; if (this.endType == AreaRendererEndType.LEVEL) { yy0 = yy1; } if (column > 0) { Number n0 = dataset.getValue(row, column - 1); if (n0 != null) { yy0 = (n0.doubleValue() + yy1) / 2.0; } } double yy2 = 0.0; if (column < dataset.getColumnCount() - 1) { Number n2 = dataset.getValue(row, column + 1); if (n2 != null) { yy2 = (n2.doubleValue() + yy1) / 2.0; } } else if (this.endType == AreaRendererEndType.LEVEL) { yy2 = yy1; } RectangleEdge edge = plot.getRangeAxisEdge(); float y0 = (float) rangeAxis.valueToJava2D(yy0, dataArea, edge); float y1 = (float) rangeAxis.valueToJava2D(yy1, dataArea, edge); float y2 = (float) rangeAxis.valueToJava2D(yy2, dataArea, edge); float yz = (float) rangeAxis.valueToJava2D(0.0, dataArea, edge); double labelXX = x1; double labelYY = y1; g2.setPaint(getItemPaint(row, column)); g2.setStroke(getItemStroke(row, column)); GeneralPath area = new GeneralPath(); if (orientation == PlotOrientation.VERTICAL) { area.moveTo(x0, yz); area.lineTo(x0, y0); area.lineTo(x1, y1); area.lineTo(x2, y2); area.lineTo(x2, yz); } else if (orientation == PlotOrientation.HORIZONTAL) { area.moveTo(yz, x0); area.lineTo(y0, x0); area.lineTo(y1, x1); area.lineTo(y2, x2); area.lineTo(yz, x2); double temp = labelXX; labelXX = labelYY; labelYY = temp; } area.closePath(); g2.setPaint(getItemPaint(row, column)); g2.fill(area); // draw the item labels if there are any... if (isItemLabelVisible(row, column)) { drawItemLabel(g2, orientation, dataset, row, column, labelXX, labelYY, (value.doubleValue() < 0.0)); } // submit the current data point as a crosshair candidate int datasetIndex = plot.indexOf(dataset); updateCrosshairValues(state.getCrosshairState(), dataset.getRowKey(row), dataset.getColumnKey(column), yy1, datasetIndex, x1, y1, orientation); // add an item entity, if this information is being collected EntityCollection entities = state.getEntityCollection(); if (entities != null) { addItemEntity(entities, dataset, row, column, area); } } /** * Tests this instance for equality with an arbitrary object. * * @param obj the object to test (<code>null</code> permitted). * * @return A boolean. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof AreaRenderer)) { return false; } AreaRenderer that = (AreaRenderer) obj; if (!this.endType.equals(that.endType)) { return false; } return super.equals(obj); } /** * Returns an independent copy of the renderer. * * @return A clone. * * @throws CloneNotSupportedException should not happen. */ @Override public Object clone() throws CloneNotSupportedException { return super.clone(); } }
13,447
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
GroupedStackedBarRenderer.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/renderer/category/GroupedStackedBarRenderer.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ------------------------------ * GroupedStackedBarRenderer.java * ------------------------------ * (C) Copyright 2004-2012, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 29-Apr-2004 : Version 1 (DG); * 08-Jul-2004 : Added equals() method (DG); * 05-Nov-2004 : Modified drawItem() signature (DG); * 07-Jan-2005 : Renamed getRangeExtent() --> findRangeBounds (DG); * 20-Apr-2005 : Renamed CategoryLabelGenerator * --> CategoryItemLabelGenerator (DG); * 22-Sep-2005 : Renamed getMaxBarWidth() --> getMaximumBarWidth() (DG); * 20-Dec-2007 : Fix for bug 1848961 (DG); * 24-Jun-2008 : Added new barPainter mechanism (DG); * 17-Jun-2012 : Removed JCommon dependencies (DG); * */ package org.jfree.chart.renderer.category; import java.awt.Graphics2D; import java.awt.geom.Rectangle2D; import java.io.Serializable; import org.jfree.chart.axis.CategoryAxis; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.ui.RectangleEdge; import org.jfree.chart.util.PublicCloneable; import org.jfree.chart.entity.EntityCollection; import org.jfree.chart.event.RendererChangeEvent; import org.jfree.chart.labels.CategoryItemLabelGenerator; import org.jfree.chart.plot.CategoryPlot; import org.jfree.chart.plot.PlotOrientation; import org.jfree.data.KeyToGroupMap; import org.jfree.data.Range; import org.jfree.data.category.CategoryDataset; import org.jfree.data.general.DatasetUtilities; /** * A renderer that draws stacked bars within groups. This will probably be * merged with the {@link StackedBarRenderer} class at some point. The example * shown here is generated by the <code>StackedBarChartDemo4.java</code> * program included in the JFreeChart Demo Collection: * <br><br> * <img src="../../../../../images/GroupedStackedBarRendererSample.png" * alt="GroupedStackedBarRendererSample.png" /> */ public class GroupedStackedBarRenderer extends StackedBarRenderer implements Cloneable, PublicCloneable, Serializable { /** For serialization. */ private static final long serialVersionUID = -2725921399005922939L; /** A map used to assign each series to a group. */ private KeyToGroupMap seriesToGroupMap; /** * Creates a new renderer. */ public GroupedStackedBarRenderer() { super(); this.seriesToGroupMap = new KeyToGroupMap(); } /** * Updates the map used to assign each series to a group, and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param map the map (<code>null</code> not permitted). */ public void setSeriesToGroupMap(KeyToGroupMap map) { if (map == null) { throw new IllegalArgumentException("Null 'map' argument."); } this.seriesToGroupMap = map; fireChangeEvent(); } /** * Returns the range of values the renderer requires to display all the * items from the specified dataset. * * @param dataset the dataset (<code>null</code> permitted). * * @return The range (or <code>null</code> if the dataset is * <code>null</code> or empty). */ @Override public Range findRangeBounds(CategoryDataset dataset) { if (dataset == null) { return null; } Range r = DatasetUtilities.findStackedRangeBounds( dataset, this.seriesToGroupMap); return r; } /** * Calculates the bar width and stores it in the renderer state. We * override the method in the base class to take account of the * series-to-group mapping. * * @param plot the plot. * @param dataArea the data area. * @param rendererIndex the renderer index. * @param state the renderer state. */ @Override protected void calculateBarWidth(CategoryPlot plot, Rectangle2D dataArea, int rendererIndex, CategoryItemRendererState state) { // calculate the bar width CategoryAxis xAxis = plot.getDomainAxisForDataset(rendererIndex); CategoryDataset data = plot.getDataset(rendererIndex); if (data != null) { PlotOrientation orientation = plot.getOrientation(); double space = 0.0; if (orientation == PlotOrientation.HORIZONTAL) { space = dataArea.getHeight(); } else if (orientation == PlotOrientation.VERTICAL) { space = dataArea.getWidth(); } double maxWidth = space * getMaximumBarWidth(); int groups = this.seriesToGroupMap.getGroupCount(); int categories = data.getColumnCount(); int columns = groups * categories; double categoryMargin = 0.0; double itemMargin = 0.0; if (categories > 1) { categoryMargin = xAxis.getCategoryMargin(); } if (groups > 1) { itemMargin = getItemMargin(); } double used = space * (1 - xAxis.getLowerMargin() - xAxis.getUpperMargin() - categoryMargin - itemMargin); if (columns > 0) { state.setBarWidth(Math.min(used / columns, maxWidth)); } else { state.setBarWidth(Math.min(used, maxWidth)); } } } /** * Calculates the coordinate of the first "side" of a bar. This will be * the minimum x-coordinate for a vertical bar, and the minimum * y-coordinate for a horizontal bar. * * @param plot the plot. * @param orientation the plot orientation. * @param dataArea the data area. * @param domainAxis the domain axis. * @param state the renderer state (has the bar width precalculated). * @param row the row index. * @param column the column index. * * @return The coordinate. */ @Override protected double calculateBarW0(CategoryPlot plot, PlotOrientation orientation, Rectangle2D dataArea, CategoryAxis domainAxis, CategoryItemRendererState state, int row, int column) { // calculate bar width... double space = 0.0; if (orientation == PlotOrientation.HORIZONTAL) { space = dataArea.getHeight(); } else { space = dataArea.getWidth(); } double barW0 = domainAxis.getCategoryStart(column, getColumnCount(), dataArea, plot.getDomainAxisEdge()); int groupCount = this.seriesToGroupMap.getGroupCount(); int groupIndex = this.seriesToGroupMap.getGroupIndex( this.seriesToGroupMap.getGroup(plot.getDataset( plot.getIndexOf(this)).getRowKey(row))); int categoryCount = getColumnCount(); if (groupCount > 1) { double groupGap = space * getItemMargin() / (categoryCount * (groupCount - 1)); double groupW = calculateSeriesWidth(space, domainAxis, categoryCount, groupCount); barW0 = barW0 + groupIndex * (groupW + groupGap) + (groupW / 2.0) - (state.getBarWidth() / 2.0); } else { barW0 = domainAxis.getCategoryMiddle(column, getColumnCount(), dataArea, plot.getDomainAxisEdge()) - state.getBarWidth() / 2.0; } return barW0; } /** * Draws a stacked bar for a specific item. * * @param g2 the graphics device. * @param state the renderer state. * @param dataArea the plot area. * @param plot the plot. * @param domainAxis the domain (category) axis. * @param rangeAxis the range (value) axis. * @param dataset the data. * @param row the row index (zero-based). * @param column the column index (zero-based). * @param pass the pass index. */ @Override public void drawItem(Graphics2D g2, CategoryItemRendererState state, Rectangle2D dataArea, CategoryPlot plot, CategoryAxis domainAxis, ValueAxis rangeAxis, CategoryDataset dataset, int row, int column, int pass) { // nothing is drawn for null values... Number dataValue = dataset.getValue(row, column); if (dataValue == null) { return; } double value = dataValue.doubleValue(); Comparable group = this.seriesToGroupMap.getGroup( dataset.getRowKey(row)); PlotOrientation orientation = plot.getOrientation(); double barW0 = calculateBarW0(plot, orientation, dataArea, domainAxis, state, row, column); double positiveBase = 0.0; double negativeBase = 0.0; for (int i = 0; i < row; i++) { if (group.equals(this.seriesToGroupMap.getGroup( dataset.getRowKey(i)))) { Number v = dataset.getValue(i, column); if (v != null) { double d = v.doubleValue(); if (d > 0) { positiveBase = positiveBase + d; } else { negativeBase = negativeBase + d; } } } } double translatedBase; double translatedValue; boolean positive = (value > 0.0); boolean inverted = rangeAxis.isInverted(); RectangleEdge barBase; if (orientation == PlotOrientation.HORIZONTAL) { if (positive && inverted || !positive && !inverted) { barBase = RectangleEdge.RIGHT; } else { barBase = RectangleEdge.LEFT; } } else { if (positive && !inverted || !positive && inverted) { barBase = RectangleEdge.BOTTOM; } else { barBase = RectangleEdge.TOP; } } RectangleEdge location = plot.getRangeAxisEdge(); if (value > 0.0) { translatedBase = rangeAxis.valueToJava2D(positiveBase, dataArea, location); translatedValue = rangeAxis.valueToJava2D(positiveBase + value, dataArea, location); } else { translatedBase = rangeAxis.valueToJava2D(negativeBase, dataArea, location); translatedValue = rangeAxis.valueToJava2D(negativeBase + value, dataArea, location); } double barL0 = Math.min(translatedBase, translatedValue); double barLength = Math.max(Math.abs(translatedValue - translatedBase), getMinimumBarLength()); Rectangle2D bar = null; if (orientation == PlotOrientation.HORIZONTAL) { bar = new Rectangle2D.Double(barL0, barW0, barLength, state.getBarWidth()); } else { bar = new Rectangle2D.Double(barW0, barL0, state.getBarWidth(), barLength); } getBarPainter().paintBar(g2, this, row, column, bar, barBase); CategoryItemLabelGenerator generator = getItemLabelGenerator(row, column); if (generator != null && isItemLabelVisible(row, column)) { drawItemLabel(g2, dataset, row, column, plot, generator, bar, (value < 0.0)); } // collect entity and tool tip information... if (state.getInfo() != null) { EntityCollection entities = state.getEntityCollection(); if (entities != null) { addItemEntity(entities, dataset, row, column, bar); } } } /** * Tests this renderer for equality with an arbitrary object. * * @param obj the object (<code>null</code> permitted). * * @return A boolean. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof GroupedStackedBarRenderer)) { return false; } GroupedStackedBarRenderer that = (GroupedStackedBarRenderer) obj; if (!this.seriesToGroupMap.equals(that.seriesToGroupMap)) { return false; } return super.equals(obj); } }
14,220
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
MinMaxCategoryRenderer.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/renderer/category/MinMaxCategoryRenderer.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * --------------------------- * MinMaxCategoryRenderer.java * --------------------------- * (C) Copyright 2002-2012, by Object Refinery Limited. * * Original Author: Tomer Peretz; * Contributor(s): David Gilbert (for Object Refinery Limited); * Christian W. Zuckschwerdt; * Nicolas Brodu (for Astrium and EADS Corporate Research * Center); * * Changes: * -------- * 29-May-2002 : Version 1 (TP); * 02-Oct-2002 : Fixed errors reported by Checkstyle (DG); * 24-Oct-2002 : Amendments for changes in CategoryDataset interface and * CategoryToolTipGenerator interface (DG); * 05-Nov-2002 : Base dataset is now TableDataset not CategoryDataset (DG); * 17-Jan-2003 : Moved plot classes to a separate package (DG); * 10-Apr-2003 : Changed CategoryDataset to KeyedValues2DDataset in drawItem() * method (DG); * 30-Jul-2003 : Modified entity constructor (CZ); * 08-Sep-2003 : Implemented Serializable (NB); * 29-Oct-2003 : Added workaround for font alignment in PDF output (DG); * 05-Nov-2004 : Modified drawItem() signature (DG); * 17-Nov-2005 : Added change events and argument checks (DG); * ------------- JFREECHART 1.0.x --------------------------------------------- * 02-Feb-2007 : Removed author tags all over JFreeChart sources (DG); * 09-Mar-2007 : Fixed problem with horizontal rendering (DG); * 28-Sep-2007 : Added equals() method override (DG); * 17-Jun-2012 : Removed JCommon dependencies (DG); * */ package org.jfree.chart.renderer.category; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Component; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.Shape; import java.awt.Stroke; import java.awt.geom.AffineTransform; import java.awt.geom.Arc2D; import java.awt.geom.GeneralPath; import java.awt.geom.Line2D; import java.awt.geom.Rectangle2D; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import javax.swing.Icon; import org.jfree.chart.axis.CategoryAxis; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.util.PaintUtilities; import org.jfree.chart.entity.EntityCollection; import org.jfree.chart.event.RendererChangeEvent; import org.jfree.chart.plot.CategoryPlot; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.util.SerialUtilities; import org.jfree.data.category.CategoryDataset; /** * Renderer for drawing min max plot. This renderer draws all the series under * the same category in the same x position using <code>objectIcon</code> and * a line from the maximum value to the minimum value. For use with the * {@link CategoryPlot} class. The example shown here is generated by * the <code>MinMaxCategoryPlotDemo1.java</code> program included in the * JFreeChart Demo Collection: * <br><br> * <img src="../../../../../images/MinMaxCategoryRendererSample.png" * alt="MinMaxCategoryRendererSample.png" /> */ public class MinMaxCategoryRenderer extends AbstractCategoryItemRenderer { /** For serialization. */ private static final long serialVersionUID = 2935615937671064911L; /** A flag indicating whether or not lines are drawn between XY points. */ private boolean plotLines = false; /** * The paint of the line between the minimum value and the maximum value. */ private transient Paint groupPaint = Color.BLACK; /** * The stroke of the line between the minimum value and the maximum value. */ private transient Stroke groupStroke = new BasicStroke(1.0f); /** The icon used to indicate the minimum value.*/ private transient Icon minIcon = getIcon(new Arc2D.Double(-4, -4, 8, 8, 0, 360, Arc2D.OPEN), null, Color.BLACK); /** The icon used to indicate the maximum value.*/ private transient Icon maxIcon = getIcon(new Arc2D.Double(-4, -4, 8, 8, 0, 360, Arc2D.OPEN), null, Color.BLACK); /** The icon used to indicate the values.*/ private transient Icon objectIcon = getIcon(new Line2D.Double(-4, 0, 4, 0), false, true); /** The last category. */ private int lastCategory = -1; /** The minimum. */ private double min; /** The maximum. */ private double max; /** * Default constructor. */ public MinMaxCategoryRenderer() { super(); } /** * Gets whether or not lines are drawn between category points. * * @return boolean true if line will be drawn between sequenced categories, * otherwise false. * * @see #setDrawLines(boolean) */ public boolean isDrawLines() { return this.plotLines; } /** * Sets the flag that controls whether or not lines are drawn to connect * the items within a series and sends a {@link RendererChangeEvent} to * all registered listeners. * * @param draw the new value of the flag. * * @see #isDrawLines() */ public void setDrawLines(boolean draw) { if (this.plotLines != draw) { this.plotLines = draw; fireChangeEvent(); } } /** * Returns the paint used to draw the line between the minimum and maximum * value items in each category. * * @return The paint (never <code>null</code>). * * @see #setGroupPaint(Paint) */ public Paint getGroupPaint() { return this.groupPaint; } /** * Sets the paint used to draw the line between the minimum and maximum * value items in each category and sends a {@link RendererChangeEvent} to * all registered listeners. * * @param paint the paint (<code>null</code> not permitted). * * @see #getGroupPaint() */ public void setGroupPaint(Paint paint) { if (paint == null) { throw new IllegalArgumentException("Null 'paint' argument."); } this.groupPaint = paint; fireChangeEvent(); } /** * Returns the stroke used to draw the line between the minimum and maximum * value items in each category. * * @return The stroke (never <code>null</code>). * * @see #setGroupStroke(Stroke) */ public Stroke getGroupStroke() { return this.groupStroke; } /** * Sets the stroke of the line between the minimum value and the maximum * value and sends a {@link RendererChangeEvent} to all registered * listeners. * * @param stroke the new stroke (<code>null</code> not permitted). */ public void setGroupStroke(Stroke stroke) { if (stroke == null) { throw new IllegalArgumentException("Null 'stroke' argument."); } this.groupStroke = stroke; fireChangeEvent(); } /** * Returns the icon drawn for each data item. * * @return The icon (never <code>null</code>). * * @see #setObjectIcon(Icon) */ public Icon getObjectIcon() { return this.objectIcon; } /** * Sets the icon drawn for each data item and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param icon the icon. * * @see #getObjectIcon() */ public void setObjectIcon(Icon icon) { if (icon == null) { throw new IllegalArgumentException("Null 'icon' argument."); } this.objectIcon = icon; fireChangeEvent(); } /** * Returns the icon displayed for the maximum value data item within each * category. * * @return The icon (never <code>null</code>). * * @see #setMaxIcon(Icon) */ public Icon getMaxIcon() { return this.maxIcon; } /** * Sets the icon displayed for the maximum value data item within each * category and sends a {@link RendererChangeEvent} to all registered * listeners. * * @param icon the icon (<code>null</code> not permitted). * * @see #getMaxIcon() */ public void setMaxIcon(Icon icon) { if (icon == null) { throw new IllegalArgumentException("Null 'icon' argument."); } this.maxIcon = icon; fireChangeEvent(); } /** * Returns the icon displayed for the minimum value data item within each * category. * * @return The icon (never <code>null</code>). * * @see #setMinIcon(Icon) */ public Icon getMinIcon() { return this.minIcon; } /** * Sets the icon displayed for the minimum value data item within each * category and sends a {@link RendererChangeEvent} to all registered * listeners. * * @param icon the icon (<code>null</code> not permitted). * * @see #getMinIcon() */ public void setMinIcon(Icon icon) { if (icon == null) { throw new IllegalArgumentException("Null 'icon' argument."); } this.minIcon = icon; fireChangeEvent(); } /** * Draw a single data item. * * @param g2 the graphics device. * @param state the renderer state. * @param dataArea the area in which the data is drawn. * @param plot the plot. * @param domainAxis the domain axis. * @param rangeAxis the range axis. * @param dataset the dataset. * @param row the row index (zero-based). * @param column the column index (zero-based). * @param pass the pass index. */ @Override public void drawItem(Graphics2D g2, CategoryItemRendererState state, Rectangle2D dataArea, CategoryPlot plot, CategoryAxis domainAxis, ValueAxis rangeAxis, CategoryDataset dataset, int row, int column, int pass) { // first check the number we are plotting... Number value = dataset.getValue(row, column); if (value != null) { // current data point... double x1 = domainAxis.getCategoryMiddle(column, getColumnCount(), dataArea, plot.getDomainAxisEdge()); double y1 = rangeAxis.valueToJava2D(value.doubleValue(), dataArea, plot.getRangeAxisEdge()); g2.setPaint(getItemPaint(row, column)); g2.setStroke(getItemStroke(row, column)); Shape shape = null; shape = new Rectangle2D.Double(x1 - 4, y1 - 4, 8.0, 8.0); PlotOrientation orient = plot.getOrientation(); if (orient == PlotOrientation.VERTICAL) { this.objectIcon.paintIcon(null, g2, (int) x1, (int) y1); } else { this.objectIcon.paintIcon(null, g2, (int) y1, (int) x1); } if (this.lastCategory == column) { if (this.min > value.doubleValue()) { this.min = value.doubleValue(); } if (this.max < value.doubleValue()) { this.max = value.doubleValue(); } // last series, so we are ready to draw the min and max if (dataset.getRowCount() - 1 == row) { g2.setPaint(this.groupPaint); g2.setStroke(this.groupStroke); double minY = rangeAxis.valueToJava2D(this.min, dataArea, plot.getRangeAxisEdge()); double maxY = rangeAxis.valueToJava2D(this.max, dataArea, plot.getRangeAxisEdge()); if (orient == PlotOrientation.VERTICAL) { g2.draw(new Line2D.Double(x1, minY, x1, maxY)); this.minIcon.paintIcon(null, g2, (int) x1, (int) minY); this.maxIcon.paintIcon(null, g2, (int) x1, (int) maxY); } else { g2.draw(new Line2D.Double(minY, x1, maxY, x1)); this.minIcon.paintIcon(null, g2, (int) minY, (int) x1); this.maxIcon.paintIcon(null, g2, (int) maxY, (int) x1); } } } else { // reset the min and max this.lastCategory = column; this.min = value.doubleValue(); this.max = value.doubleValue(); } // connect to the previous point if (this.plotLines) { if (column != 0) { Number previousValue = dataset.getValue(row, column - 1); if (previousValue != null) { // previous data point... double previous = previousValue.doubleValue(); double x0 = domainAxis.getCategoryMiddle(column - 1, getColumnCount(), dataArea, plot.getDomainAxisEdge()); double y0 = rangeAxis.valueToJava2D(previous, dataArea, plot.getRangeAxisEdge()); g2.setPaint(getItemPaint(row, column)); g2.setStroke(getItemStroke(row, column)); Line2D line; if (orient == PlotOrientation.VERTICAL) { line = new Line2D.Double(x0, y0, x1, y1); } else { line = new Line2D.Double(y0, x0, y1, x1); } g2.draw(line); } } } // add an item entity, if this information is being collected EntityCollection entities = state.getEntityCollection(); if (entities != null && shape != null) { addItemEntity(entities, dataset, row, column, shape); } } } /** * Tests this instance for equality with an arbitrary object. The icon * fields are NOT included in the test, so this implementation is a little * weak. * * @param obj the object (<code>null</code> permitted). * * @return A boolean. * * @since 1.0.7 */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof MinMaxCategoryRenderer)) { return false; } MinMaxCategoryRenderer that = (MinMaxCategoryRenderer) obj; if (this.plotLines != that.plotLines) { return false; } if (!PaintUtilities.equal(this.groupPaint, that.groupPaint)) { return false; } if (!this.groupStroke.equals(that.groupStroke)) { return false; } return super.equals(obj); } /** * Returns an icon. * * @param shape the shape. * @param fillPaint the fill paint. * @param outlinePaint the outline paint. * * @return The icon. */ private Icon getIcon(Shape shape, final Paint fillPaint, final Paint outlinePaint) { final int width = shape.getBounds().width; final int height = shape.getBounds().height; final GeneralPath path = new GeneralPath(shape); return new Icon() { @Override public void paintIcon(Component c, Graphics g, int x, int y) { Graphics2D g2 = (Graphics2D) g; path.transform(AffineTransform.getTranslateInstance(x, y)); if (fillPaint != null) { g2.setPaint(fillPaint); g2.fill(path); } if (outlinePaint != null) { g2.setPaint(outlinePaint); g2.draw(path); } path.transform(AffineTransform.getTranslateInstance(-x, -y)); } @Override public int getIconWidth() { return width; } @Override public int getIconHeight() { return height; } }; } /** * Returns an icon from a shape. * * @param shape the shape. * @param fill the fill flag. * @param outline the outline flag. * * @return The icon. */ private Icon getIcon(Shape shape, final boolean fill, final boolean outline) { final int width = shape.getBounds().width; final int height = shape.getBounds().height; final GeneralPath path = new GeneralPath(shape); return new Icon() { @Override public void paintIcon(Component c, Graphics g, int x, int y) { Graphics2D g2 = (Graphics2D) g; path.transform(AffineTransform.getTranslateInstance(x, y)); if (fill) { g2.fill(path); } if (outline) { g2.draw(path); } path.transform(AffineTransform.getTranslateInstance(-x, -y)); } @Override public int getIconWidth() { return width; } @Override public int getIconHeight() { return height; } }; } /** * Provides serialization support. * * @param stream the output stream. * * @throws IOException if there is an I/O error. */ private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); SerialUtilities.writeStroke(this.groupStroke, stream); SerialUtilities.writePaint(this.groupPaint, stream); } /** * Provides serialization support. * * @param stream the input stream. * * @throws IOException if there is an I/O error. * @throws ClassNotFoundException if there is a classpath problem. */ private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); this.groupStroke = SerialUtilities.readStroke(stream); this.groupPaint = SerialUtilities.readPaint(stream); this.minIcon = getIcon(new Arc2D.Double(-4, -4, 8, 8, 0, 360, Arc2D.OPEN), null, Color.BLACK); this.maxIcon = getIcon(new Arc2D.Double(-4, -4, 8, 8, 0, 360, Arc2D.OPEN), null, Color.BLACK); this.objectIcon = getIcon(new Line2D.Double(-4, 0, 4, 0), false, true); } }
19,737
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
ScatterRenderer.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/renderer/category/ScatterRenderer.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2013, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * -------------------- * ScatterRenderer.java * -------------------- * (C) Copyright 2007-2013, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): David Forslund; * Peter Kolb (patches 2497611, 2791407); * * Changes * ------- * 08-Oct-2007 : Version 1, based on patch 1780779 by David Forslund (DG); * 11-Oct-2007 : Renamed ScatterRenderer (DG); * 17-Jun-2008 : Apply legend shape, font and paint attributes (DG); * 14-Jan-2009 : Added support for seriesVisible flags (PK); * 16-May-2009 : Patch 2791407 - findRangeBounds() override (PK); * 15-Jun-2012 : Removed JCommon dependency (DG); * */ package org.jfree.chart.renderer.category; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.Shape; import java.awt.Stroke; import java.awt.geom.Line2D; import java.awt.geom.Rectangle2D; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.List; import org.jfree.chart.LegendItem; import org.jfree.chart.axis.CategoryAxis; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.entity.EntityCollection; import org.jfree.chart.util.BooleanList; import org.jfree.chart.util.ObjectUtilities; import org.jfree.chart.util.PublicCloneable; import org.jfree.chart.util.ShapeUtilities; import org.jfree.chart.event.RendererChangeEvent; import org.jfree.chart.plot.CategoryPlot; import org.jfree.chart.plot.PlotOrientation; import org.jfree.data.Range; import org.jfree.data.category.CategoryDataset; import org.jfree.data.statistics.MultiValueCategoryDataset; /** * A renderer that handles the multiple values from a * {@link MultiValueCategoryDataset} by plotting a shape for each value for * each given item in the dataset. The example shown here is generated by * the <code>ScatterRendererDemo1.java</code> program included in the * JFreeChart Demo Collection: * <br><br> * <img src="../../../../../images/ScatterRendererSample.png" * alt="ScatterRendererSample.png" /> * * @since 1.0.7 */ public class ScatterRenderer extends AbstractCategoryItemRenderer implements Cloneable, PublicCloneable, Serializable { /** * A table of flags that control (per series) whether or not shapes are * filled. */ private BooleanList seriesShapesFilled; /** * The default value returned by the getShapeFilled() method. */ private boolean baseShapesFilled; /** * A flag that controls whether the fill paint is used for filling * shapes. */ private boolean useFillPaint; /** * A flag that controls whether outlines are drawn for shapes. */ private boolean drawOutlines; /** * A flag that controls whether the outline paint is used for drawing shape * outlines - if not, the regular series paint is used. */ private boolean useOutlinePaint; /** * A flag that controls whether or not the x-position for each item is * offset within the category according to the series. */ private boolean useSeriesOffset; /** * The item margin used for series offsetting - this allows the positioning * to match the bar positions of the {@link BarRenderer} class. */ private double itemMargin; /** * Constructs a new renderer. */ public ScatterRenderer() { this.seriesShapesFilled = new BooleanList(); this.baseShapesFilled = true; this.useFillPaint = false; this.drawOutlines = false; this.useOutlinePaint = false; this.useSeriesOffset = true; this.itemMargin = 0.20; } /** * Returns the flag that controls whether or not the x-position for each * data item is offset within the category according to the series. * * @return A boolean. * * @see #setUseSeriesOffset(boolean) */ public boolean getUseSeriesOffset() { return this.useSeriesOffset; } /** * Sets the flag that controls whether or not the x-position for each * data item is offset within its category according to the series, and * sends a {@link RendererChangeEvent} to all registered listeners. * * @param offset the offset. * * @see #getUseSeriesOffset() */ public void setUseSeriesOffset(boolean offset) { this.useSeriesOffset = offset; fireChangeEvent(); } /** * Returns the item margin, which is the gap between items within a * category (expressed as a percentage of the overall category width). * This can be used to match the offset alignment with the bars drawn by * a {@link BarRenderer}). * * @return The item margin. * * @see #setItemMargin(double) * @see #getUseSeriesOffset() */ public double getItemMargin() { return this.itemMargin; } /** * Sets the item margin, which is the gap between items within a category * (expressed as a percentage of the overall category width), and sends * a {@link RendererChangeEvent} to all registered listeners. * * @param margin the margin (0.0 <= margin < 1.0). * * @see #getItemMargin() * @see #getUseSeriesOffset() */ public void setItemMargin(double margin) { if (margin < 0.0 || margin >= 1.0) { throw new IllegalArgumentException("Requires 0.0 <= margin < 1.0."); } this.itemMargin = margin; fireChangeEvent(); } /** * Returns <code>true</code> if outlines should be drawn for shapes, and * <code>false</code> otherwise. * * @return A boolean. * * @see #setDrawOutlines(boolean) */ public boolean getDrawOutlines() { return this.drawOutlines; } /** * Sets the flag that controls whether outlines are drawn for * shapes, and sends a {@link RendererChangeEvent} to all registered * listeners. * <p/> * In some cases, shapes look better if they do NOT have an outline, but * this flag allows you to set your own preference. * * @param flag the flag. * * @see #getDrawOutlines() */ public void setDrawOutlines(boolean flag) { this.drawOutlines = flag; fireChangeEvent(); } /** * Returns the flag that controls whether the outline paint is used for * shape outlines. If not, the regular series paint is used. * * @return A boolean. * * @see #setUseOutlinePaint(boolean) */ public boolean getUseOutlinePaint() { return this.useOutlinePaint; } /** * Sets the flag that controls whether the outline paint is used for shape * outlines, and sends a {@link RendererChangeEvent} to all registered * listeners. * * @param use the flag. * * @see #getUseOutlinePaint() */ public void setUseOutlinePaint(boolean use) { this.useOutlinePaint = use; fireChangeEvent(); } // SHAPES FILLED /** * Returns the flag used to control whether or not the shape for an item * is filled. The default implementation passes control to the * <code>getSeriesShapesFilled</code> method. You can override this method * if you require different behaviour. * * @param series the series index (zero-based). * @param item the item index (zero-based). * @return A boolean. */ public boolean getItemShapeFilled(int series, int item) { return getSeriesShapesFilled(series); } /** * Returns the flag used to control whether or not the shapes for a series * are filled. * * @param series the series index (zero-based). * @return A boolean. */ public boolean getSeriesShapesFilled(int series) { Boolean flag = this.seriesShapesFilled.getBoolean(series); if (flag != null) { return flag; } else { return this.baseShapesFilled; } } /** * Sets the 'shapes filled' flag for a series and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param series the series index (zero-based). * @param filled the flag. */ public void setSeriesShapesFilled(int series, Boolean filled) { this.seriesShapesFilled.setBoolean(series, filled); fireChangeEvent(); } /** * Sets the 'shapes filled' flag for a series and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param series the series index (zero-based). * @param filled the flag. */ public void setSeriesShapesFilled(int series, boolean filled) { this.seriesShapesFilled.setBoolean(series, filled); fireChangeEvent(); } /** * Returns the base 'shape filled' attribute. * * @return The base flag. */ public boolean getBaseShapesFilled() { return this.baseShapesFilled; } /** * Sets the base 'shapes filled' flag and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param flag the flag. */ public void setBaseShapesFilled(boolean flag) { this.baseShapesFilled = flag; fireChangeEvent(); } /** * Returns <code>true</code> if the renderer should use the fill paint * setting to fill shapes, and <code>false</code> if it should just * use the regular paint. * * @return A boolean. */ public boolean getUseFillPaint() { return this.useFillPaint; } /** * Sets the flag that controls whether the fill paint is used to fill * shapes, and sends a {@link RendererChangeEvent} to all * registered listeners. * * @param flag the flag. */ public void setUseFillPaint(boolean flag) { this.useFillPaint = flag; fireChangeEvent(); } /** * Returns the range of values the renderer requires to display all the * items from the specified dataset. This takes into account the range * between the min/max values, possibly ignoring invisible series. * * @param dataset the dataset (<code>null</code> permitted). * * @return The range (or <code>null</code> if the dataset is * <code>null</code> or empty). */ @Override public Range findRangeBounds(CategoryDataset dataset) { return findRangeBounds(dataset, true); } /** * Draw a single data item. * * @param g2 the graphics device. * @param state the renderer state. * @param dataArea the area in which the data is drawn. * @param plot the plot. * @param domainAxis the domain axis. * @param rangeAxis the range axis. * @param dataset the dataset. * @param row the row index (zero-based). * @param column the column index (zero-based). * @param pass the pass index. */ @Override public void drawItem(Graphics2D g2, CategoryItemRendererState state, Rectangle2D dataArea, CategoryPlot plot, CategoryAxis domainAxis, ValueAxis rangeAxis, CategoryDataset dataset, int row, int column, int pass) { // do nothing if item is not visible if (!getItemVisible(row, column)) { return; } int visibleRow = state.getVisibleSeriesIndex(row); if (visibleRow < 0) { return; } int visibleRowCount = state.getVisibleSeriesCount(); PlotOrientation orientation = plot.getOrientation(); MultiValueCategoryDataset d = (MultiValueCategoryDataset) dataset; List<Number> values = d.getValues(row, column); if (values == null) { return; } for (Number n : values) { // current data point... double x1; if (this.useSeriesOffset) { x1 = domainAxis.getCategorySeriesMiddle(column, dataset.getColumnCount(), visibleRow, visibleRowCount, this.itemMargin, dataArea, plot.getDomainAxisEdge()); } else { x1 = domainAxis.getCategoryMiddle(column, getColumnCount(), dataArea, plot.getDomainAxisEdge()); } double value = n.doubleValue(); double y1 = rangeAxis.valueToJava2D(value, dataArea, plot.getRangeAxisEdge()); Shape shape = getItemShape(row, column); if (orientation == PlotOrientation.HORIZONTAL) { shape = ShapeUtilities.createTranslatedShape(shape, y1, x1); } else if (orientation == PlotOrientation.VERTICAL) { shape = ShapeUtilities.createTranslatedShape(shape, x1, y1); } if (getItemShapeFilled(row, column)) { if (this.useFillPaint) { g2.setPaint(getItemFillPaint(row, column)); } else { g2.setPaint(getItemPaint(row, column)); } g2.fill(shape); } if (this.drawOutlines) { if (this.useOutlinePaint) { g2.setPaint(getItemOutlinePaint(row, column)); } else { g2.setPaint(getItemPaint(row, column)); } g2.setStroke(getItemOutlineStroke(row, column)); g2.draw(shape); } // collecting the entity info if (state != null) { EntityCollection entities = state.getEntityCollection(); if (orientation == PlotOrientation.HORIZONTAL) { addEntity(entities, shape, dataset, row, column, y1, x1); } else { addEntity(entities, shape, dataset, row, column, x1, y1); } } } } /** * Returns a legend item for a series. * * @param datasetIndex the dataset index (zero-based). * @param series the series index (zero-based). * * @return The legend item. */ @Override public LegendItem getLegendItem(int datasetIndex, int series) { CategoryPlot cp = getPlot(); if (cp == null) { return null; } if (isSeriesVisible(series) && isSeriesVisibleInLegend(series)) { CategoryDataset dataset = cp.getDataset(datasetIndex); String label = getLegendItemLabelGenerator().generateLabel( dataset, series); String description = label; String toolTipText = null; if (getLegendItemToolTipGenerator() != null) { toolTipText = getLegendItemToolTipGenerator().generateLabel( dataset, series); } String urlText = null; if (getLegendItemURLGenerator() != null) { urlText = getLegendItemURLGenerator().generateLabel( dataset, series); } Shape shape = lookupLegendShape(series); Paint paint = lookupSeriesPaint(series); Paint fillPaint = (this.useFillPaint ? getItemFillPaint(series, 0) : paint); boolean shapeOutlineVisible = this.drawOutlines; Paint outlinePaint = (this.useOutlinePaint ? getItemOutlinePaint(series, 0) : paint); Stroke outlineStroke = lookupSeriesOutlineStroke(series); LegendItem result = new LegendItem(label, description, toolTipText, urlText, true, shape, getItemShapeFilled(series, 0), fillPaint, shapeOutlineVisible, outlinePaint, outlineStroke, false, new Line2D.Double(-7.0, 0.0, 7.0, 0.0), getItemStroke(series, 0), getItemPaint(series, 0)); result.setLabelFont(lookupLegendTextFont(series)); Paint labelPaint = lookupLegendTextPaint(series); if (labelPaint != null) { result.setLabelPaint(labelPaint); } result.setDataset(dataset); result.setDatasetIndex(datasetIndex); result.setSeriesKey(dataset.getRowKey(series)); result.setSeriesIndex(series); return result; } return null; } /** * Tests this renderer for equality with an arbitrary object. * * @param obj the object (<code>null</code> permitted). * @return A boolean. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof ScatterRenderer)) { return false; } ScatterRenderer that = (ScatterRenderer) obj; if (!ObjectUtilities.equal(this.seriesShapesFilled, that.seriesShapesFilled)) { return false; } if (this.baseShapesFilled != that.baseShapesFilled) { return false; } if (this.useFillPaint != that.useFillPaint) { return false; } if (this.drawOutlines != that.drawOutlines) { return false; } if (this.useOutlinePaint != that.useOutlinePaint) { return false; } if (this.useSeriesOffset != that.useSeriesOffset) { return false; } if (this.itemMargin != that.itemMargin) { return false; } return super.equals(obj); } /** * Returns an independent copy of the renderer. * * @return A clone. * * @throws CloneNotSupportedException should not happen. */ @Override public Object clone() throws CloneNotSupportedException { ScatterRenderer clone = (ScatterRenderer) super.clone(); clone.seriesShapesFilled = (BooleanList) this.seriesShapesFilled.clone(); return clone; } /** * Provides serialization support. * * @param stream the output stream. * @throws java.io.IOException if there is an I/O error. */ private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); } /** * Provides serialization support. * * @param stream the input stream. * @throws java.io.IOException if there is an I/O error. * @throws ClassNotFoundException if there is a classpath problem. */ private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); } }
19,984
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
BarPainter.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/renderer/category/BarPainter.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * --------------- * BarPainter.java * --------------- * (C) Copyright 2008-2012, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes: * -------- * 19-Jun-2008 : Version 1 (DG); * 17-Jun-2012 : Removed JCommon dependencies (DG); * */ package org.jfree.chart.renderer.category; import java.awt.Graphics2D; import java.awt.geom.RectangularShape; import org.jfree.chart.ui.RectangleEdge; /** * The interface for plugin painter for the {@link BarRenderer} class. When * developing a class that implements this interface, bear in mind the * following: * <ul> * <li>the <code>equals(Object)</code> method should be overridden;</li> * <li>instances of the class should be immutable OR implement the * <code>PublicCloneable</code> interface, so that a renderer using the * painter can be cloned reliably; * <li>the class should be <code>Serializable</code>, otherwise chart * serialization will not be supported.</li> * </ul> * * @since 1.0.11 */ public interface BarPainter { /** * Paints a single bar on behalf of a renderer. * * @param g2 the graphics target. * @param renderer the renderer. * @param row the row index for the item. * @param column the column index for the item. * @param bar the bounds for the bar. * @param base the base of the bar. */ public void paintBar(Graphics2D g2, BarRenderer renderer, int row, int column, RectangularShape bar, RectangleEdge base); /** * Paints the shadow for a single bar on behalf of a renderer. * * @param g2 the graphics target. * @param renderer the renderer. * @param row the row index for the item. * @param column the column index for the item. * @param bar the bounds for the bar. * @param base the base of the bar. * @param pegShadow peg the shadow to the base of the bar? */ public void paintBarShadow(Graphics2D g2, BarRenderer renderer, int row, int column, RectangularShape bar, RectangleEdge base, boolean pegShadow); }
3,384
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
CategoryItemRenderer.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/renderer/category/CategoryItemRenderer.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ------------------------- * CategoryItemRenderer.java * ------------------------- * * (C) Copyright 2001-2012, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): Mark Watson (www.markwatson.com); * * Changes: * For history prior to the release of JFreeChart 1.0.0 in December 2005, * please refer to the source files in the JFreeChart 1.0.x release. * * ------------- JFREECHART 1.0.x --------------------------------------------- * 20-Feb-2007 : Updated API docs (DG); * 19-Apr-2007 : Deprecated seriesVisible and seriesVisibleInLegend flags (DG); * 20-Apr-2007 : Deprecated paint, fillPaint, outlinePaint, stroke, * outlineStroke, shape, itemLabelsVisible, itemLabelFont, * itemLabelPaint, positiveItemLabelPosition, * negativeItemLabelPosition and createEntities override * fields (DG); * 26-Jun-2008 : Added new method required for crosshair support - THIS CHANGES * THE API as of version 1.0.11 (DG); * 17-Jun-2012 : Removed JCommon dependencies (DG); * * ------------- JFREECHART Future State Edition (1.2.0?) --------------------- * < under development > * */ package org.jfree.chart.renderer.category; import java.awt.Graphics2D; import java.awt.geom.Rectangle2D; import org.jfree.chart.axis.CategoryAxis; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.ui.RectangleEdge; import org.jfree.chart.event.RendererChangeEvent; import org.jfree.chart.labels.CategoryItemLabelGenerator; import org.jfree.chart.labels.CategoryToolTipGenerator; import org.jfree.chart.plot.CategoryMarker; import org.jfree.chart.plot.CategoryPlot; import org.jfree.chart.plot.Marker; import org.jfree.chart.plot.PlotRenderingInfo; import org.jfree.chart.renderer.Renderer; import org.jfree.chart.urls.CategoryURLGenerator; import org.jfree.data.Range; import org.jfree.data.category.CategoryDataset; /** * A plug-in object that is used by the {@link CategoryPlot} class to display * individual data items from a {@link CategoryDataset}. * <p> * This interface defines the methods that must be provided by all renderers. * If you are implementing a custom renderer, you should consider extending the * {@link AbstractCategoryItemRenderer} class. * <p> * Most renderer attributes are defined using a "three layer" approach. When * looking up an attribute (for example, the outline paint) the renderer first * checks to see if there is a setting (in layer 0) that applies to ALL items * that the renderer draws. If there is, that setting is used, but if it is * <code>null</code> the renderer looks up the next layer, which contains * "per series" settings for the attribute (many attributes are defined on a * per series basis, so this is the layer that is most commonly used). If the * layer 1 setting is <code>null</code>, the renderer will look up the final * layer, which provides a default or "base" setting. Some attributes allow * the base setting to be <code>null</code>, while other attributes enforce * non-<code>null</code> values. */ public interface CategoryItemRenderer extends Renderer { /** * Returns the plot that the renderer has been assigned to (where * <code>null</code> indicates that the renderer is not currently assigned * to a plot). * * @return The plot (possibly <code>null</code>). * * @see #setPlot(CategoryPlot) */ public CategoryPlot getPlot(); /** * Sets the plot that the renderer has been assigned to. This method is * usually called by the {@link CategoryPlot}, in normal usage you * shouldn't need to call this method directly. * * @param plot the plot (<code>null</code> not permitted). * * @see #getPlot() */ public void setPlot(CategoryPlot plot); /** * Returns the range of values the renderer requires to display all the * items from the specified dataset. * * @param dataset the dataset (<code>null</code> permitted). * * @return The range (or <code>null</code> if the dataset is * <code>null</code> or empty). */ public Range findRangeBounds(CategoryDataset dataset); // FIXME: LegendItemGenerator? // TOOL TIP GENERATOR /** * Returns the tool tip generator that should be used for the specified * item. This method looks up the generator using the "three-layer" * approach outlined in the general description of this interface. * * @param row the row index (zero-based). * @param column the column index (zero-based). * * @return The generator (possibly <code>null</code>). */ public CategoryToolTipGenerator getToolTipGenerator(int row, int column); /** * Returns the tool tip generator for the specified series (a "layer 1" * generator). * * @param series the series index (zero-based). * * @return The tool tip generator (possibly <code>null</code>). * * @see #setSeriesToolTipGenerator(int, CategoryToolTipGenerator) */ public CategoryToolTipGenerator getSeriesToolTipGenerator(int series); /** * Sets the tool tip generator for a series and sends a * {@link org.jfree.chart.event.RendererChangeEvent} to all registered * listeners. * * @param series the series index (zero-based). * @param generator the generator (<code>null</code> permitted). * * @see #getSeriesToolTipGenerator(int) */ public void setSeriesToolTipGenerator(int series, CategoryToolTipGenerator generator); public void setSeriesToolTipGenerator(int series, CategoryToolTipGenerator generator, boolean notify); /** * Returns the default tool tip generator. * * @return The tool tip generator (possibly <code>null</code>). * * @see #setDefaultToolTipGenerator(CategoryToolTipGenerator) */ public CategoryToolTipGenerator getDefaultToolTipGenerator(); /** * Sets the default tool tip generator and sends a * {@link org.jfree.chart.event.RendererChangeEvent} to all registered * listeners. * * @param generator the generator (<code>null</code> permitted). * * @see #getDefaultToolTipGenerator() */ public void setDefaultToolTipGenerator(CategoryToolTipGenerator generator); public void setDefaultToolTipGenerator(CategoryToolTipGenerator generator, boolean notify); // ITEM LABEL GENERATOR /** * Returns the item label generator for the specified data item. * * @param series the series index (zero-based). * @param item the item index (zero-based). * * @return The generator (possibly <code>null</code>). */ public CategoryItemLabelGenerator getItemLabelGenerator(int series, int item); /** * Returns the item label generator for a series. * * @param series the series index (zero-based). * * @return The label generator (possibly <code>null</code>). * * @see #setSeriesItemLabelGenerator(int, CategoryItemLabelGenerator) */ public CategoryItemLabelGenerator getSeriesItemLabelGenerator(int series); /** * Sets the item label generator for a series and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param series the series index (zero-based). * @param generator the generator. * * @see #getSeriesItemLabelGenerator(int) */ public void setSeriesItemLabelGenerator(int series, CategoryItemLabelGenerator generator); public void setSeriesItemLabelGenerator(int series, CategoryItemLabelGenerator generator, boolean notify); /** * Returns the default item label generator. * * @return The generator (possibly <code>null</code>). * * @see #setDefaultItemLabelGenerator(CategoryItemLabelGenerator) */ public CategoryItemLabelGenerator getDefaultItemLabelGenerator(); /** * Sets the default item label generator and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param generator the generator (<code>null</code> permitted). * * @see #getDefaultItemLabelGenerator() */ public void setDefaultItemLabelGenerator(CategoryItemLabelGenerator generator); public void setDefaultItemLabelGenerator(CategoryItemLabelGenerator generator, boolean notify); // ITEM URL GENERATOR /** * Returns the URL generator for an item. * * @param series the series index (zero-based). * @param item the item index (zero-based). * * @return The item URL generator. */ public CategoryURLGenerator getItemURLGenerator(int series, int item); /** * Returns the item URL generator for a series. * * @param series the series index (zero-based). * * @return The URL generator. * * @see #setSeriesItemURLGenerator(int, CategoryURLGenerator) */ public CategoryURLGenerator getSeriesItemURLGenerator(int series); /** * Sets the item URL generator for a series. * * @param series the series index (zero-based). * @param generator the generator. * * @see #getSeriesItemURLGenerator(int) */ public void setSeriesItemURLGenerator(int series, CategoryURLGenerator generator); public void setSeriesItemURLGenerator(int series, CategoryURLGenerator generator, boolean notify); /** * Returns the default item URL generator. * * @return The item URL generator (possibly <code>null</code>). * * @see #setDefaultItemURLGenerator(CategoryURLGenerator) */ public CategoryURLGenerator getDefaultItemURLGenerator(); /** * Sets the default item URL generator and sends a {@link RendererChangeEvent} * to all registered listeners. * * @param generator the item URL generator (<code>null</code> permitted). * * @see #getDefaultItemURLGenerator() */ public void setDefaultItemURLGenerator(CategoryURLGenerator generator); public void setDefaultItemURLGenerator(CategoryURLGenerator generator, boolean notify); // FIXME: ANNOTATIONS //// DRAWING ////////////////////////////////////////////////////////////// /** * Initialises the renderer. This method will be called before the first * item is rendered, giving the renderer an opportunity to initialise any * state information it wants to maintain. The renderer can do nothing if * it chooses. * * @param g2 the graphics device. * @param dataArea the area inside the axes. * @param plot the plot. * @param rendererIndex the renderer index. * @param info collects chart rendering information for return to caller. * * @return A state object (maintains state information relevant to one * chart drawing). */ public CategoryItemRendererState initialise(Graphics2D g2, Rectangle2D dataArea, CategoryPlot plot, int rendererIndex, PlotRenderingInfo info); /** * Draws a background for the data area. * * @param g2 the graphics device. * @param plot the plot. * @param dataArea the data area. */ public void drawBackground(Graphics2D g2, CategoryPlot plot, Rectangle2D dataArea); /** * Draws an outline for the data area. * * @param g2 the graphics device. * @param plot the plot. * @param dataArea the data area. */ public void drawOutline(Graphics2D g2, CategoryPlot plot, Rectangle2D dataArea); /** * Draws a single data item. * * @param g2 the graphics device. * @param state state information for one chart. * @param dataArea the data plot area. * @param plot the plot. * @param domainAxis the domain axis. * @param rangeAxis the range axis. * @param dataset the data. * @param row the row index (zero-based). * @param column the column index (zero-based). * @param pass the pass index. */ public void drawItem(Graphics2D g2, CategoryItemRendererState state, Rectangle2D dataArea, CategoryPlot plot, CategoryAxis domainAxis, ValueAxis rangeAxis, CategoryDataset dataset, int row, int column, int pass); /** * Draws a grid line against the domain axis. * * @param g2 the graphics device. * @param plot the plot. * @param dataArea the area for plotting data (not yet adjusted for any * 3D effect). * @param value the value. * * @see #drawRangeGridline(Graphics2D, CategoryPlot, ValueAxis, * Rectangle2D, double) */ public void drawDomainGridline(Graphics2D g2, CategoryPlot plot, Rectangle2D dataArea, double value); /** * Draws a grid line against the range axis. * * @param g2 the graphics device. * @param plot the plot. * @param axis the value axis. * @param dataArea the area for plotting data (not yet adjusted for any * 3D effect). * @param value the value. * * @see #drawDomainGridline(Graphics2D, CategoryPlot, Rectangle2D, double) */ public void drawRangeGridline(Graphics2D g2, CategoryPlot plot, ValueAxis axis, Rectangle2D dataArea, double value); /** * Draws a line (or some other marker) to indicate a particular category on * the domain axis. * * @param g2 the graphics device. * @param plot the plot. * @param axis the category axis. * @param marker the marker. * @param dataArea the area for plotting data (not including 3D effect). * * @see #drawRangeMarker(Graphics2D, CategoryPlot, ValueAxis, Marker, * Rectangle2D) */ public void drawDomainMarker(Graphics2D g2, CategoryPlot plot, CategoryAxis axis, CategoryMarker marker, Rectangle2D dataArea); /** * Draws a line (or some other marker) to indicate a particular value on * the range axis. * * @param g2 the graphics device. * @param plot the plot. * @param axis the value axis. * @param marker the marker. * @param dataArea the area for plotting data (not including 3D effect). * * @see #drawDomainMarker(Graphics2D, CategoryPlot, CategoryAxis, * CategoryMarker, Rectangle2D) */ public void drawRangeMarker(Graphics2D g2, CategoryPlot plot, ValueAxis axis, Marker marker, Rectangle2D dataArea); /** * Returns the Java2D coordinate for the middle of the specified data item. * * @param rowKey the row key. * @param columnKey the column key. * @param dataset the dataset. * @param axis the axis. * @param area the data area. * @param edge the edge along which the axis lies. * * @return The Java2D coordinate for the middle of the item. * * @since 1.0.11 */ public double getItemMiddle(Comparable rowKey, Comparable columnKey, CategoryDataset dataset, CategoryAxis axis, Rectangle2D area, RectangleEdge edge); }
15,946
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
StatisticalBarRenderer.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/renderer/category/StatisticalBarRenderer.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * --------------------------- * StatisticalBarRenderer.java * --------------------------- * (C) Copyright 2002-2012, by Pascal Collet and Contributors. * * Original Author: Pascal Collet; * Contributor(s): David Gilbert (for Object Refinery Limited); * Christian W. Zuckschwerdt; * Peter Kolb (patches 2497611, 2791407); * Martin Hoeller; * * Changes * ------- * 21-Aug-2002 : Version 1, contributed by Pascal Collet (DG); * 01-Oct-2002 : Fixed errors reported by Checkstyle (DG); * 24-Oct-2002 : Changes to dataset interface (DG); * 05-Nov-2002 : Base dataset is now TableDataset not CategoryDataset (DG); * 05-Feb-2003 : Updates for new DefaultStatisticalCategoryDataset (DG); * 25-Mar-2003 : Implemented Serializable (DG); * 30-Jul-2003 : Modified entity constructor (CZ); * 06-Oct-2003 : Corrected typo in exception message (DG); * 05-Nov-2004 : Modified drawItem() signature (DG); * 15-Jun-2005 : Added errorIndicatorPaint attribute (DG); * ------------- JFREECHART 1.0.x --------------------------------------------- * 19-May-2006 : Added support for tooltips and URLs (DG); * 12-Jul-2006 : Added support for item labels (DG); * 02-Feb-2007 : Removed author tags all over JFreeChart sources (DG); * 28-Aug-2007 : Fixed NullPointerException - see bug 1779941 (DG); * 14-Nov-2007 : Added errorIndicatorStroke, and fixed bugs with drawBarOutline * and gradientPaintTransformer attributes being ignored (DG); * 14-Jan-2009 : Added support for seriesVisible flags (PK); * 16-May-2009 : Added findRangeBounds() override to take into account the * dataset interval (PK); * 28-Oct-2011 : Fixed problem with maximalBarWidth, bug #2810220 (MH); * 30-Oct-2011 : Additional change for bug #2810220 (DG); * 17-Jun-2012 : Removed JCommon dependencies (DG); * */ package org.jfree.chart.renderer.category; import java.awt.BasicStroke; import java.awt.Color; import java.awt.GradientPaint; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.Stroke; import java.awt.geom.Line2D; import java.awt.geom.Rectangle2D; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import org.jfree.chart.axis.CategoryAxis; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.ui.GradientPaintTransformer; import org.jfree.chart.ui.RectangleEdge; import org.jfree.chart.util.ObjectUtilities; import org.jfree.chart.util.PaintUtilities; import org.jfree.chart.util.PublicCloneable; import org.jfree.chart.entity.EntityCollection; import org.jfree.chart.event.RendererChangeEvent; import org.jfree.chart.labels.CategoryItemLabelGenerator; import org.jfree.chart.plot.CategoryPlot; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.util.SerialUtilities; import org.jfree.data.Range; import org.jfree.data.category.CategoryDataset; import org.jfree.data.statistics.StatisticalCategoryDataset; /** * A renderer that handles the drawing a bar plot where * each bar has a mean value and a standard deviation line. The example shown * here is generated by the <code>StatisticalBarChartDemo1.java</code> program * included in the JFreeChart Demo Collection: * <br><br> * <img src="../../../../../images/StatisticalBarRendererSample.png" * alt="StatisticalBarRendererSample.png" /> */ public class StatisticalBarRenderer extends BarRenderer implements CategoryItemRenderer, Cloneable, PublicCloneable, Serializable { /** For serialization. */ private static final long serialVersionUID = -4986038395414039117L; /** The paint used to show the error indicator. */ private transient Paint errorIndicatorPaint; /** * The stroke used to draw the error indicators. * * @since 1.0.8 */ private transient Stroke errorIndicatorStroke; /** * Default constructor. */ public StatisticalBarRenderer() { super(); this.errorIndicatorPaint = Color.GRAY; this.errorIndicatorStroke = new BasicStroke(1.0f); } /** * Returns the paint used for the error indicators. * * @return The paint used for the error indicators (possibly * <code>null</code>). * * @see #setErrorIndicatorPaint(Paint) */ public Paint getErrorIndicatorPaint() { return this.errorIndicatorPaint; } /** * Sets the paint used for the error indicators (if <code>null</code>, * the item outline paint is used instead) and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param paint the paint (<code>null</code> permitted). * * @see #getErrorIndicatorPaint() */ public void setErrorIndicatorPaint(Paint paint) { this.errorIndicatorPaint = paint; fireChangeEvent(); } /** * Returns the stroke used to draw the error indicators. If this is * <code>null</code>, the renderer will use the item outline stroke). * * @return The stroke (possibly <code>null</code>). * * @see #setErrorIndicatorStroke(Stroke) * * @since 1.0.8 */ public Stroke getErrorIndicatorStroke() { return this.errorIndicatorStroke; } /** * Sets the stroke used to draw the error indicators, and sends a * {@link RendererChangeEvent} to all registered listeners. If you set * this to <code>null</code>, the renderer will use the item outline * stroke. * * @param stroke the stroke (<code>null</code> permitted). * * @see #getErrorIndicatorStroke() * * @since 1.0.8 */ public void setErrorIndicatorStroke(Stroke stroke) { this.errorIndicatorStroke = stroke; fireChangeEvent(); } /** * Returns the range of values the renderer requires to display all the * items from the specified dataset. This takes into account the range * between the min/max values, possibly ignoring invisible series. * * @param dataset the dataset (<code>null</code> permitted). * * @return The range (or <code>null</code> if the dataset is * <code>null</code> or empty). */ @Override public Range findRangeBounds(CategoryDataset dataset) { return findRangeBounds(dataset, true); } /** * Draws the bar with its standard deviation line range for a single * (series, category) data item. * * @param g2 the graphics device. * @param state the renderer state. * @param dataArea the data area. * @param plot the plot. * @param domainAxis the domain axis. * @param rangeAxis the range axis. * @param data the data. * @param row the row index (zero-based). * @param column the column index (zero-based). * @param pass the pass index. */ @Override public void drawItem(Graphics2D g2, CategoryItemRendererState state, Rectangle2D dataArea, CategoryPlot plot, CategoryAxis domainAxis, ValueAxis rangeAxis, CategoryDataset data, int row, int column, int pass) { int visibleRow = state.getVisibleSeriesIndex(row); if (visibleRow < 0) { return; } // defensive check if (!(data instanceof StatisticalCategoryDataset)) { throw new IllegalArgumentException( "Requires StatisticalCategoryDataset."); } StatisticalCategoryDataset statData = (StatisticalCategoryDataset) data; PlotOrientation orientation = plot.getOrientation(); if (orientation == PlotOrientation.HORIZONTAL) { drawHorizontalItem(g2, state, dataArea, plot, domainAxis, rangeAxis, statData, visibleRow, row, column); } else if (orientation == PlotOrientation.VERTICAL) { drawVerticalItem(g2, state, dataArea, plot, domainAxis, rangeAxis, statData, visibleRow, row, column); } } /** * Draws an item for a plot with a horizontal orientation. * * @param g2 the graphics device. * @param state the renderer state. * @param dataArea the data area. * @param plot the plot. * @param domainAxis the domain axis. * @param rangeAxis the range axis. * @param dataset the data. * @param visibleRow the visible row index. * @param row the row index (zero-based). * @param column the column index (zero-based). */ protected void drawHorizontalItem(Graphics2D g2, CategoryItemRendererState state, Rectangle2D dataArea, CategoryPlot plot, CategoryAxis domainAxis, ValueAxis rangeAxis, StatisticalCategoryDataset dataset, int visibleRow, int row, int column) { // BAR Y double rectY = calculateBarW0(plot, PlotOrientation.HORIZONTAL, dataArea, domainAxis, state, visibleRow, column); // BAR X Number meanValue = dataset.getMeanValue(row, column); if (meanValue == null) { return; } double value = meanValue.doubleValue(); double base = 0.0; double lclip = getLowerClip(); double uclip = getUpperClip(); if (uclip <= 0.0) { // cases 1, 2, 3 and 4 if (value >= uclip) { return; // bar is not visible } base = uclip; if (value <= lclip) { value = lclip; } } else if (lclip <= 0.0) { // cases 5, 6, 7 and 8 if (value >= uclip) { value = uclip; } else { if (value <= lclip) { value = lclip; } } } else { // cases 9, 10, 11 and 12 if (value <= lclip) { return; // bar is not visible } base = getLowerClip(); if (value >= uclip) { value = uclip; } } RectangleEdge yAxisLocation = plot.getRangeAxisEdge(); double transY1 = rangeAxis.valueToJava2D(base, dataArea, yAxisLocation); double transY2 = rangeAxis.valueToJava2D(value, dataArea, yAxisLocation); double rectX = Math.min(transY2, transY1); double rectHeight = state.getBarWidth(); double rectWidth = Math.abs(transY2 - transY1); Rectangle2D bar = new Rectangle2D.Double(rectX, rectY, rectWidth, rectHeight); Paint itemPaint = getItemPaint(row, column); GradientPaintTransformer t = getGradientPaintTransformer(); if (t != null && itemPaint instanceof GradientPaint) { itemPaint = t.transform((GradientPaint) itemPaint, bar); } g2.setPaint(itemPaint); g2.fill(bar); // draw the outline... if (isDrawBarOutline() && state.getBarWidth() > BAR_OUTLINE_WIDTH_THRESHOLD) { Stroke stroke = getItemOutlineStroke(row, column); Paint paint = getItemOutlinePaint(row, column); if (stroke != null && paint != null) { g2.setStroke(stroke); g2.setPaint(paint); g2.draw(bar); } } // standard deviation lines Number n = dataset.getStdDevValue(row, column); if (n != null) { double valueDelta = n.doubleValue(); double highVal = rangeAxis.valueToJava2D(meanValue.doubleValue() + valueDelta, dataArea, yAxisLocation); double lowVal = rangeAxis.valueToJava2D(meanValue.doubleValue() - valueDelta, dataArea, yAxisLocation); if (this.errorIndicatorPaint != null) { g2.setPaint(this.errorIndicatorPaint); } else { g2.setPaint(getItemOutlinePaint(row, column)); } if (this.errorIndicatorStroke != null) { g2.setStroke(this.errorIndicatorStroke); } else { g2.setStroke(getItemOutlineStroke(row, column)); } Line2D line = null; line = new Line2D.Double(lowVal, rectY + rectHeight / 2.0d, highVal, rectY + rectHeight / 2.0d); g2.draw(line); line = new Line2D.Double(highVal, rectY + rectHeight * 0.25, highVal, rectY + rectHeight * 0.75); g2.draw(line); line = new Line2D.Double(lowVal, rectY + rectHeight * 0.25, lowVal, rectY + rectHeight * 0.75); g2.draw(line); } CategoryItemLabelGenerator generator = getItemLabelGenerator(row, column); if (generator != null && isItemLabelVisible(row, column)) { drawItemLabel(g2, dataset, row, column, plot, generator, bar, (value < 0.0)); } // add an item entity, if this information is being collected EntityCollection entities = state.getEntityCollection(); if (entities != null) { addItemEntity(entities, dataset, row, column, bar); } } /** * Draws an item for a plot with a vertical orientation. * * @param g2 the graphics device. * @param state the renderer state. * @param dataArea the data area. * @param plot the plot. * @param domainAxis the domain axis. * @param rangeAxis the range axis. * @param dataset the data. * @param visibleRow the visible row index. * @param row the row index (zero-based). * @param column the column index (zero-based). */ protected void drawVerticalItem(Graphics2D g2, CategoryItemRendererState state, Rectangle2D dataArea, CategoryPlot plot, CategoryAxis domainAxis, ValueAxis rangeAxis, StatisticalCategoryDataset dataset, int visibleRow, int row, int column) { // BAR X double rectX = calculateBarW0(plot, PlotOrientation.VERTICAL, dataArea, domainAxis, state, visibleRow, column); // BAR Y Number meanValue = dataset.getMeanValue(row, column); if (meanValue == null) { return; } double value = meanValue.doubleValue(); double base = 0.0; double lclip = getLowerClip(); double uclip = getUpperClip(); if (uclip <= 0.0) { // cases 1, 2, 3 and 4 if (value >= uclip) { return; // bar is not visible } base = uclip; if (value <= lclip) { value = lclip; } } else if (lclip <= 0.0) { // cases 5, 6, 7 and 8 if (value >= uclip) { value = uclip; } else { if (value <= lclip) { value = lclip; } } } else { // cases 9, 10, 11 and 12 if (value <= lclip) { return; // bar is not visible } base = getLowerClip(); if (value >= uclip) { value = uclip; } } RectangleEdge yAxisLocation = plot.getRangeAxisEdge(); double transY1 = rangeAxis.valueToJava2D(base, dataArea, yAxisLocation); double transY2 = rangeAxis.valueToJava2D(value, dataArea, yAxisLocation); double rectY = Math.min(transY2, transY1); double rectWidth = state.getBarWidth(); double rectHeight = Math.abs(transY2 - transY1); Rectangle2D bar = new Rectangle2D.Double(rectX, rectY, rectWidth, rectHeight); Paint itemPaint = getItemPaint(row, column); GradientPaintTransformer t = getGradientPaintTransformer(); if (t != null && itemPaint instanceof GradientPaint) { itemPaint = t.transform((GradientPaint) itemPaint, bar); } g2.setPaint(itemPaint); g2.fill(bar); // draw the outline... if (isDrawBarOutline() && state.getBarWidth() > BAR_OUTLINE_WIDTH_THRESHOLD) { Stroke stroke = getItemOutlineStroke(row, column); Paint paint = getItemOutlinePaint(row, column); if (stroke != null && paint != null) { g2.setStroke(stroke); g2.setPaint(paint); g2.draw(bar); } } // standard deviation lines Number n = dataset.getStdDevValue(row, column); if (n != null) { double valueDelta = n.doubleValue(); double highVal = rangeAxis.valueToJava2D(meanValue.doubleValue() + valueDelta, dataArea, yAxisLocation); double lowVal = rangeAxis.valueToJava2D(meanValue.doubleValue() - valueDelta, dataArea, yAxisLocation); if (this.errorIndicatorPaint != null) { g2.setPaint(this.errorIndicatorPaint); } else { g2.setPaint(getItemOutlinePaint(row, column)); } if (this.errorIndicatorStroke != null) { g2.setStroke(this.errorIndicatorStroke); } else { g2.setStroke(getItemOutlineStroke(row, column)); } Line2D line = null; line = new Line2D.Double(rectX + rectWidth / 2.0d, lowVal, rectX + rectWidth / 2.0d, highVal); g2.draw(line); line = new Line2D.Double(rectX + rectWidth / 2.0d - 5.0d, highVal, rectX + rectWidth / 2.0d + 5.0d, highVal); g2.draw(line); line = new Line2D.Double(rectX + rectWidth / 2.0d - 5.0d, lowVal, rectX + rectWidth / 2.0d + 5.0d, lowVal); g2.draw(line); } CategoryItemLabelGenerator generator = getItemLabelGenerator(row, column); if (generator != null && isItemLabelVisible(row, column)) { drawItemLabel(g2, dataset, row, column, plot, generator, bar, (value < 0.0)); } // add an item entity, if this information is being collected EntityCollection entities = state.getEntityCollection(); if (entities != null) { addItemEntity(entities, dataset, row, column, bar); } } /** * Tests this renderer for equality with an arbitrary object. * * @param obj the object (<code>null</code> permitted). * * @return A boolean. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof StatisticalBarRenderer)) { return false; } StatisticalBarRenderer that = (StatisticalBarRenderer) obj; if (!PaintUtilities.equal(this.errorIndicatorPaint, that.errorIndicatorPaint)) { return false; } if (!ObjectUtilities.equal(this.errorIndicatorStroke, that.errorIndicatorStroke)) { return false; } return super.equals(obj); } /** * Provides serialization support. * * @param stream the output stream. * * @throws IOException if there is an I/O error. */ private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); SerialUtilities.writePaint(this.errorIndicatorPaint, stream); SerialUtilities.writeStroke(this.errorIndicatorStroke, stream); } /** * Provides serialization support. * * @param stream the input stream. * * @throws IOException if there is an I/O error. * @throws ClassNotFoundException if there is a classpath problem. */ private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); this.errorIndicatorPaint = SerialUtilities.readPaint(stream); this.errorIndicatorStroke = SerialUtilities.readStroke(stream); } }
22,360
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
LineRenderer3D.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/renderer/category/LineRenderer3D.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ------------------- * LineRenderer3D.java * ------------------- * (C) Copyright 2004-2012, by Tobias Selb and Contributors. * * Original Author: Tobias Selb (http://www.uepselon.com); * Contributor(s): David Gilbert (for Object Refinery Limited); * Martin Hoeller (patch 3435374); * * Changes * ------- * 15-Oct-2004 : Version 1 (TS); * 05-Nov-2004 : Modified drawItem() signature (DG); * 11-Nov-2004 : Now uses ShapeUtilities class to translate shapes (DG); * 26-Jan-2005 : Update for changes in super class (DG); * 13-Apr-2005 : Check item visibility in drawItem() method (DG); * 09-Jun-2005 : Use addItemEntity() in drawItem() method (DG); * 10-Jun-2005 : Fixed capitalisation of setXOffset() and setYOffset() (DG); * ------------- JFREECHART 1.0.x --------------------------------------------- * 01-Dec-2006 : Fixed equals() and serialization (DG); * 17-Jan-2007 : Fixed bug in drawDomainGridline() method and added * argument check to setWallPaint() (DG); * 03-Apr-2007 : Fixed bugs in drawBackground() method (DG); * 16-Oct-2007 : Fixed bug in range marker drawing (DG); * 09-Nov-2011 : Fixed bug 3433405 - wrong item label position (MH); * 13-Nov-2011 : Fixed item labels overlapped by line - patch 3435374 (MH); * 17-Jun-2012 : Removed JCommon dependencies (DG); * */ package org.jfree.chart.renderer.category; import java.awt.AlphaComposite; import java.awt.Color; import java.awt.Composite; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Paint; import java.awt.Shape; import java.awt.Stroke; import java.awt.geom.GeneralPath; import java.awt.geom.Line2D; import java.awt.geom.Rectangle2D; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import org.jfree.chart.Effect3D; import org.jfree.chart.axis.CategoryAxis; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.util.PaintUtilities; import org.jfree.chart.util.ShapeUtilities; import org.jfree.chart.entity.EntityCollection; import org.jfree.chart.event.RendererChangeEvent; import org.jfree.chart.plot.CategoryPlot; import org.jfree.chart.plot.Marker; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.ValueMarker; import org.jfree.chart.util.SerialUtilities; import org.jfree.data.Range; import org.jfree.data.category.CategoryDataset; /** * A line renderer with a 3D effect. The example shown here is generated by * the <code>LineChart3DDemo1.java</code> program included in the JFreeChart * Demo Collection: * <br><br> * <img src="../../../../../images/LineRenderer3DSample.png" * alt="LineRenderer3DSample.png" /> */ public class LineRenderer3D extends LineAndShapeRenderer implements Effect3D, Serializable { /** For serialization. */ private static final long serialVersionUID = 5467931468380928736L; /** The default x-offset for the 3D effect. */ public static final double DEFAULT_X_OFFSET = 12.0; /** The default y-offset for the 3D effect. */ public static final double DEFAULT_Y_OFFSET = 8.0; /** The default wall paint. */ public static final Paint DEFAULT_WALL_PAINT = new Color(0xDD, 0xDD, 0xDD); /** The size of x-offset for the 3D effect. */ private double xOffset; /** The size of y-offset for the 3D effect. */ private double yOffset; /** The paint used to shade the left and lower 3D wall. */ private transient Paint wallPaint; /** * Creates a new renderer. */ public LineRenderer3D() { super(true, false); // create a line renderer only this.xOffset = DEFAULT_X_OFFSET; this.yOffset = DEFAULT_Y_OFFSET; this.wallPaint = DEFAULT_WALL_PAINT; } /** * Returns the x-offset for the 3D effect. * * @return The x-offset. * * @see #setXOffset(double) * @see #getYOffset() */ @Override public double getXOffset() { return this.xOffset; } /** * Returns the y-offset for the 3D effect. * * @return The y-offset. * * @see #setYOffset(double) * @see #getXOffset() */ @Override public double getYOffset() { return this.yOffset; } /** * Sets the x-offset and sends a {@link RendererChangeEvent} to all * registered listeners. * * @param xOffset the x-offset. * * @see #getXOffset() */ public void setXOffset(double xOffset) { this.xOffset = xOffset; fireChangeEvent(); } /** * Sets the y-offset and sends a {@link RendererChangeEvent} to all * registered listeners. * * @param yOffset the y-offset. * * @see #getYOffset() */ public void setYOffset(double yOffset) { this.yOffset = yOffset; fireChangeEvent(); } /** * Returns the paint used to highlight the left and bottom wall in the plot * background. * * @return The paint. * * @see #setWallPaint(Paint) */ public Paint getWallPaint() { return this.wallPaint; } /** * Sets the paint used to highlight the left and bottom walls in the plot * background, and sends a {@link RendererChangeEvent} to all * registered listeners. * * @param paint the paint (<code>null</code> not permitted). * * @see #getWallPaint() */ public void setWallPaint(Paint paint) { if (paint == null) { throw new IllegalArgumentException("Null 'paint' argument."); } this.wallPaint = paint; fireChangeEvent(); } /** * Draws the background for the plot. * * @param g2 the graphics device. * @param plot the plot. * @param dataArea the area inside the axes. */ @Override public void drawBackground(Graphics2D g2, CategoryPlot plot, Rectangle2D dataArea) { float x0 = (float) dataArea.getX(); float x1 = x0 + (float) Math.abs(this.xOffset); float x3 = (float) dataArea.getMaxX(); float x2 = x3 - (float) Math.abs(this.xOffset); float y0 = (float) dataArea.getMaxY(); float y1 = y0 - (float) Math.abs(this.yOffset); float y3 = (float) dataArea.getMinY(); float y2 = y3 + (float) Math.abs(this.yOffset); GeneralPath clip = new GeneralPath(); clip.moveTo(x0, y0); clip.lineTo(x0, y2); clip.lineTo(x1, y3); clip.lineTo(x3, y3); clip.lineTo(x3, y1); clip.lineTo(x2, y0); clip.closePath(); Composite originalComposite = g2.getComposite(); g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, plot.getBackgroundAlpha())); // fill background... Paint backgroundPaint = plot.getBackgroundPaint(); if (backgroundPaint != null) { g2.setPaint(backgroundPaint); g2.fill(clip); } GeneralPath leftWall = new GeneralPath(); leftWall.moveTo(x0, y0); leftWall.lineTo(x0, y2); leftWall.lineTo(x1, y3); leftWall.lineTo(x1, y1); leftWall.closePath(); g2.setPaint(getWallPaint()); g2.fill(leftWall); GeneralPath bottomWall = new GeneralPath(); bottomWall.moveTo(x0, y0); bottomWall.lineTo(x1, y1); bottomWall.lineTo(x3, y1); bottomWall.lineTo(x2, y0); bottomWall.closePath(); g2.setPaint(getWallPaint()); g2.fill(bottomWall); // highlight the background corners... g2.setPaint(Color.LIGHT_GRAY); Line2D corner = new Line2D.Double(x0, y0, x1, y1); g2.draw(corner); corner.setLine(x1, y1, x1, y3); g2.draw(corner); corner.setLine(x1, y1, x3, y1); g2.draw(corner); // draw background image, if there is one... Image backgroundImage = plot.getBackgroundImage(); if (backgroundImage != null) { Rectangle2D adjusted = new Rectangle2D.Double(dataArea.getX() + getXOffset(), dataArea.getY(), dataArea.getWidth() - getXOffset(), dataArea.getHeight() - getYOffset()); plot.drawBackgroundImage(g2, adjusted); } g2.setComposite(originalComposite); } /** * Draws the outline for the plot. * * @param g2 the graphics device. * @param plot the plot. * @param dataArea the area inside the axes. */ @Override public void drawOutline(Graphics2D g2, CategoryPlot plot, Rectangle2D dataArea) { float x0 = (float) dataArea.getX(); float x1 = x0 + (float) Math.abs(this.xOffset); float x3 = (float) dataArea.getMaxX(); float x2 = x3 - (float) Math.abs(this.xOffset); float y0 = (float) dataArea.getMaxY(); float y1 = y0 - (float) Math.abs(this.yOffset); float y3 = (float) dataArea.getMinY(); float y2 = y3 + (float) Math.abs(this.yOffset); GeneralPath clip = new GeneralPath(); clip.moveTo(x0, y0); clip.lineTo(x0, y2); clip.lineTo(x1, y3); clip.lineTo(x3, y3); clip.lineTo(x3, y1); clip.lineTo(x2, y0); clip.closePath(); // put an outline around the data area... Stroke outlineStroke = plot.getOutlineStroke(); Paint outlinePaint = plot.getOutlinePaint(); if ((outlineStroke != null) && (outlinePaint != null)) { g2.setStroke(outlineStroke); g2.setPaint(outlinePaint); g2.draw(clip); } } /** * Draws a grid line against the domain axis. * * @param g2 the graphics device. * @param plot the plot. * @param dataArea the area for plotting data (not yet adjusted for any * 3D effect). * @param value the Java2D value at which the grid line should be drawn. * */ @Override public void drawDomainGridline(Graphics2D g2, CategoryPlot plot, Rectangle2D dataArea, double value) { Line2D line1 = null; Line2D line2 = null; PlotOrientation orientation = plot.getOrientation(); if (orientation == PlotOrientation.HORIZONTAL) { double y0 = value; double y1 = value - getYOffset(); double x0 = dataArea.getMinX(); double x1 = x0 + getXOffset(); double x2 = dataArea.getMaxX(); line1 = new Line2D.Double(x0, y0, x1, y1); line2 = new Line2D.Double(x1, y1, x2, y1); } else if (orientation == PlotOrientation.VERTICAL) { double x0 = value; double x1 = value + getXOffset(); double y0 = dataArea.getMaxY(); double y1 = y0 - getYOffset(); double y2 = dataArea.getMinY(); line1 = new Line2D.Double(x0, y0, x1, y1); line2 = new Line2D.Double(x1, y1, x1, y2); } g2.setPaint(plot.getDomainGridlinePaint()); g2.setStroke(plot.getDomainGridlineStroke()); g2.draw(line1); g2.draw(line2); } /** * Draws a grid line against the range axis. * * @param g2 the graphics device. * @param plot the plot. * @param axis the value axis. * @param dataArea the area for plotting data (not yet adjusted for any * 3D effect). * @param value the value at which the grid line should be drawn. * */ @Override public void drawRangeGridline(Graphics2D g2, CategoryPlot plot, ValueAxis axis, Rectangle2D dataArea, double value) { Range range = axis.getRange(); if (!range.contains(value)) { return; } Rectangle2D adjusted = new Rectangle2D.Double(dataArea.getX(), dataArea.getY() + getYOffset(), dataArea.getWidth() - getXOffset(), dataArea.getHeight() - getYOffset()); Line2D line1 = null; Line2D line2 = null; PlotOrientation orientation = plot.getOrientation(); if (orientation == PlotOrientation.HORIZONTAL) { double x0 = axis.valueToJava2D(value, adjusted, plot.getRangeAxisEdge()); double x1 = x0 + getXOffset(); double y0 = dataArea.getMaxY(); double y1 = y0 - getYOffset(); double y2 = dataArea.getMinY(); line1 = new Line2D.Double(x0, y0, x1, y1); line2 = new Line2D.Double(x1, y1, x1, y2); } else if (orientation == PlotOrientation.VERTICAL) { double y0 = axis.valueToJava2D(value, adjusted, plot.getRangeAxisEdge()); double y1 = y0 - getYOffset(); double x0 = dataArea.getMinX(); double x1 = x0 + getXOffset(); double x2 = dataArea.getMaxX(); line1 = new Line2D.Double(x0, y0, x1, y1); line2 = new Line2D.Double(x1, y1, x2, y1); } g2.setPaint(plot.getRangeGridlinePaint()); g2.setStroke(plot.getRangeGridlineStroke()); g2.draw(line1); g2.draw(line2); } /** * Draws a range marker. * * @param g2 the graphics device. * @param plot the plot. * @param axis the value axis. * @param marker the marker. * @param dataArea the area for plotting data (not including 3D effect). */ @Override public void drawRangeMarker(Graphics2D g2, CategoryPlot plot, ValueAxis axis, Marker marker, Rectangle2D dataArea) { Rectangle2D adjusted = new Rectangle2D.Double(dataArea.getX(), dataArea.getY() + getYOffset(), dataArea.getWidth() - getXOffset(), dataArea.getHeight() - getYOffset()); if (marker instanceof ValueMarker) { ValueMarker vm = (ValueMarker) marker; double value = vm.getValue(); Range range = axis.getRange(); if (!range.contains(value)) { return; } GeneralPath path = null; PlotOrientation orientation = plot.getOrientation(); if (orientation == PlotOrientation.HORIZONTAL) { float x = (float) axis.valueToJava2D(value, adjusted, plot.getRangeAxisEdge()); float y = (float) adjusted.getMaxY(); path = new GeneralPath(); path.moveTo(x, y); path.lineTo((float) (x + getXOffset()), y - (float) getYOffset()); path.lineTo((float) (x + getXOffset()), (float) (adjusted.getMinY() - getYOffset())); path.lineTo(x, (float) adjusted.getMinY()); path.closePath(); } else if (orientation == PlotOrientation.VERTICAL) { float y = (float) axis.valueToJava2D(value, adjusted, plot.getRangeAxisEdge()); float x = (float) dataArea.getX(); path = new GeneralPath(); path.moveTo(x, y); path.lineTo(x + (float) this.xOffset, y - (float) this.yOffset); path.lineTo((float) (adjusted.getMaxX() + this.xOffset), y - (float) this.yOffset); path.lineTo((float) (adjusted.getMaxX()), y); path.closePath(); } g2.setPaint(marker.getPaint()); g2.fill(path); g2.setPaint(marker.getOutlinePaint()); g2.draw(path); } else { super.drawRangeMarker(g2, plot, axis, marker, adjusted); // TODO: draw the interval marker with a 3D effect } } /** * Draw a single data item. * * @param g2 the graphics device. * @param state the renderer state. * @param dataArea the area in which the data is drawn. * @param plot the plot. * @param domainAxis the domain axis. * @param rangeAxis the range axis. * @param dataset the dataset. * @param row the row index (zero-based). * @param column the column index (zero-based). * @param pass the pass index. */ @Override public void drawItem(Graphics2D g2, CategoryItemRendererState state, Rectangle2D dataArea, CategoryPlot plot, CategoryAxis domainAxis, ValueAxis rangeAxis, CategoryDataset dataset, int row, int column, int pass) { if (!getItemVisible(row, column)) { return; } // nothing is drawn for null... Number v = dataset.getValue(row, column); if (v == null) { return; } Rectangle2D adjusted = new Rectangle2D.Double(dataArea.getX(), dataArea.getY() + getYOffset(), dataArea.getWidth() - getXOffset(), dataArea.getHeight() - getYOffset()); PlotOrientation orientation = plot.getOrientation(); // current data point... double x1 = domainAxis.getCategoryMiddle(column, getColumnCount(), adjusted, plot.getDomainAxisEdge()); double value = v.doubleValue(); double y1 = rangeAxis.valueToJava2D(value, adjusted, plot.getRangeAxisEdge()); Shape shape = getItemShape(row, column); if (orientation == PlotOrientation.HORIZONTAL) { shape = ShapeUtilities.createTranslatedShape(shape, y1, x1); } else if (orientation == PlotOrientation.VERTICAL) { shape = ShapeUtilities.createTranslatedShape(shape, x1, y1); } if (pass == 0 && getItemLineVisible(row, column)) { if (column != 0) { Number previousValue = dataset.getValue(row, column - 1); if (previousValue != null) { // previous data point... double previous = previousValue.doubleValue(); double x0 = domainAxis.getCategoryMiddle(column - 1, getColumnCount(), adjusted, plot.getDomainAxisEdge()); double y0 = rangeAxis.valueToJava2D(previous, adjusted, plot.getRangeAxisEdge()); double x2 = x0 + getXOffset(); double y2 = y0 - getYOffset(); double x3 = x1 + getXOffset(); double y3 = y1 - getYOffset(); GeneralPath clip = new GeneralPath(); if (orientation == PlotOrientation.HORIZONTAL) { clip.moveTo((float) y0, (float) x0); clip.lineTo((float) y1, (float) x1); clip.lineTo((float) y3, (float) x3); clip.lineTo((float) y2, (float) x2); clip.lineTo((float) y0, (float) x0); clip.closePath(); } else if (orientation == PlotOrientation.VERTICAL) { clip.moveTo((float) x0, (float) y0); clip.lineTo((float) x1, (float) y1); clip.lineTo((float) x3, (float) y3); clip.lineTo((float) x2, (float) y2); clip.lineTo((float) x0, (float) y0); clip.closePath(); } g2.setPaint(getItemPaint(row, column)); g2.fill(clip); g2.setStroke(getItemOutlineStroke(row, column)); g2.setPaint(getItemOutlinePaint(row, column)); g2.draw(clip); } } } // draw the item label if there is one... if (pass == 1 && isItemLabelVisible(row, column)) { if (orientation == PlotOrientation.HORIZONTAL) { drawItemLabel(g2, orientation, dataset, row, column, y1, x1, (value < 0.0)); } else if (orientation == PlotOrientation.VERTICAL) { drawItemLabel(g2, orientation, dataset, row, column, x1, y1, (value < 0.0)); } } // add an item entity, if this information is being collected EntityCollection entities = state.getEntityCollection(); if (entities != null) { addItemEntity(entities, dataset, row, column, shape); } } /** * Checks this renderer for equality with an arbitrary object. * * @param obj the object (<code>null</code> permitted). * * @return A boolean. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof LineRenderer3D)) { return false; } LineRenderer3D that = (LineRenderer3D) obj; if (this.xOffset != that.xOffset) { return false; } if (this.yOffset != that.yOffset) { return false; } if (!PaintUtilities.equal(this.wallPaint, that.wallPaint)) { return false; } return super.equals(obj); } /** * Provides serialization support. * * @param stream the output stream. * * @throws IOException if there is an I/O error. */ private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); SerialUtilities.writePaint(this.wallPaint, stream); } /** * Provides serialization support. * * @param stream the input stream. * * @throws IOException if there is an I/O error. * @throws ClassNotFoundException if there is a classpath problem. */ private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); this.wallPaint = SerialUtilities.readPaint(stream); } }
23,941
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
LineAndShapeRenderer.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/renderer/category/LineAndShapeRenderer.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ------------------------- * LineAndShapeRenderer.java * ------------------------- * (C) Copyright 2001-2012, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): Mark Watson (www.markwatson.com); * Jeremy Bowman; * Richard Atkinson; * Christian W. Zuckschwerdt; * Peter Kolb (patch 2497611); * * Changes * ------- * 23-Oct-2001 : Version 1 (DG); * 15-Nov-2001 : Modified to allow for null data values (DG); * 16-Jan-2002 : Renamed HorizontalCategoryItemRenderer.java * --> CategoryItemRenderer.java (DG); * 05-Feb-2002 : Changed return type of the drawCategoryItem method from void * to Shape, as part of the tooltips implementation (DG); * 11-May-2002 : Support for value label drawing (JB); * 29-May-2002 : Now extends AbstractCategoryItemRenderer (DG); * 25-Jun-2002 : Removed redundant import (DG); * 05-Aug-2002 : Small modification to drawCategoryItem method to support URLs * for HTML image maps (RA); * 26-Sep-2002 : Fixed errors reported by Checkstyle (DG); * 11-Oct-2002 : Added new constructor to incorporate tool tip and URL * generators (DG); * 24-Oct-2002 : Amendments for changes in CategoryDataset interface and * CategoryToolTipGenerator interface (DG); * 05-Nov-2002 : Base dataset is now TableDataset not CategoryDataset (DG); * 06-Nov-2002 : Renamed drawCategoryItem() --> drawItem() and now using axis * for category spacing (DG); * 17-Jan-2003 : Moved plot classes to a separate package (DG); * 10-Apr-2003 : Changed CategoryDataset to KeyedValues2DDataset in drawItem() * method (DG); * 12-May-2003 : Modified to take into account the plot orientation (DG); * 29-Jul-2003 : Amended code that doesn't compile with JDK 1.2.2 (DG); * 30-Jul-2003 : Modified entity constructor (CZ); * 22-Sep-2003 : Fixed cloning (DG); * 10-Feb-2004 : Small change to drawItem() method to make cut-and-paste * override easier (DG); * 16-Jun-2004 : Fixed bug (id=972454) with label positioning on horizontal * charts (DG); * 15-Oct-2004 : Updated equals() method (DG); * 05-Nov-2004 : Modified drawItem() signature (DG); * 11-Nov-2004 : Now uses ShapeUtilities class to translate shapes (DG); * 27-Jan-2005 : Changed attribute names, modified constructor and removed * constants (DG); * 01-Feb-2005 : Removed unnecessary constants (DG); * 15-Mar-2005 : Fixed bug 1163897, concerning outlines for shapes (DG); * 13-Apr-2005 : Check flags that control series visibility (DG); * 20-Apr-2005 : Use generators for legend labels, tooltips and URLs (DG); * 09-Jun-2005 : Use addItemEntity() method (DG); * ------------- JFREECHART 1.0.x --------------------------------------------- * 25-May-2006 : Added check to drawItem() to detect when both the line and * the shape are not visible (DG); * 20-Apr-2007 : Updated getLegendItem() for renderer change (DG); * 17-May-2007 : Set datasetIndex and seriesIndex in getLegendItem() (DG); * 18-May-2007 : Set dataset and seriesKey for LegendItem (DG); * 24-Sep-2007 : Deprecated redundant fields/methods (DG); * 27-Sep-2007 : Added option to offset series x-position within category (DG); * 17-Jun-2008 : Apply legend shape, font and paint attributes (DG); * 26-Jun-2008 : Added crosshair support (DG); * 14-Jan-2009 : Added support for seriesVisible flags (PK); * 15-Jun-2012 : Remove JCommon dependency (DG); * */ package org.jfree.chart.renderer.category; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.Shape; import java.awt.Stroke; import java.awt.geom.Line2D; import java.awt.geom.Rectangle2D; import java.io.Serializable; import org.jfree.chart.LegendItem; import org.jfree.chart.axis.CategoryAxis; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.util.BooleanList; import org.jfree.chart.util.ObjectUtilities; import org.jfree.chart.util.PublicCloneable; import org.jfree.chart.util.ShapeUtilities; import org.jfree.chart.entity.EntityCollection; import org.jfree.chart.event.RendererChangeEvent; import org.jfree.chart.plot.CategoryPlot; import org.jfree.chart.plot.PlotOrientation; import org.jfree.data.category.CategoryDataset; /** * A renderer that draws shapes for each data item, and lines between data * items (for use with the {@link CategoryPlot} class). * The example shown here is generated by the <code>LineChartDemo1.java</code> * program included in the JFreeChart Demo Collection: * <br><br> * <img src="../../../../../images/LineAndShapeRendererSample.png" * alt="LineAndShapeRendererSample.png" /> */ public class LineAndShapeRenderer extends AbstractCategoryItemRenderer implements Cloneable, PublicCloneable, Serializable { /** For serialization. */ private static final long serialVersionUID = -197749519869226398L; /** * A table of flags that control (per series) whether or not lines are * visible. */ private BooleanList seriesLinesVisible; /** * A flag indicating whether or not lines are drawn between non-null * points. */ private boolean baseLinesVisible; /** * A table of flags that control (per series) whether or not shapes are * visible. */ private BooleanList seriesShapesVisible; /** The default value returned by the getShapeVisible() method. */ private boolean baseShapesVisible; /** * A table of flags that control (per series) whether or not shapes are * filled. */ private BooleanList seriesShapesFilled; /** The default value returned by the getShapeFilled() method. */ private boolean baseShapesFilled; /** * A flag that controls whether the fill paint is used for filling * shapes. */ private boolean useFillPaint; /** A flag that controls whether outlines are drawn for shapes. */ private boolean drawOutlines; /** * A flag that controls whether the outline paint is used for drawing shape * outlines - if not, the regular series paint is used. */ private boolean useOutlinePaint; /** * A flag that controls whether or not the x-position for each item is * offset within the category according to the series. * * @since 1.0.7 */ private boolean useSeriesOffset; /** * The item margin used for series offsetting - this allows the positioning * to match the bar positions of the {@link BarRenderer} class. * * @since 1.0.7 */ private double itemMargin; /** * Creates a renderer with both lines and shapes visible by default. */ public LineAndShapeRenderer() { this(true, true); } /** * Creates a new renderer with lines and/or shapes visible. * * @param lines draw lines? * @param shapes draw shapes? */ public LineAndShapeRenderer(boolean lines, boolean shapes) { super(); this.seriesLinesVisible = new BooleanList(); this.baseLinesVisible = lines; this.seriesShapesVisible = new BooleanList(); this.baseShapesVisible = shapes; this.seriesShapesFilled = new BooleanList(); this.baseShapesFilled = true; this.useFillPaint = false; this.drawOutlines = true; this.useOutlinePaint = false; this.useSeriesOffset = false; // preserves old behaviour this.itemMargin = 0.0; } // LINES VISIBLE /** * Returns the flag used to control whether or not the line for an item is * visible. * * @param series the series index (zero-based). * @param item the item index (zero-based). * * @return A boolean. */ public boolean getItemLineVisible(int series, int item) { Boolean flag = getSeriesLinesVisible(series); if (flag != null) { return flag; } else { return this.baseLinesVisible; } } /** * Returns the flag used to control whether or not the lines for a series * are visible. * * @param series the series index (zero-based). * * @return The flag (possibly <code>null</code>). * * @see #setSeriesLinesVisible(int, Boolean) */ public Boolean getSeriesLinesVisible(int series) { return this.seriesLinesVisible.getBoolean(series); } /** * Sets the 'lines visible' flag for a series and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param series the series index (zero-based). * @param flag the flag (<code>null</code> permitted). * * @see #getSeriesLinesVisible(int) */ public void setSeriesLinesVisible(int series, Boolean flag) { this.seriesLinesVisible.setBoolean(series, flag); fireChangeEvent(); } /** * Sets the 'lines visible' flag for a series and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param series the series index (zero-based). * @param visible the flag. * * @see #getSeriesLinesVisible(int) */ public void setSeriesLinesVisible(int series, boolean visible) { setSeriesLinesVisible(series, Boolean.valueOf(visible)); } /** * Returns the base 'lines visible' attribute. * * @return The base flag. * * @see #getBaseLinesVisible() */ public boolean getBaseLinesVisible() { return this.baseLinesVisible; } /** * Sets the base 'lines visible' flag and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param flag the flag. * * @see #getBaseLinesVisible() */ public void setBaseLinesVisible(boolean flag) { this.baseLinesVisible = flag; fireChangeEvent(); } // SHAPES VISIBLE /** * Returns the flag used to control whether or not the shape for an item is * visible. * * @param series the series index (zero-based). * @param item the item index (zero-based). * * @return A boolean. */ public boolean getItemShapeVisible(int series, int item) { Boolean flag = getSeriesShapesVisible(series); if (flag != null) { return flag; } else { return this.baseShapesVisible; } } /** * Returns the flag used to control whether or not the shapes for a series * are visible. * * @param series the series index (zero-based). * * @return A boolean. * * @see #setSeriesShapesVisible(int, Boolean) */ public Boolean getSeriesShapesVisible(int series) { return this.seriesShapesVisible.getBoolean(series); } /** * Sets the 'shapes visible' flag for a series and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param series the series index (zero-based). * @param visible the flag. * * @see #getSeriesShapesVisible(int) */ public void setSeriesShapesVisible(int series, boolean visible) { setSeriesShapesVisible(series, Boolean.valueOf(visible)); } /** * Sets the 'shapes visible' flag for a series and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param series the series index (zero-based). * @param flag the flag. * * @see #getSeriesShapesVisible(int) */ public void setSeriesShapesVisible(int series, Boolean flag) { this.seriesShapesVisible.setBoolean(series, flag); fireChangeEvent(); } /** * Returns the base 'shape visible' attribute. * * @return The base flag. * * @see #setBaseShapesVisible(boolean) */ public boolean getBaseShapesVisible() { return this.baseShapesVisible; } /** * Sets the base 'shapes visible' flag and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param flag the flag. * * @see #getBaseShapesVisible() */ public void setBaseShapesVisible(boolean flag) { this.baseShapesVisible = flag; fireChangeEvent(); } /** * Returns <code>true</code> if outlines should be drawn for shapes, and * <code>false</code> otherwise. * * @return A boolean. * * @see #setDrawOutlines(boolean) */ public boolean getDrawOutlines() { return this.drawOutlines; } /** * Sets the flag that controls whether outlines are drawn for * shapes, and sends a {@link RendererChangeEvent} to all registered * listeners. * <P> * In some cases, shapes look better if they do NOT have an outline, but * this flag allows you to set your own preference. * * @param flag the flag. * * @see #getDrawOutlines() */ public void setDrawOutlines(boolean flag) { this.drawOutlines = flag; fireChangeEvent(); } /** * Returns the flag that controls whether the outline paint is used for * shape outlines. If not, the regular series paint is used. * * @return A boolean. * * @see #setUseOutlinePaint(boolean) */ public boolean getUseOutlinePaint() { return this.useOutlinePaint; } /** * Sets the flag that controls whether the outline paint is used for shape * outlines, and sends a {@link RendererChangeEvent} to all registered * listeners. * * @param use the flag. * * @see #getUseOutlinePaint() */ public void setUseOutlinePaint(boolean use) { this.useOutlinePaint = use; fireChangeEvent(); } // SHAPES FILLED /** * Returns the flag used to control whether or not the shape for an item * is filled. The default implementation passes control to the * <code>getSeriesShapesFilled</code> method. You can override this method * if you require different behaviour. * * @param series the series index (zero-based). * @param item the item index (zero-based). * * @return A boolean. */ public boolean getItemShapeFilled(int series, int item) { return getSeriesShapesFilled(series); } /** * Returns the flag used to control whether or not the shapes for a series * are filled. * * @param series the series index (zero-based). * * @return A boolean. */ public boolean getSeriesShapesFilled(int series) { Boolean flag = this.seriesShapesFilled.getBoolean(series); if (flag != null) { return flag; } else { return this.baseShapesFilled; } } /** * Sets the 'shapes filled' flag for a series and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param series the series index (zero-based). * @param filled the flag. * * @see #getSeriesShapesFilled(int) */ public void setSeriesShapesFilled(int series, Boolean filled) { this.seriesShapesFilled.setBoolean(series, filled); fireChangeEvent(); } /** * Sets the 'shapes filled' flag for a series and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param series the series index (zero-based). * @param filled the flag. * * @see #getSeriesShapesFilled(int) */ public void setSeriesShapesFilled(int series, boolean filled) { // delegate setSeriesShapesFilled(series, Boolean.valueOf(filled)); } /** * Returns the base 'shape filled' attribute. * * @return The base flag. * * @see #setBaseShapesFilled(boolean) */ public boolean getBaseShapesFilled() { return this.baseShapesFilled; } /** * Sets the base 'shapes filled' flag and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param flag the flag. * * @see #getBaseShapesFilled() */ public void setBaseShapesFilled(boolean flag) { this.baseShapesFilled = flag; fireChangeEvent(); } /** * Returns <code>true</code> if the renderer should use the fill paint * setting to fill shapes, and <code>false</code> if it should just * use the regular paint. * * @return A boolean. * * @see #setUseFillPaint(boolean) */ public boolean getUseFillPaint() { return this.useFillPaint; } /** * Sets the flag that controls whether the fill paint is used to fill * shapes, and sends a {@link RendererChangeEvent} to all * registered listeners. * * @param flag the flag. * * @see #getUseFillPaint() */ public void setUseFillPaint(boolean flag) { this.useFillPaint = flag; fireChangeEvent(); } /** * Returns the flag that controls whether or not the x-position for each * data item is offset within the category according to the series. * * @return A boolean. * * @see #setUseSeriesOffset(boolean) * * @since 1.0.7 */ public boolean getUseSeriesOffset() { return this.useSeriesOffset; } /** * Sets the flag that controls whether or not the x-position for each * data item is offset within its category according to the series, and * sends a {@link RendererChangeEvent} to all registered listeners. * * @param offset the offset. * * @see #getUseSeriesOffset() * * @since 1.0.7 */ public void setUseSeriesOffset(boolean offset) { this.useSeriesOffset = offset; fireChangeEvent(); } /** * Returns the item margin, which is the gap between items within a * category (expressed as a percentage of the overall category width). * This can be used to match the offset alignment with the bars drawn by * a {@link BarRenderer}). * * @return The item margin. * * @see #setItemMargin(double) * @see #getUseSeriesOffset() * * @since 1.0.7 */ public double getItemMargin() { return this.itemMargin; } /** * Sets the item margin, which is the gap between items within a category * (expressed as a percentage of the overall category width), and sends * a {@link RendererChangeEvent} to all registered listeners. * * @param margin the margin (0.0 <= margin < 1.0). * * @see #getItemMargin() * @see #getUseSeriesOffset() * * @since 1.0.7 */ public void setItemMargin(double margin) { if (margin < 0.0 || margin >= 1.0) { throw new IllegalArgumentException("Requires 0.0 <= margin < 1.0."); } this.itemMargin = margin; fireChangeEvent(); } /** * Returns a legend item for a series. * * @param datasetIndex the dataset index (zero-based). * @param series the series index (zero-based). * * @return The legend item. */ @Override public LegendItem getLegendItem(int datasetIndex, int series) { CategoryPlot cp = getPlot(); if (cp == null) { return null; } if (isSeriesVisible(series) && isSeriesVisibleInLegend(series)) { CategoryDataset dataset = cp.getDataset(datasetIndex); String label = getLegendItemLabelGenerator().generateLabel( dataset, series); String description = label; String toolTipText = null; if (getLegendItemToolTipGenerator() != null) { toolTipText = getLegendItemToolTipGenerator().generateLabel( dataset, series); } String urlText = null; if (getLegendItemURLGenerator() != null) { urlText = getLegendItemURLGenerator().generateLabel( dataset, series); } Shape shape = lookupLegendShape(series); Paint paint = lookupSeriesPaint(series); Paint fillPaint = (this.useFillPaint ? getItemFillPaint(series, 0) : paint); boolean shapeOutlineVisible = this.drawOutlines; Paint outlinePaint = (this.useOutlinePaint ? getItemOutlinePaint(series, 0) : paint); Stroke outlineStroke = lookupSeriesOutlineStroke(series); boolean lineVisible = getItemLineVisible(series, 0); boolean shapeVisible = getItemShapeVisible(series, 0); LegendItem result = new LegendItem(label, description, toolTipText, urlText, shapeVisible, shape, getItemShapeFilled(series, 0), fillPaint, shapeOutlineVisible, outlinePaint, outlineStroke, lineVisible, new Line2D.Double(-7.0, 0.0, 7.0, 0.0), getItemStroke(series, 0), getItemPaint(series, 0)); result.setLabelFont(lookupLegendTextFont(series)); Paint labelPaint = lookupLegendTextPaint(series); if (labelPaint != null) { result.setLabelPaint(labelPaint); } result.setDataset(dataset); result.setDatasetIndex(datasetIndex); result.setSeriesKey(dataset.getRowKey(series)); result.setSeriesIndex(series); return result; } return null; } /** * This renderer uses two passes to draw the data. * * @return The pass count (<code>2</code> for this renderer). */ @Override public int getPassCount() { return 2; } /** * Draw a single data item. * * @param g2 the graphics device. * @param state the renderer state. * @param dataArea the area in which the data is drawn. * @param plot the plot. * @param domainAxis the domain axis. * @param rangeAxis the range axis. * @param dataset the dataset. * @param row the row index (zero-based). * @param column the column index (zero-based). * @param pass the pass index. */ @Override public void drawItem(Graphics2D g2, CategoryItemRendererState state, Rectangle2D dataArea, CategoryPlot plot, CategoryAxis domainAxis, ValueAxis rangeAxis, CategoryDataset dataset, int row, int column, int pass) { // do nothing if item is not visible if (!getItemVisible(row, column)) { return; } // do nothing if both the line and shape are not visible if (!getItemLineVisible(row, column) && !getItemShapeVisible(row, column)) { return; } // nothing is drawn for null... Number v = dataset.getValue(row, column); if (v == null) { return; } int visibleRow = state.getVisibleSeriesIndex(row); if (visibleRow < 0) { return; } int visibleRowCount = state.getVisibleSeriesCount(); PlotOrientation orientation = plot.getOrientation(); // current data point... double x1; if (this.useSeriesOffset) { x1 = domainAxis.getCategorySeriesMiddle(column, dataset.getColumnCount(), visibleRow, visibleRowCount, this.itemMargin, dataArea, plot.getDomainAxisEdge()); } else { x1 = domainAxis.getCategoryMiddle(column, getColumnCount(), dataArea, plot.getDomainAxisEdge()); } double value = v.doubleValue(); double y1 = rangeAxis.valueToJava2D(value, dataArea, plot.getRangeAxisEdge()); if (pass == 0 && getItemLineVisible(row, column)) { if (column != 0) { Number previousValue = dataset.getValue(row, column - 1); if (previousValue != null) { // previous data point... double previous = previousValue.doubleValue(); double x0; if (this.useSeriesOffset) { x0 = domainAxis.getCategorySeriesMiddle( column - 1, dataset.getColumnCount(), visibleRow, visibleRowCount, this.itemMargin, dataArea, plot.getDomainAxisEdge()); } else { x0 = domainAxis.getCategoryMiddle(column - 1, getColumnCount(), dataArea, plot.getDomainAxisEdge()); } double y0 = rangeAxis.valueToJava2D(previous, dataArea, plot.getRangeAxisEdge()); Line2D line = null; if (orientation == PlotOrientation.HORIZONTAL) { line = new Line2D.Double(y0, x0, y1, x1); } else if (orientation == PlotOrientation.VERTICAL) { line = new Line2D.Double(x0, y0, x1, y1); } g2.setPaint(getItemPaint(row, column)); g2.setStroke(getItemStroke(row, column)); g2.draw(line); } } } if (pass == 1) { Shape shape = getItemShape(row, column); if (orientation == PlotOrientation.HORIZONTAL) { shape = ShapeUtilities.createTranslatedShape(shape, y1, x1); } else if (orientation == PlotOrientation.VERTICAL) { shape = ShapeUtilities.createTranslatedShape(shape, x1, y1); } if (getItemShapeVisible(row, column)) { if (getItemShapeFilled(row, column)) { if (this.useFillPaint) { g2.setPaint(getItemFillPaint(row, column)); } else { g2.setPaint(getItemPaint(row, column)); } g2.fill(shape); } if (this.drawOutlines) { if (this.useOutlinePaint) { g2.setPaint(getItemOutlinePaint(row, column)); } else { g2.setPaint(getItemPaint(row, column)); } g2.setStroke(getItemOutlineStroke(row, column)); g2.draw(shape); } } // draw the item label if there is one... if (isItemLabelVisible(row, column)) { if (orientation == PlotOrientation.HORIZONTAL) { drawItemLabel(g2, orientation, dataset, row, column, y1, x1, (value < 0.0)); } else if (orientation == PlotOrientation.VERTICAL) { drawItemLabel(g2, orientation, dataset, row, column, x1, y1, (value < 0.0)); } } // submit the current data point as a crosshair candidate int datasetIndex = plot.indexOf(dataset); updateCrosshairValues(state.getCrosshairState(), dataset.getRowKey(row), dataset.getColumnKey(column), value, datasetIndex, x1, y1, orientation); // add an item entity, if this information is being collected EntityCollection entities = state.getEntityCollection(); if (entities != null) { addItemEntity(entities, dataset, row, column, shape); } } } /** * Tests this renderer for equality with an arbitrary object. * * @param obj the object (<code>null</code> permitted). * * @return A boolean. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof LineAndShapeRenderer)) { return false; } LineAndShapeRenderer that = (LineAndShapeRenderer) obj; if (this.baseLinesVisible != that.baseLinesVisible) { return false; } if (!ObjectUtilities.equal(this.seriesLinesVisible, that.seriesLinesVisible)) { return false; } if (this.baseShapesVisible != that.baseShapesVisible) { return false; } if (!ObjectUtilities.equal(this.seriesShapesVisible, that.seriesShapesVisible)) { return false; } if (!ObjectUtilities.equal(this.seriesShapesFilled, that.seriesShapesFilled)) { return false; } if (this.baseShapesFilled != that.baseShapesFilled) { return false; } if (this.useOutlinePaint != that.useOutlinePaint) { return false; } if (this.useSeriesOffset != that.useSeriesOffset) { return false; } if (this.itemMargin != that.itemMargin) { return false; } return super.equals(obj); } /** * Returns an independent copy of the renderer. * * @return A clone. * * @throws CloneNotSupportedException should not happen. */ @Override public Object clone() throws CloneNotSupportedException { LineAndShapeRenderer clone = (LineAndShapeRenderer) super.clone(); clone.seriesLinesVisible = (BooleanList) this.seriesLinesVisible.clone(); clone.seriesShapesVisible = (BooleanList) this.seriesShapesVisible.clone(); clone.seriesShapesFilled = (BooleanList) this.seriesShapesFilled.clone(); return clone; } }
31,339
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
LayeredBarRenderer.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/renderer/category/LayeredBarRenderer.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ----------------------- * LayeredBarRenderer.java * ----------------------- * (C) Copyright 2003-2012, by Arnaud Lelievre and Contributors. * * Original Author: Arnaud Lelievre (for Garden); * Contributor(s): David Gilbert (for Object Refinery Limited); * Zoheb Borbora; * * Changes * ------- * 28-Aug-2003 : Version 1 (AL); * 16-Sep-2003 : Changed ChartRenderingInfo --> PlotRenderingInfo (DG); * 07-Oct-2003 : Added renderer state (DG); * 21-Oct-2003 : Bar width moved to renderer state (DG); * 05-Nov-2004 : Modified drawItem() signature (DG); * 20-Apr-2005 : Renamed CategoryLabelGenerator * --> CategoryItemLabelGenerator (DG); * 17-Nov-2005 : Added support for gradient paint (DG); * ------------- JFREECHART 1.0.x --------------------------------------------- * 18-Aug-2006 : Fixed the bar width calculation to respect the maximum bar * width setting (thanks to Zoheb Borbora) (DG); * 02-Feb-2007 : Removed author tags all over JFreeChart sources (DG); * 19-May-2009 : Fixed FindBugs warnings, patch by Michal Wozniak (DG); * 16-Jun-2012 : Removed JCommon dependencies (DG); * */ package org.jfree.chart.renderer.category; import java.awt.GradientPaint; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.Stroke; import java.awt.geom.Rectangle2D; import java.io.Serializable; import org.jfree.chart.axis.CategoryAxis; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.ui.GradientPaintTransformer; import org.jfree.chart.ui.RectangleEdge; import org.jfree.chart.util.ObjectList; import org.jfree.chart.entity.EntityCollection; import org.jfree.chart.labels.CategoryItemLabelGenerator; import org.jfree.chart.plot.CategoryPlot; import org.jfree.chart.plot.PlotOrientation; import org.jfree.data.category.CategoryDataset; /** * A {@link CategoryItemRenderer} that represents data using bars which are * superimposed. The example shown here is generated by the * <code>LayeredBarChartDemo1.java</code> program included in the JFreeChart * Demo Collection: * <br><br> * <img src="../../../../../images/LayeredBarRendererSample.png" * alt="LayeredBarRendererSample.png" /> */ public class LayeredBarRenderer extends BarRenderer implements Serializable { /** For serialization. */ private static final long serialVersionUID = -8716572894780469487L; /** A list of the width of each series bar. */ protected ObjectList<Double> seriesBarWidthList; /** * Default constructor. */ public LayeredBarRenderer() { super(); this.seriesBarWidthList = new ObjectList<Double>(); } /** * Returns the bar width for a series, or <code>Double.NaN</code> if no * width has been set. * * @param series the series index (zero based). * * @return The width for the series (1.0=100%, it is the maximum). */ public double getSeriesBarWidth(int series) { double result = Double.NaN; Number n = this.seriesBarWidthList.get(series); if (n != null) { result = n.doubleValue(); } return result; } /** * Sets the width of the bars of a series. * * @param series the series index (zero based). * @param width the width of the series bar in percentage (1.0=100%, it is * the maximum). */ public void setSeriesBarWidth(int series, double width) { this.seriesBarWidthList.set(series, new Double(width)); } /** * Calculates the bar width and stores it in the renderer state. * * @param plot the plot. * @param dataArea the data area. * @param rendererIndex the renderer index. * @param state the renderer state. */ @Override protected void calculateBarWidth(CategoryPlot plot, Rectangle2D dataArea, int rendererIndex, CategoryItemRendererState state) { // calculate the bar width - this calculation differs from the // BarRenderer calculation because the bars are layered on top of one // another, so there is effectively only one bar per category for // the purpose of the bar width calculation CategoryAxis domainAxis = getDomainAxis(plot, rendererIndex); CategoryDataset dataset = plot.getDataset(rendererIndex); if (dataset != null) { int columns = dataset.getColumnCount(); int rows = dataset.getRowCount(); double space = 0.0; PlotOrientation orientation = plot.getOrientation(); if (orientation == PlotOrientation.HORIZONTAL) { space = dataArea.getHeight(); } else if (orientation == PlotOrientation.VERTICAL) { space = dataArea.getWidth(); } double maxWidth = space * getMaximumBarWidth(); double categoryMargin = 0.0; if (columns > 1) { categoryMargin = domainAxis.getCategoryMargin(); } double used = space * (1 - domainAxis.getLowerMargin() - domainAxis.getUpperMargin() - categoryMargin); if ((rows * columns) > 0) { state.setBarWidth(Math.min(used / (dataset.getColumnCount()), maxWidth)); } else { state.setBarWidth(Math.min(used, maxWidth)); } } } /** * Draws the bar for one item in the dataset. * * @param g2 the graphics device. * @param state the renderer state. * @param dataArea the plot area. * @param plot the plot. * @param domainAxis the domain (category) axis. * @param rangeAxis the range (value) axis. * @param data the data. * @param row the row index (zero-based). * @param column the column index (zero-based). * @param pass the pass index. */ @Override public void drawItem(Graphics2D g2, CategoryItemRendererState state, Rectangle2D dataArea, CategoryPlot plot, CategoryAxis domainAxis, ValueAxis rangeAxis, CategoryDataset data, int row, int column, int pass) { PlotOrientation orientation = plot.getOrientation(); if (orientation == PlotOrientation.HORIZONTAL) { drawHorizontalItem(g2, state, dataArea, plot, domainAxis, rangeAxis, data, row, column); } else if (orientation == PlotOrientation.VERTICAL) { drawVerticalItem(g2, state, dataArea, plot, domainAxis, rangeAxis, data, row, column); } } /** * Draws the bar for a single (series, category) data item. * * @param g2 the graphics device. * @param state the renderer state. * @param dataArea the data area. * @param plot the plot. * @param domainAxis the domain axis. * @param rangeAxis the range axis. * @param dataset the dataset. * @param row the row index (zero-based). * @param column the column index (zero-based). */ protected void drawHorizontalItem(Graphics2D g2, CategoryItemRendererState state, Rectangle2D dataArea, CategoryPlot plot, CategoryAxis domainAxis, ValueAxis rangeAxis, CategoryDataset dataset, int row, int column) { // nothing is drawn for null values... Number dataValue = dataset.getValue(row, column); if (dataValue == null) { return; } // X double value = dataValue.doubleValue(); double base = 0.0; double lclip = getLowerClip(); double uclip = getUpperClip(); if (uclip <= 0.0) { // cases 1, 2, 3 and 4 if (value >= uclip) { return; // bar is not visible } base = uclip; if (value <= lclip) { value = lclip; } } else if (lclip <= 0.0) { // cases 5, 6, 7 and 8 if (value >= uclip) { value = uclip; } else { if (value <= lclip) { value = lclip; } } } else { // cases 9, 10, 11 and 12 if (value <= lclip) { return; // bar is not visible } base = lclip; if (value >= uclip) { value = uclip; } } RectangleEdge edge = plot.getRangeAxisEdge(); double transX1 = rangeAxis.valueToJava2D(base, dataArea, edge); double transX2 = rangeAxis.valueToJava2D(value, dataArea, edge); double rectX = Math.min(transX1, transX2); double rectWidth = Math.abs(transX2 - transX1); // Y double rectY = domainAxis.getCategoryMiddle(column, getColumnCount(), dataArea, plot.getDomainAxisEdge()) - state.getBarWidth() / 2.0; int seriesCount = getRowCount(); // draw the bar... double shift = 0.0; double rectHeight = 0.0; double widthFactor = 1.0; double seriesBarWidth = getSeriesBarWidth(row); if (!Double.isNaN(seriesBarWidth)) { widthFactor = seriesBarWidth; } rectHeight = widthFactor * state.getBarWidth(); rectY = rectY + (1 - widthFactor) * state.getBarWidth() / 2.0; if (seriesCount > 1) { shift = rectHeight * 0.20 / (seriesCount - 1); } Rectangle2D bar = new Rectangle2D.Double(rectX, (rectY + ((seriesCount - 1 - row) * shift)), rectWidth, (rectHeight - (seriesCount - 1 - row) * shift * 2)); Paint itemPaint = getItemPaint(row, column); GradientPaintTransformer t = getGradientPaintTransformer(); if (t != null && itemPaint instanceof GradientPaint) { itemPaint = t.transform((GradientPaint) itemPaint, bar); } g2.setPaint(itemPaint); g2.fill(bar); // draw the outline... if (isDrawBarOutline() && state.getBarWidth() > BAR_OUTLINE_WIDTH_THRESHOLD) { Stroke stroke = getItemOutlineStroke(row, column); Paint paint = getItemOutlinePaint(row, column); if (stroke != null && paint != null) { g2.setStroke(stroke); g2.setPaint(paint); g2.draw(bar); } } CategoryItemLabelGenerator generator = getItemLabelGenerator(row, column); if (generator != null && isItemLabelVisible(row, column)) { drawItemLabel(g2, dataset, row, column, plot, generator, bar, (transX1 > transX2)); } // collect entity and tool tip information... EntityCollection entities = state.getEntityCollection(); if (entities != null) { addItemEntity(entities, dataset, row, column, bar); } } /** * Draws the bar for a single (series, category) data item. * * @param g2 the graphics device. * @param state the renderer state. * @param dataArea the data area. * @param plot the plot. * @param domainAxis the domain axis. * @param rangeAxis the range axis. * @param dataset the dataset. * @param row the row index (zero-based). * @param column the column index (zero-based). */ protected void drawVerticalItem(Graphics2D g2, CategoryItemRendererState state, Rectangle2D dataArea, CategoryPlot plot, CategoryAxis domainAxis, ValueAxis rangeAxis, CategoryDataset dataset, int row, int column) { // nothing is drawn for null values... Number dataValue = dataset.getValue(row, column); if (dataValue == null) { return; } // BAR X double rectX = domainAxis.getCategoryMiddle(column, getColumnCount(), dataArea, plot.getDomainAxisEdge()) - state.getBarWidth() / 2.0; int seriesCount = getRowCount(); // BAR Y double value = dataValue.doubleValue(); double base = 0.0; double lclip = getLowerClip(); double uclip = getUpperClip(); if (uclip <= 0.0) { // cases 1, 2, 3 and 4 if (value >= uclip) { return; // bar is not visible } base = uclip; if (value <= lclip) { value = lclip; } } else if (lclip <= 0.0) { // cases 5, 6, 7 and 8 if (value >= uclip) { value = uclip; } else { if (value <= lclip) { value = lclip; } } } else { // cases 9, 10, 11 and 12 if (value <= lclip) { return; // bar is not visible } base = getLowerClip(); if (value >= uclip) { value = uclip; } } RectangleEdge edge = plot.getRangeAxisEdge(); double transY1 = rangeAxis.valueToJava2D(base, dataArea, edge); double transY2 = rangeAxis.valueToJava2D(value, dataArea, edge); double rectY = Math.min(transY2, transY1); double rectWidth = 0.0; double rectHeight = Math.abs(transY2 - transY1); // draw the bar... double shift = 0.0; double widthFactor = 1.0; double seriesBarWidth = getSeriesBarWidth(row); if (!Double.isNaN(seriesBarWidth)) { widthFactor = seriesBarWidth; } rectWidth = widthFactor * state.getBarWidth(); rectX = rectX + (1 - widthFactor) * state.getBarWidth() / 2.0; if (seriesCount > 1) { // needs to be improved !!! shift = rectWidth * 0.20 / (seriesCount - 1); } Rectangle2D bar = new Rectangle2D.Double( (rectX + ((seriesCount - 1 - row) * shift)), rectY, (rectWidth - (seriesCount - 1 - row) * shift * 2), rectHeight); Paint itemPaint = getItemPaint(row, column); GradientPaintTransformer t = getGradientPaintTransformer(); if (t != null && itemPaint instanceof GradientPaint) { itemPaint = t.transform((GradientPaint) itemPaint, bar); } g2.setPaint(itemPaint); g2.fill(bar); // draw the outline... if (isDrawBarOutline() && state.getBarWidth() > BAR_OUTLINE_WIDTH_THRESHOLD) { Stroke stroke = getItemOutlineStroke(row, column); Paint paint = getItemOutlinePaint(row, column); if (stroke != null && paint != null) { g2.setStroke(stroke); g2.setPaint(paint); g2.draw(bar); } } // draw the item labels if there are any... double transX1 = rangeAxis.valueToJava2D(base, dataArea, edge); double transX2 = rangeAxis.valueToJava2D(value, dataArea, edge); CategoryItemLabelGenerator generator = getItemLabelGenerator(row, column); if (generator != null && isItemLabelVisible(row, column)) { drawItemLabel(g2, dataset, row, column, plot, generator, bar, (transX1 > transX2)); } // collect entity and tool tip information... EntityCollection entities = state.getEntityCollection(); if (entities != null) { addItemEntity(entities, dataset, row, column, bar); } } }
17,571
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
StackedAreaRenderer.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/renderer/category/StackedAreaRenderer.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ------------------------ * StackedAreaRenderer.java * ------------------------ * (C) Copyright 2002-2012, by Dan Rivett ([email protected]) and * Contributors. * * Original Author: Dan Rivett (adapted from AreaRenderer); * Contributor(s): Jon Iles; * David Gilbert (for Object Refinery Limited); * Christian W. Zuckschwerdt; * Peter Kolb (patch 2511330); * * Changes: * -------- * 20-Sep-2002 : Version 1, contributed by Dan Rivett; * 24-Oct-2002 : Amendments for changes in CategoryDataset interface and * CategoryToolTipGenerator interface (DG); * 01-Nov-2002 : Added tooltips (DG); * 06-Nov-2002 : Renamed drawCategoryItem() --> drawItem() and now using axis * for category spacing. Renamed StackedAreaCategoryItemRenderer * --> StackedAreaRenderer (DG); * 26-Nov-2002 : Switched CategoryDataset --> TableDataset (DG); * 26-Nov-2002 : Replaced isStacked() method with getRangeType() method (DG); * 17-Jan-2003 : Moved plot classes to a separate package (DG); * 25-Mar-2003 : Implemented Serializable (DG); * 13-May-2003 : Modified to take into account the plot orientation (DG); * 30-Jul-2003 : Modified entity constructor (CZ); * 07-Oct-2003 : Added renderer state (DG); * 29-Apr-2004 : Added getRangeExtent() override (DG); * 05-Nov-2004 : Modified drawItem() signature (DG); * 07-Jan-2005 : Renamed getRangeExtent() --> findRangeBounds() (DG); * ------------- JFREECHART 1.0.x --------------------------------------------- * 11-Oct-2006 : Added support for rendering data values as percentages, * and added a second pass for drawing item labels (DG); * 04-Feb-2009 : Fixed support for hidden series, and bug in findRangeBounds() * method for null dataset (PK/DG); * 04-Feb-2009 : Added item label support, and generate entities only in first * pass (DG); * 04-Feb-2009 : Fixed bug for renderAsPercentages == true (DG); * 17-Jun-2012 : Removed JCommon dependencies (DG); * */ package org.jfree.chart.renderer.category; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.Shape; import java.awt.geom.GeneralPath; import java.awt.geom.Rectangle2D; import java.io.Serializable; import org.jfree.chart.axis.CategoryAxis; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.ui.RectangleEdge; import org.jfree.chart.util.PublicCloneable; import org.jfree.chart.entity.EntityCollection; import org.jfree.chart.event.RendererChangeEvent; import org.jfree.chart.plot.CategoryPlot; import org.jfree.data.DataUtilities; import org.jfree.data.Range; import org.jfree.data.category.CategoryDataset; import org.jfree.data.general.DatasetUtilities; /** * A renderer that draws stacked area charts for a {@link CategoryPlot}. * The example shown here is generated by the * <code>StackedAreaChartDemo1.java</code> program included in the * JFreeChart Demo Collection: * <br><br> * <img src="../../../../../images/StackedAreaRendererSample.png" * alt="StackedAreaRendererSample.png" /> */ public class StackedAreaRenderer extends AreaRenderer implements Cloneable, PublicCloneable, Serializable { /** For serialization. */ private static final long serialVersionUID = -3595635038460823663L; /** A flag that controls whether the areas display values or percentages. */ private boolean renderAsPercentages; /** * Creates a new renderer. */ public StackedAreaRenderer() { this(false); } /** * Creates a new renderer. * * @param renderAsPercentages a flag that controls whether the data values * are rendered as percentages. */ public StackedAreaRenderer(boolean renderAsPercentages) { super(); this.renderAsPercentages = renderAsPercentages; } /** * Returns <code>true</code> if the renderer displays each item value as * a percentage (so that the stacked areas add to 100%), and * <code>false</code> otherwise. * * @return A boolean. * * @since 1.0.3 */ public boolean getRenderAsPercentages() { return this.renderAsPercentages; } /** * Sets the flag that controls whether the renderer displays each item * value as a percentage (so that the stacked areas add to 100%), and sends * a {@link RendererChangeEvent} to all registered listeners. * * @param asPercentages the flag. * * @since 1.0.3 */ public void setRenderAsPercentages(boolean asPercentages) { this.renderAsPercentages = asPercentages; fireChangeEvent(); } /** * Returns the number of passes (<code>2</code>) required by this renderer. * The first pass is used to draw the areas, the second pass is used to * draw the item labels (if visible). * * @return The number of passes required by the renderer. */ @Override public int getPassCount() { return 2; } /** * Returns the range of values the renderer requires to display all the * items from the specified dataset. * * @param dataset the dataset (<code>null</code> not permitted). * * @return The range (or <code>null</code> if the dataset is empty). */ @Override public Range findRangeBounds(CategoryDataset dataset) { if (dataset == null) { return null; } if (this.renderAsPercentages) { return new Range(0.0, 1.0); } else { return DatasetUtilities.findStackedRangeBounds(dataset); } } /** * Draw a single data item. * * @param g2 the graphics device. * @param state the renderer state. * @param dataArea the data plot area. * @param plot the plot. * @param domainAxis the domain axis. * @param rangeAxis the range axis. * @param dataset the data. * @param row the row index (zero-based). * @param column the column index (zero-based). * @param pass the pass index. */ @Override public void drawItem(Graphics2D g2, CategoryItemRendererState state, Rectangle2D dataArea, CategoryPlot plot, CategoryAxis domainAxis, ValueAxis rangeAxis, CategoryDataset dataset, int row, int column, int pass) { if (!isSeriesVisible(row)) { return; } // setup for collecting optional entity info... Shape entityArea = null; EntityCollection entities = state.getEntityCollection(); double y1 = 0.0; Number n = dataset.getValue(row, column); if (n != null) { y1 = n.doubleValue(); if (this.renderAsPercentages) { double total = DataUtilities.calculateColumnTotal(dataset, column, state.getVisibleSeriesArray()); y1 = y1 / total; } } double[] stack1 = getStackValues(dataset, row, column, state.getVisibleSeriesArray()); // leave the y values (y1, y0) untranslated as it is going to be be // stacked up later by previous series values, after this it will be // translated. double xx1 = domainAxis.getCategoryMiddle(column, getColumnCount(), dataArea, plot.getDomainAxisEdge()); // get the previous point and the next point so we can calculate a // "hot spot" for the area (used by the chart entity)... double y0 = 0.0; n = dataset.getValue(row, Math.max(column - 1, 0)); if (n != null) { y0 = n.doubleValue(); if (this.renderAsPercentages) { double total = DataUtilities.calculateColumnTotal(dataset, Math.max(column - 1, 0), state.getVisibleSeriesArray()); y0 = y0 / total; } } double[] stack0 = getStackValues(dataset, row, Math.max(column - 1, 0), state.getVisibleSeriesArray()); // FIXME: calculate xx0 double xx0 = domainAxis.getCategoryStart(column, getColumnCount(), dataArea, plot.getDomainAxisEdge()); int itemCount = dataset.getColumnCount(); double y2 = 0.0; n = dataset.getValue(row, Math.min(column + 1, itemCount - 1)); if (n != null) { y2 = n.doubleValue(); if (this.renderAsPercentages) { double total = DataUtilities.calculateColumnTotal(dataset, Math.min(column + 1, itemCount - 1), state.getVisibleSeriesArray()); y2 = y2 / total; } } double[] stack2 = getStackValues(dataset, row, Math.min(column + 1, itemCount - 1), state.getVisibleSeriesArray()); double xx2 = domainAxis.getCategoryEnd(column, getColumnCount(), dataArea, plot.getDomainAxisEdge()); // FIXME: calculate xxLeft and xxRight double xxLeft = xx0; double xxRight = xx2; double[] stackLeft = averageStackValues(stack0, stack1); double[] stackRight = averageStackValues(stack1, stack2); double[] adjStackLeft = adjustedStackValues(stack0, stack1); double[] adjStackRight = adjustedStackValues(stack1, stack2); float transY1; RectangleEdge edge1 = plot.getRangeAxisEdge(); GeneralPath left = new GeneralPath(); GeneralPath right = new GeneralPath(); if (y1 >= 0.0) { // handle positive value transY1 = (float) rangeAxis.valueToJava2D(y1 + stack1[1], dataArea, edge1); float transStack1 = (float) rangeAxis.valueToJava2D(stack1[1], dataArea, edge1); float transStackLeft = (float) rangeAxis.valueToJava2D( adjStackLeft[1], dataArea, edge1); // LEFT POLYGON if (y0 >= 0.0) { double yleft = (y0 + y1) / 2.0 + stackLeft[1]; float transYLeft = (float) rangeAxis.valueToJava2D(yleft, dataArea, edge1); left.moveTo((float) xx1, transY1); left.lineTo((float) xx1, transStack1); left.lineTo((float) xxLeft, transStackLeft); left.lineTo((float) xxLeft, transYLeft); left.closePath(); } else { left.moveTo((float) xx1, transStack1); left.lineTo((float) xx1, transY1); left.lineTo((float) xxLeft, transStackLeft); left.closePath(); } float transStackRight = (float) rangeAxis.valueToJava2D( adjStackRight[1], dataArea, edge1); // RIGHT POLYGON if (y2 >= 0.0) { double yright = (y1 + y2) / 2.0 + stackRight[1]; float transYRight = (float) rangeAxis.valueToJava2D(yright, dataArea, edge1); right.moveTo((float) xx1, transStack1); right.lineTo((float) xx1, transY1); right.lineTo((float) xxRight, transYRight); right.lineTo((float) xxRight, transStackRight); right.closePath(); } else { right.moveTo((float) xx1, transStack1); right.lineTo((float) xx1, transY1); right.lineTo((float) xxRight, transStackRight); right.closePath(); } } else { // handle negative value transY1 = (float) rangeAxis.valueToJava2D(y1 + stack1[0], dataArea, edge1); float transStack1 = (float) rangeAxis.valueToJava2D(stack1[0], dataArea, edge1); float transStackLeft = (float) rangeAxis.valueToJava2D( adjStackLeft[0], dataArea, edge1); // LEFT POLYGON if (y0 >= 0.0) { left.moveTo((float) xx1, transStack1); left.lineTo((float) xx1, transY1); left.lineTo((float) xxLeft, transStackLeft); left.clone(); } else { double yleft = (y0 + y1) / 2.0 + stackLeft[0]; float transYLeft = (float) rangeAxis.valueToJava2D(yleft, dataArea, edge1); left.moveTo((float) xx1, transY1); left.lineTo((float) xx1, transStack1); left.lineTo((float) xxLeft, transStackLeft); left.lineTo((float) xxLeft, transYLeft); left.closePath(); } float transStackRight = (float) rangeAxis.valueToJava2D( adjStackRight[0], dataArea, edge1); // RIGHT POLYGON if (y2 >= 0.0) { right.moveTo((float) xx1, transStack1); right.lineTo((float) xx1, transY1); right.lineTo((float) xxRight, transStackRight); right.closePath(); } else { double yright = (y1 + y2) / 2.0 + stackRight[0]; float transYRight = (float) rangeAxis.valueToJava2D(yright, dataArea, edge1); right.moveTo((float) xx1, transStack1); right.lineTo((float) xx1, transY1); right.lineTo((float) xxRight, transYRight); right.lineTo((float) xxRight, transStackRight); right.closePath(); } } if (pass == 0) { Paint itemPaint = getItemPaint(row, column); g2.setPaint(itemPaint); g2.fill(left); g2.fill(right); // add an entity for the item... if (entities != null) { GeneralPath gp = new GeneralPath(left); gp.append(right, false); entityArea = gp; addItemEntity(entities, dataset, row, column, entityArea); } } else if (pass == 1) { drawItemLabel(g2, plot.getOrientation(), dataset, row, column, xx1, transY1, y1 < 0.0); } } /** * Calculates the stacked values (one positive and one negative) of all * series up to, but not including, <code>series</code> for the specified * item. It returns [0.0, 0.0] if <code>series</code> is the first series. * * @param dataset the dataset (<code>null</code> not permitted). * @param series the series index. * @param index the item index. * * @return An array containing the cumulative negative and positive values * for all series values up to but excluding <code>series</code> * for <code>index</code>. */ protected double[] getStackValues(CategoryDataset dataset, int series, int index, int[] validRows) { double[] result = new double[2]; double total = 0.0; if (this.renderAsPercentages) { total = DataUtilities.calculateColumnTotal(dataset, index, validRows); } for (int i = 0; i < series; i++) { if (isSeriesVisible(i)) { double v = 0.0; Number n = dataset.getValue(i, index); if (n != null) { v = n.doubleValue(); if (this.renderAsPercentages) { v = v / total; } } if (!Double.isNaN(v)) { if (v >= 0.0) { result[1] += v; } else { result[0] += v; } } } } return result; } /** * Returns a pair of "stack" values calculated as the mean of the two * specified stack value pairs. * * @param stack1 the first stack pair. * @param stack2 the second stack pair. * * @return A pair of average stack values. */ private double[] averageStackValues(double[] stack1, double[] stack2) { double[] result = new double[2]; result[0] = (stack1[0] + stack2[0]) / 2.0; result[1] = (stack1[1] + stack2[1]) / 2.0; return result; } /** * Calculates adjusted stack values from the supplied values. The value is * the mean of the supplied values, unless either of the supplied values * is zero, in which case the adjusted value is zero also. * * @param stack1 the first stack pair. * @param stack2 the second stack pair. * * @return A pair of average stack values. */ private double[] adjustedStackValues(double[] stack1, double[] stack2) { double[] result = new double[2]; if (stack1[0] == 0.0 || stack2[0] == 0.0) { result[0] = 0.0; } else { result[0] = (stack1[0] + stack2[0]) / 2.0; } if (stack1[1] == 0.0 || stack2[1] == 0.0) { result[1] = 0.0; } else { result[1] = (stack1[1] + stack2[1]) / 2.0; } return result; } /** * Checks this instance for equality with an arbitrary object. * * @param obj the object (<code>null</code> not permitted). * * @return A boolean. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof StackedAreaRenderer)) { return false; } StackedAreaRenderer that = (StackedAreaRenderer) obj; if (this.renderAsPercentages != that.renderAsPercentages) { return false; } return super.equals(obj); } }
19,327
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
LevelRenderer.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/renderer/category/LevelRenderer.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ------------------ * LevelRenderer.java * ------------------ * (C) Copyright 2004-2012, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): Peter Kolb (patch 2511330); * * Changes * ------- * 09-Jan-2004 : Version 1 (DG); * 05-Nov-2004 : Modified drawItem() signature (DG); * 20-Apr-2005 : Renamed CategoryLabelGenerator * --> CategoryItemLabelGenerator (DG); * ------------- JFREECHART 1.0.x --------------------------------------------- * 23-Jan-2006 : Renamed getMaxItemWidth() --> getMaximumItemWidth() (DG); * 13-May-2008 : Code clean-up (DG); * 26-Jun-2008 : Added crosshair support (DG); * 23-Jan-2009 : Set more appropriate default shape in legend (DG); * 23-Jan-2009 : Added support for seriesVisible flags - see patch * 2511330 (PK) * 17-Jun-2012 : Removed JCommon dependencies (DG); * */ package org.jfree.chart.renderer.category; import java.awt.Color; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.Stroke; import java.awt.geom.Line2D; import java.awt.geom.Rectangle2D; import java.io.Serializable; import org.jfree.chart.HashUtilities; import org.jfree.chart.axis.CategoryAxis; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.ui.RectangleEdge; import org.jfree.chart.util.PublicCloneable; import org.jfree.chart.entity.EntityCollection; import org.jfree.chart.event.RendererChangeEvent; import org.jfree.chart.labels.CategoryItemLabelGenerator; import org.jfree.chart.plot.CategoryPlot; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.PlotRenderingInfo; import org.jfree.data.category.CategoryDataset; /** * A {@link CategoryItemRenderer} that draws individual data items as * horizontal lines, spaced in the same way as bars in a bar chart. The * example shown here is generated by the * <code>OverlaidBarChartDemo2.java</code> program included in the JFreeChart * Demo Collection: * <br><br> * <img src="../../../../../images/LevelRendererSample.png" * alt="LevelRendererSample.png" /> */ public class LevelRenderer extends AbstractCategoryItemRenderer implements Cloneable, PublicCloneable, Serializable { /** For serialization. */ private static final long serialVersionUID = -8204856624355025117L; /** The default item margin percentage. */ public static final double DEFAULT_ITEM_MARGIN = 0.20; /** The margin between items within a category. */ private double itemMargin; /** The maximum item width as a percentage of the available space. */ private double maxItemWidth; /** * Creates a new renderer with default settings. */ public LevelRenderer() { super(); this.itemMargin = DEFAULT_ITEM_MARGIN; this.maxItemWidth = 1.0; // 100 percent, so it will not apply unless // changed setDefaultLegendShape(new Rectangle2D.Float(-5.0f, -1.0f, 10.0f, 2.0f)); // set the outline paint to fully transparent, then the legend shape // will just have the same colour as the lines drawn by the renderer setDefaultOutlinePaint(new Color(0, 0, 0, 0)); } /** * Returns the item margin. * * @return The margin. * * @see #setItemMargin(double) */ public double getItemMargin() { return this.itemMargin; } /** * Sets the item margin and sends a {@link RendererChangeEvent} to all * registered listeners. The value is expressed as a percentage of the * available width for plotting all the bars, with the resulting amount to * be distributed between all the bars evenly. * * @param percent the new margin. * * @see #getItemMargin() */ public void setItemMargin(double percent) { this.itemMargin = percent; fireChangeEvent(); } /** * Returns the maximum width, as a percentage of the available drawing * space. * * @return The maximum width. * * @see #setMaximumItemWidth(double) */ public double getMaximumItemWidth() { return this.maxItemWidth; } /** * Sets the maximum item width, which is specified as a percentage of the * available space for all items, and sends a {@link RendererChangeEvent} * to all registered listeners. * * @param percent the percent. * * @see #getMaximumItemWidth() */ public void setMaximumItemWidth(double percent) { this.maxItemWidth = percent; fireChangeEvent(); } /** * Initialises the renderer and returns a state object that will be passed * to subsequent calls to the drawItem method. * <p> * This method gets called once at the start of the process of drawing a * chart. * * @param g2 the graphics device. * @param dataArea the area in which the data is to be plotted. * @param plot the plot. * @param rendererIndex the renderer index. * @param info collects chart rendering information for return to caller. * * @return The renderer state. */ @Override public CategoryItemRendererState initialise(Graphics2D g2, Rectangle2D dataArea, CategoryPlot plot, int rendererIndex, PlotRenderingInfo info) { CategoryItemRendererState state = super.initialise(g2, dataArea, plot, rendererIndex, info); calculateItemWidth(plot, dataArea, rendererIndex, state); return state; } /** * Calculates the bar width and stores it in the renderer state. * * @param plot the plot. * @param dataArea the data area. * @param rendererIndex the renderer index. * @param state the renderer state. */ protected void calculateItemWidth(CategoryPlot plot, Rectangle2D dataArea, int rendererIndex, CategoryItemRendererState state) { CategoryAxis domainAxis = getDomainAxis(plot, rendererIndex); CategoryDataset dataset = plot.getDataset(rendererIndex); if (dataset != null) { int columns = dataset.getColumnCount(); int rows = state.getVisibleSeriesCount() >= 0 ? state.getVisibleSeriesCount() : dataset.getRowCount(); double space = 0.0; PlotOrientation orientation = plot.getOrientation(); if (orientation == PlotOrientation.HORIZONTAL) { space = dataArea.getHeight(); } else if (orientation == PlotOrientation.VERTICAL) { space = dataArea.getWidth(); } double maxWidth = space * getMaximumItemWidth(); double categoryMargin = 0.0; double currentItemMargin = 0.0; if (columns > 1) { categoryMargin = domainAxis.getCategoryMargin(); } if (rows > 1) { currentItemMargin = getItemMargin(); } double used = space * (1 - domainAxis.getLowerMargin() - domainAxis.getUpperMargin() - categoryMargin - currentItemMargin); if ((rows * columns) > 0) { state.setBarWidth(Math.min(used / (rows * columns), maxWidth)); } else { state.setBarWidth(Math.min(used, maxWidth)); } } } /** * Calculates the coordinate of the first "side" of a bar. This will be * the minimum x-coordinate for a vertical bar, and the minimum * y-coordinate for a horizontal bar. * * @param plot the plot. * @param orientation the plot orientation. * @param dataArea the data area. * @param domainAxis the domain axis. * @param state the renderer state (has the bar width precalculated). * @param row the row index. * @param column the column index. * * @return The coordinate. */ protected double calculateBarW0(CategoryPlot plot, PlotOrientation orientation, Rectangle2D dataArea, CategoryAxis domainAxis, CategoryItemRendererState state, int row, int column) { // calculate bar width... double space; if (orientation == PlotOrientation.HORIZONTAL) { space = dataArea.getHeight(); } else { space = dataArea.getWidth(); } double barW0 = domainAxis.getCategoryStart(column, getColumnCount(), dataArea, plot.getDomainAxisEdge()); int seriesCount = state.getVisibleSeriesCount(); if (seriesCount < 0) { seriesCount = getRowCount(); } int categoryCount = getColumnCount(); if (seriesCount > 1) { double seriesGap = space * getItemMargin() / (categoryCount * (seriesCount - 1)); double seriesW = calculateSeriesWidth(space, domainAxis, categoryCount, seriesCount); barW0 = barW0 + row * (seriesW + seriesGap) + (seriesW / 2.0) - (state.getBarWidth() / 2.0); } else { barW0 = domainAxis.getCategoryMiddle(column, getColumnCount(), dataArea, plot.getDomainAxisEdge()) - state.getBarWidth() / 2.0; } return barW0; } /** * Draws the bar for a single (series, category) data item. * * @param g2 the graphics device. * @param state the renderer state. * @param dataArea the data area. * @param plot the plot. * @param domainAxis the domain axis. * @param rangeAxis the range axis. * @param dataset the dataset. * @param row the row index (zero-based). * @param column the column index (zero-based). * @param pass the pass index. */ @Override public void drawItem(Graphics2D g2, CategoryItemRendererState state, Rectangle2D dataArea, CategoryPlot plot, CategoryAxis domainAxis, ValueAxis rangeAxis, CategoryDataset dataset, int row, int column, int pass) { // nothing is drawn if the row index is not included in the list with // the indices of the visible rows... int visibleRow = state.getVisibleSeriesIndex(row); if (visibleRow < 0) { return; } // nothing is drawn for null values... Number dataValue = dataset.getValue(row, column); if (dataValue == null) { return; } double value = dataValue.doubleValue(); PlotOrientation orientation = plot.getOrientation(); double barW0 = calculateBarW0(plot, orientation, dataArea, domainAxis, state, visibleRow, column); RectangleEdge edge = plot.getRangeAxisEdge(); double barL = rangeAxis.valueToJava2D(value, dataArea, edge); // draw the bar... Line2D line = null; double x; double y; if (orientation == PlotOrientation.HORIZONTAL) { x = barL; y = barW0 + state.getBarWidth() / 2.0; line = new Line2D.Double(barL, barW0, barL, barW0 + state.getBarWidth()); } else { x = barW0 + state.getBarWidth() / 2.0; y = barL; line = new Line2D.Double(barW0, barL, barW0 + state.getBarWidth(), barL); } Stroke itemStroke = getItemStroke(row, column); Paint itemPaint = getItemPaint(row, column); g2.setStroke(itemStroke); g2.setPaint(itemPaint); g2.draw(line); CategoryItemLabelGenerator generator = getItemLabelGenerator(row, column); if (generator != null && isItemLabelVisible(row, column)) { drawItemLabel(g2, orientation, dataset, row, column, x, y, (value < 0.0)); } // submit the current data point as a crosshair candidate int datasetIndex = plot.indexOf(dataset); updateCrosshairValues(state.getCrosshairState(), dataset.getRowKey(row), dataset.getColumnKey(column), value, datasetIndex, barW0, barL, orientation); // collect entity and tool tip information... EntityCollection entities = state.getEntityCollection(); if (entities != null) { addItemEntity(entities, dataset, row, column, line.getBounds()); } } /** * Calculates the available space for each series. * * @param space the space along the entire axis (in Java2D units). * @param axis the category axis. * @param categories the number of categories. * @param series the number of series. * * @return The width of one series. */ protected double calculateSeriesWidth(double space, CategoryAxis axis, int categories, int series) { double factor = 1.0 - getItemMargin() - axis.getLowerMargin() - axis.getUpperMargin(); if (categories > 1) { factor = factor - axis.getCategoryMargin(); } return (space * factor) / (categories * series); } /** * Returns the Java2D coordinate for the middle of the specified data item. * * @param rowKey the row key. * @param columnKey the column key. * @param dataset the dataset. * @param axis the axis. * @param area the drawing area. * @param edge the edge along which the axis lies. * * @return The Java2D coordinate. * * @since 1.0.11 */ @Override public double getItemMiddle(Comparable rowKey, Comparable columnKey, CategoryDataset dataset, CategoryAxis axis, Rectangle2D area, RectangleEdge edge) { return axis.getCategorySeriesMiddle(columnKey, rowKey, dataset, this.itemMargin, area, edge); } /** * Tests an object for equality with this instance. * * @param obj the object (<code>null</code> permitted). * * @return A boolean. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof LevelRenderer)) { return false; } LevelRenderer that = (LevelRenderer) obj; if (this.itemMargin != that.itemMargin) { return false; } if (this.maxItemWidth != that.maxItemWidth) { return false; } return super.equals(obj); } /** * Returns a hash code for this instance. * * @return A hash code. */ @Override public int hashCode() { int hash = super.hashCode(); hash = HashUtilities.hashCode(hash, this.itemMargin); hash = HashUtilities.hashCode(hash, this.maxItemWidth); return hash; } }
16,413
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
CategoryStepRenderer.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/renderer/category/CategoryStepRenderer.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ------------------------- * CategoryStepRenderer.java * ------------------------- * * (C) Copyright 2004-2012, by Brian Cole and Contributors. * * Original Author: Brian Cole; * Contributor(s): David Gilbert (for Object Refinery Limited); * * Changes * ------- * 21-Apr-2004 : Version 1, contributed by Brian Cole (DG); * 22-Apr-2004 : Fixed Checkstyle complaints (DG); * 05-Nov-2004 : Modified drawItem() signature (DG); * 08-Mar-2005 : Added equals() method (DG); * ------------- JFREECHART 1.0.x --------------------------------------------- * 30-Nov-2006 : Added checks for series visibility (DG); * 22-Feb-2007 : Use new state object for reusable line, enable chart entities * (for tooltips, URLs), added new getLegendItem() override (DG); * 20-Apr-2007 : Updated getLegendItem() for renderer change (DG); * 18-May-2007 : Set dataset and seriesKey for LegendItem (DG); * 17-Jun-2008 : Apply legend shape, font and paint attributes (DG); * 17-Jun-2012 : Removed JCommon dependencies (DG); * */ package org.jfree.chart.renderer.category; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.Shape; import java.awt.geom.Line2D; import java.awt.geom.Rectangle2D; import java.io.Serializable; import org.jfree.chart.LegendItem; import org.jfree.chart.axis.CategoryAxis; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.util.PublicCloneable; import org.jfree.chart.entity.EntityCollection; import org.jfree.chart.event.RendererChangeEvent; import org.jfree.chart.plot.CategoryPlot; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.PlotRenderingInfo; import org.jfree.chart.renderer.xy.XYStepRenderer; import org.jfree.data.category.CategoryDataset; /** * A "step" renderer similar to {@link XYStepRenderer} but * that can be used with the {@link CategoryPlot} class. The example shown * here is generated by the <code>CategoryStepChartDemo1.java</code> program * included in the JFreeChart Demo Collection: * <br><br> * <img src="../../../../../images/CategoryStepRendererSample.png" * alt="CategoryStepRendererSample.png" /> */ public class CategoryStepRenderer extends AbstractCategoryItemRenderer implements Cloneable, PublicCloneable, Serializable { /** * State information for the renderer. */ protected static class State extends CategoryItemRendererState { /** * A working line for re-use to avoid creating large numbers of * objects. */ public Line2D line; /** * Creates a new state instance. * * @param info collects plot rendering information (<code>null</code> * permitted). */ public State(PlotRenderingInfo info) { super(info); this.line = new Line2D.Double(); } } /** For serialization. */ private static final long serialVersionUID = -5121079703118261470L; /** The stagger width. */ public static final int STAGGER_WIDTH = 5; // could make this configurable /** * A flag that controls whether or not the steps for multiple series are * staggered. */ private boolean stagger = false; /** * Creates a new renderer (stagger defaults to <code>false</code>). */ public CategoryStepRenderer() { this(false); } /** * Creates a new renderer. * * @param stagger should the horizontal part of the step be staggered by * series? */ public CategoryStepRenderer(boolean stagger) { this.stagger = stagger; setDefaultLegendShape(new Rectangle2D.Double(-4.0, -3.0, 8.0, 6.0)); } /** * Returns the flag that controls whether the series steps are staggered. * * @return A boolean. */ public boolean getStagger() { return this.stagger; } /** * Sets the flag that controls whether or not the series steps are * staggered and sends a {@link RendererChangeEvent} to all registered * listeners. * * @param shouldStagger a boolean. */ public void setStagger(boolean shouldStagger) { this.stagger = shouldStagger; fireChangeEvent(); } /** * Returns a legend item for a series. * * @param datasetIndex the dataset index (zero-based). * @param series the series index (zero-based). * * @return The legend item. */ @Override public LegendItem getLegendItem(int datasetIndex, int series) { CategoryPlot p = getPlot(); if (p == null) { return null; } // check that a legend item needs to be displayed... if (!isSeriesVisible(series) || !isSeriesVisibleInLegend(series)) { return null; } CategoryDataset dataset = p.getDataset(datasetIndex); String label = getLegendItemLabelGenerator().generateLabel(dataset, series); String description = label; String toolTipText = null; if (getLegendItemToolTipGenerator() != null) { toolTipText = getLegendItemToolTipGenerator().generateLabel( dataset, series); } String urlText = null; if (getLegendItemURLGenerator() != null) { urlText = getLegendItemURLGenerator().generateLabel(dataset, series); } Shape shape = lookupLegendShape(series); Paint paint = lookupSeriesPaint(series); LegendItem item = new LegendItem(label, description, toolTipText, urlText, shape, paint); item.setLabelFont(lookupLegendTextFont(series)); Paint labelPaint = lookupLegendTextPaint(series); if (labelPaint != null) { item.setLabelPaint(labelPaint); } item.setSeriesKey(dataset.getRowKey(series)); item.setSeriesIndex(series); item.setDataset(dataset); item.setDatasetIndex(datasetIndex); return item; } /** * Creates a new state instance. This method is called from * {@link #initialise(Graphics2D, Rectangle2D, CategoryPlot, int, * PlotRenderingInfo)}, and we override it to ensure that the state * contains a working Line2D instance. * * @param info the plot rendering info (<code>null</code> is permitted). * * @return A new state instance. */ @Override protected CategoryItemRendererState createState(PlotRenderingInfo info) { return new State(info); } /** * Draws a line taking into account the specified orientation. * <p> * In version 1.0.5, the signature of this method was changed by the * addition of the 'state' parameter. This is an incompatible change, but * is considered a low risk because it is unlikely that anyone has * subclassed this renderer. If this *does* cause trouble for you, please * report it as a bug. * * @param g2 the graphics device. * @param state the renderer state. * @param orientation the plot orientation. * @param x0 the x-coordinate for the start of the line. * @param y0 the y-coordinate for the start of the line. * @param x1 the x-coordinate for the end of the line. * @param y1 the y-coordinate for the end of the line. */ protected void drawLine(Graphics2D g2, State state, PlotOrientation orientation, double x0, double y0, double x1, double y1) { if (orientation == PlotOrientation.VERTICAL) { state.line.setLine(x0, y0, x1, y1); g2.draw(state.line); } else if (orientation == PlotOrientation.HORIZONTAL) { state.line.setLine(y0, x0, y1, x1); // switch x and y g2.draw(state.line); } } /** * Draw a single data item. * * @param g2 the graphics device. * @param state the renderer state. * @param dataArea the area in which the data is drawn. * @param plot the plot. * @param domainAxis the domain axis. * @param rangeAxis the range axis. * @param dataset the dataset. * @param row the row index (zero-based). * @param column the column index (zero-based). * @param pass the pass index. */ @Override public void drawItem(Graphics2D g2, CategoryItemRendererState state, Rectangle2D dataArea, CategoryPlot plot, CategoryAxis domainAxis, ValueAxis rangeAxis, CategoryDataset dataset, int row, int column, int pass) { // do nothing if item is not visible if (!getItemVisible(row, column)) { return; } Number value = dataset.getValue(row, column); if (value == null) { return; } PlotOrientation orientation = plot.getOrientation(); // current data point... double x1s = domainAxis.getCategoryStart(column, getColumnCount(), dataArea, plot.getDomainAxisEdge()); double x1 = domainAxis.getCategoryMiddle(column, getColumnCount(), dataArea, plot.getDomainAxisEdge()); double x1e = 2 * x1 - x1s; // or: x1s + 2*(x1-x1s) double y1 = rangeAxis.valueToJava2D(value.doubleValue(), dataArea, plot.getRangeAxisEdge()); g2.setPaint(getItemPaint(row, column)); g2.setStroke(getItemStroke(row, column)); if (column != 0) { Number previousValue = dataset.getValue(row, column - 1); if (previousValue != null) { // previous data point... double previous = previousValue.doubleValue(); double x0s = domainAxis.getCategoryStart(column - 1, getColumnCount(), dataArea, plot.getDomainAxisEdge()); double x0 = domainAxis.getCategoryMiddle(column - 1, getColumnCount(), dataArea, plot.getDomainAxisEdge()); double x0e = 2 * x0 - x0s; // or: x0s + 2*(x0-x0s) double y0 = rangeAxis.valueToJava2D(previous, dataArea, plot.getRangeAxisEdge()); if (getStagger()) { int xStagger = row * STAGGER_WIDTH; if (xStagger > (x1s - x0e)) { xStagger = (int) (x1s - x0e); } x1s = x0e + xStagger; } drawLine(g2, (State) state, orientation, x0e, y0, x1s, y0); // extend x0's flat bar drawLine(g2, (State) state, orientation, x1s, y0, x1s, y1); // upright bar } } drawLine(g2, (State) state, orientation, x1s, y1, x1e, y1); // x1's flat bar // draw the item labels if there are any... if (isItemLabelVisible(row, column)) { drawItemLabel(g2, orientation, dataset, row, column, x1, y1, (value.doubleValue() < 0.0)); } // add an item entity, if this information is being collected EntityCollection entities = state.getEntityCollection(); if (entities != null) { Rectangle2D hotspot = new Rectangle2D.Double(); if (orientation == PlotOrientation.VERTICAL) { hotspot.setRect(x1s, y1, x1e - x1s, 4.0); } else { hotspot.setRect(y1 - 2.0, x1s, 4.0, x1e - x1s); } addItemEntity(entities, dataset, row, column, hotspot); } } /** * Tests this renderer for equality with an arbitrary object. * * @param obj the object (<code>null</code> permitted). * * @return A boolean. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof CategoryStepRenderer)) { return false; } CategoryStepRenderer that = (CategoryStepRenderer) obj; if (this.stagger != that.stagger) { return false; } return super.equals(obj); } }
13,562
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
BarRenderer3D.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/renderer/category/BarRenderer3D.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ------------------ * BarRenderer3D.java * ------------------ * (C) Copyright 2001-2012, by Serge V. Grachov and Contributors. * * Original Author: Serge V. Grachov; * Contributor(s): David Gilbert (for Object Refinery Limited); * Tin Luu; * Milo Simpson; * Richard Atkinson; * Rich Unger; * Christian W. Zuckschwerdt; * * Changes * ------- * 31-Oct-2001 : First version, contributed by Serge V. Grachov (DG); * 15-Nov-2001 : Modified to allow for null data values (DG); * 13-Dec-2001 : Added tooltips (DG); * 16-Jan-2002 : Added fix for single category or single series datasets, * pointed out by Taoufik Romdhane (DG); * 24-May-2002 : Incorporated tooltips into chart entities (DG); * 11-Jun-2002 : Added check for (permitted) null info object, bug and fix * reported by David Basten. Also updated Javadocs. (DG); * 19-Jun-2002 : Added code to draw labels on bars (TL); * 26-Jun-2002 : Added bar clipping to avoid PRExceptions (DG); * 05-Aug-2002 : Small modification to drawCategoryItem method to support URLs * for HTML image maps (RA); * 06-Aug-2002 : Value labels now use number formatter, thanks to Milo * Simpson (DG); * 08-Aug-2002 : Applied fixed in bug id 592218 (DG); * 20-Sep-2002 : Added fix for categoryPaint by Rich Unger, and fixed errors * reported by Checkstyle (DG); * 24-Oct-2002 : Amendments for changes in CategoryDataset interface and * CategoryToolTipGenerator interface (DG); * 05-Nov-2002 : Replaced references to CategoryDataset with TableDataset (DG); * 06-Nov-2002 : Moved to the com.jrefinery.chart.renderer package (DG); * 28-Jan-2003 : Added an attribute to control the shading of the left and * bottom walls in the plot background (DG); * 25-Mar-2003 : Implemented Serializable (DG); * 10-Apr-2003 : Removed category paint usage (DG); * 13-May-2003 : Renamed VerticalBarRenderer3D --> BarRenderer3D and merged with * HorizontalBarRenderer3D (DG); * 30-Jul-2003 : Modified entity constructor (CZ); * 19-Aug-2003 : Implemented Cloneable and PublicCloneable (DG); * 07-Oct-2003 : Added renderer state (DG); * 08-Oct-2003 : Removed clipping (replaced with flag in CategoryPlot to * control order in which the data items are processed) (DG); * 20-Oct-2003 : Fixed bug (outline stroke not being used for bar * outlines) (DG); * 21-Oct-2003 : Bar width moved into CategoryItemRendererState (DG); * 24-Nov-2003 : Fixed bug 846324 (item labels not showing) (DG); * 27-Nov-2003 : Added code to respect maxBarWidth setting (DG); * 02-Feb-2004 : Fixed bug where 'drawBarOutline' flag is not respected (DG); * 10-Feb-2004 : Small change to drawItem() method to make cut-and-paste * overriding easier (DG); * 04-Oct-2004 : Fixed bug with item label positioning when plot alignment is * horizontal (DG); * 05-Nov-2004 : Modified drawItem() signature (DG); * 20-Apr-2005 : Renamed CategoryLabelGenerator * --> CategoryItemLabelGenerator (DG); * 25-Apr-2005 : Override initialise() method to fix bug 1189642 (DG); * 09-Jun-2005 : Use addEntityItem from super class (DG); * ------------- JFREECHART 1.0.x --------------------------------------------- * 07-Dec-2006 : Implemented equals() override (DG); * 17-Jan-2007 : Fixed bug in drawDomainGridline() method (DG); * 03-Apr-2007 : Fixed bugs in drawBackground() method (DG); * 16-Oct-2007 : Fixed bug in range marker drawing (DG); * 19-Mar-2009 : Override for drawRangeLine() method (DG); * 16-Jun-2012 : Removed JCommon dependencies (DG); * */ package org.jfree.chart.renderer.category; import java.awt.AlphaComposite; import java.awt.Color; import java.awt.Composite; import java.awt.Font; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Paint; import java.awt.Stroke; import java.awt.geom.GeneralPath; import java.awt.geom.Line2D; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import org.jfree.chart.Effect3D; import org.jfree.chart.axis.CategoryAxis; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.ui.LengthAdjustmentType; import org.jfree.chart.ui.RectangleAnchor; import org.jfree.chart.ui.RectangleEdge; import org.jfree.chart.ui.TextAnchor; import org.jfree.chart.util.PaintUtilities; import org.jfree.chart.util.PublicCloneable; import org.jfree.chart.entity.EntityCollection; import org.jfree.chart.event.RendererChangeEvent; import org.jfree.chart.labels.CategoryItemLabelGenerator; import org.jfree.chart.labels.ItemLabelAnchor; import org.jfree.chart.labels.ItemLabelPosition; import org.jfree.chart.plot.CategoryPlot; import org.jfree.chart.plot.Marker; import org.jfree.chart.plot.Plot; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.PlotRenderingInfo; import org.jfree.chart.plot.ValueMarker; import org.jfree.chart.text.TextUtilities; import org.jfree.chart.util.SerialUtilities; import org.jfree.data.Range; import org.jfree.data.category.CategoryDataset; /** * A renderer for bars with a 3D effect, for use with the * {@link CategoryPlot} class. The example shown here is generated * by the <code>BarChart3DDemo1.java</code> program included in the JFreeChart * Demo Collection: * <br><br> * <img src="../../../../../images/BarRenderer3DSample.png" * alt="BarRenderer3DSample.png" /> */ public class BarRenderer3D extends BarRenderer implements Effect3D, Cloneable, PublicCloneable, Serializable { /** For serialization. */ private static final long serialVersionUID = 7686976503536003636L; /** The default x-offset for the 3D effect. */ public static final double DEFAULT_X_OFFSET = 12.0; /** The default y-offset for the 3D effect. */ public static final double DEFAULT_Y_OFFSET = 8.0; /** The default wall paint. */ public static final Paint DEFAULT_WALL_PAINT = new Color(0xDD, 0xDD, 0xDD); /** The size of x-offset for the 3D effect. */ private double xOffset; /** The size of y-offset for the 3D effect. */ private double yOffset; /** The paint used to shade the left and lower 3D wall. */ private transient Paint wallPaint; /** * Default constructor, creates a renderer with a default '3D effect'. */ public BarRenderer3D() { this(DEFAULT_X_OFFSET, DEFAULT_Y_OFFSET); } /** * Constructs a new renderer with the specified '3D effect'. * * @param xOffset the x-offset for the 3D effect. * @param yOffset the y-offset for the 3D effect. */ public BarRenderer3D(double xOffset, double yOffset) { super(); this.xOffset = xOffset; this.yOffset = yOffset; this.wallPaint = DEFAULT_WALL_PAINT; // set the default item label positions ItemLabelPosition p1 = new ItemLabelPosition(ItemLabelAnchor.INSIDE12, TextAnchor.TOP_CENTER); setDefaultPositiveItemLabelPosition(p1); ItemLabelPosition p2 = new ItemLabelPosition(ItemLabelAnchor.INSIDE12, TextAnchor.TOP_CENTER); setDefaultNegativeItemLabelPosition(p2); } /** * Returns the x-offset for the 3D effect. * * @return The 3D effect. * * @see #getYOffset() */ @Override public double getXOffset() { return this.xOffset; } /** * Returns the y-offset for the 3D effect. * * @return The 3D effect. */ @Override public double getYOffset() { return this.yOffset; } /** * Returns the paint used to highlight the left and bottom wall in the plot * background. * * @return The paint. * * @see #setWallPaint(Paint) */ public Paint getWallPaint() { return this.wallPaint; } /** * Sets the paint used to hightlight the left and bottom walls in the plot * background, and sends a {@link RendererChangeEvent} to all registered * listeners. * * @param paint the paint (<code>null</code> not permitted). * * @see #getWallPaint() */ public void setWallPaint(Paint paint) { if (paint == null) { throw new IllegalArgumentException("Null 'paint' argument."); } this.wallPaint = paint; fireChangeEvent(); } /** * Initialises the renderer and returns a state object that will be passed * to subsequent calls to the drawItem method. This method gets called * once at the start of the process of drawing a chart. * * @param g2 the graphics device. * @param dataArea the area in which the data is to be plotted. * @param plot the plot. * @param rendererIndex the renderer index. * @param info collects chart rendering information for return to caller. * * @return The renderer state. */ @Override public CategoryItemRendererState initialise(Graphics2D g2, Rectangle2D dataArea, CategoryPlot plot, int rendererIndex, PlotRenderingInfo info) { Rectangle2D adjusted = new Rectangle2D.Double(dataArea.getX(), dataArea.getY() + getYOffset(), dataArea.getWidth() - getXOffset(), dataArea.getHeight() - getYOffset()); CategoryItemRendererState state = super.initialise(g2, adjusted, plot, rendererIndex, info); return state; } /** * Draws the background for the plot. * * @param g2 the graphics device. * @param plot the plot. * @param dataArea the area inside the axes. */ @Override public void drawBackground(Graphics2D g2, CategoryPlot plot, Rectangle2D dataArea) { float x0 = (float) dataArea.getX(); float x1 = x0 + (float) Math.abs(this.xOffset); float x3 = (float) dataArea.getMaxX(); float x2 = x3 - (float) Math.abs(this.xOffset); float y0 = (float) dataArea.getMaxY(); float y1 = y0 - (float) Math.abs(this.yOffset); float y3 = (float) dataArea.getMinY(); float y2 = y3 + (float) Math.abs(this.yOffset); GeneralPath clip = new GeneralPath(); clip.moveTo(x0, y0); clip.lineTo(x0, y2); clip.lineTo(x1, y3); clip.lineTo(x3, y3); clip.lineTo(x3, y1); clip.lineTo(x2, y0); clip.closePath(); Composite originalComposite = g2.getComposite(); g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, plot.getBackgroundAlpha())); // fill background... Paint backgroundPaint = plot.getBackgroundPaint(); if (backgroundPaint != null) { g2.setPaint(backgroundPaint); g2.fill(clip); } GeneralPath leftWall = new GeneralPath(); leftWall.moveTo(x0, y0); leftWall.lineTo(x0, y2); leftWall.lineTo(x1, y3); leftWall.lineTo(x1, y1); leftWall.closePath(); g2.setPaint(getWallPaint()); g2.fill(leftWall); GeneralPath bottomWall = new GeneralPath(); bottomWall.moveTo(x0, y0); bottomWall.lineTo(x1, y1); bottomWall.lineTo(x3, y1); bottomWall.lineTo(x2, y0); bottomWall.closePath(); g2.setPaint(getWallPaint()); g2.fill(bottomWall); // highlight the background corners... g2.setPaint(Color.LIGHT_GRAY); Line2D corner = new Line2D.Double(x0, y0, x1, y1); g2.draw(corner); corner.setLine(x1, y1, x1, y3); g2.draw(corner); corner.setLine(x1, y1, x3, y1); g2.draw(corner); // draw background image, if there is one... Image backgroundImage = plot.getBackgroundImage(); if (backgroundImage != null) { Rectangle2D adjusted = new Rectangle2D.Double(dataArea.getX() + getXOffset(), dataArea.getY(), dataArea.getWidth() - getXOffset(), dataArea.getHeight() - getYOffset()); plot.drawBackgroundImage(g2, adjusted); } g2.setComposite(originalComposite); } /** * Draws the outline for the plot. * * @param g2 the graphics device. * @param plot the plot. * @param dataArea the area inside the axes. */ @Override public void drawOutline(Graphics2D g2, CategoryPlot plot, Rectangle2D dataArea) { float x0 = (float) dataArea.getX(); float x1 = x0 + (float) Math.abs(this.xOffset); float x3 = (float) dataArea.getMaxX(); float x2 = x3 - (float) Math.abs(this.xOffset); float y0 = (float) dataArea.getMaxY(); float y1 = y0 - (float) Math.abs(this.yOffset); float y3 = (float) dataArea.getMinY(); float y2 = y3 + (float) Math.abs(this.yOffset); GeneralPath clip = new GeneralPath(); clip.moveTo(x0, y0); clip.lineTo(x0, y2); clip.lineTo(x1, y3); clip.lineTo(x3, y3); clip.lineTo(x3, y1); clip.lineTo(x2, y0); clip.closePath(); // put an outline around the data area... Stroke outlineStroke = plot.getOutlineStroke(); Paint outlinePaint = plot.getOutlinePaint(); if ((outlineStroke != null) && (outlinePaint != null)) { g2.setStroke(outlineStroke); g2.setPaint(outlinePaint); g2.draw(clip); } } /** * Draws a grid line against the domain axis. * * @param g2 the graphics device. * @param plot the plot. * @param dataArea the area for plotting data (not yet adjusted for any * 3D effect). * @param value the Java2D value at which the grid line should be drawn. * */ @Override public void drawDomainGridline(Graphics2D g2, CategoryPlot plot, Rectangle2D dataArea, double value) { Line2D line1 = null; Line2D line2 = null; PlotOrientation orientation = plot.getOrientation(); if (orientation == PlotOrientation.HORIZONTAL) { double y0 = value; double y1 = value - getYOffset(); double x0 = dataArea.getMinX(); double x1 = x0 + getXOffset(); double x2 = dataArea.getMaxX(); line1 = new Line2D.Double(x0, y0, x1, y1); line2 = new Line2D.Double(x1, y1, x2, y1); } else if (orientation == PlotOrientation.VERTICAL) { double x0 = value; double x1 = value + getXOffset(); double y0 = dataArea.getMaxY(); double y1 = y0 - getYOffset(); double y2 = dataArea.getMinY(); line1 = new Line2D.Double(x0, y0, x1, y1); line2 = new Line2D.Double(x1, y1, x1, y2); } Paint paint = plot.getDomainGridlinePaint(); Stroke stroke = plot.getDomainGridlineStroke(); g2.setPaint(paint != null ? paint : Plot.DEFAULT_OUTLINE_PAINT); g2.setStroke(stroke != null ? stroke : Plot.DEFAULT_OUTLINE_STROKE); g2.draw(line1); g2.draw(line2); } /** * Draws a grid line against the range axis. * * @param g2 the graphics device. * @param plot the plot. * @param axis the value axis. * @param dataArea the area for plotting data (not yet adjusted for any * 3D effect). * @param value the value at which the grid line should be drawn. * */ @Override public void drawRangeGridline(Graphics2D g2, CategoryPlot plot, ValueAxis axis, Rectangle2D dataArea, double value) { Range range = axis.getRange(); if (!range.contains(value)) { return; } Rectangle2D adjusted = new Rectangle2D.Double(dataArea.getX(), dataArea.getY() + getYOffset(), dataArea.getWidth() - getXOffset(), dataArea.getHeight() - getYOffset()); Line2D line1 = null; Line2D line2 = null; PlotOrientation orientation = plot.getOrientation(); if (orientation == PlotOrientation.HORIZONTAL) { double x0 = axis.valueToJava2D(value, adjusted, plot.getRangeAxisEdge()); double x1 = x0 + getXOffset(); double y0 = dataArea.getMaxY(); double y1 = y0 - getYOffset(); double y2 = dataArea.getMinY(); line1 = new Line2D.Double(x0, y0, x1, y1); line2 = new Line2D.Double(x1, y1, x1, y2); } else if (orientation == PlotOrientation.VERTICAL) { double y0 = axis.valueToJava2D(value, adjusted, plot.getRangeAxisEdge()); double y1 = y0 - getYOffset(); double x0 = dataArea.getMinX(); double x1 = x0 + getXOffset(); double x2 = dataArea.getMaxX(); line1 = new Line2D.Double(x0, y0, x1, y1); line2 = new Line2D.Double(x1, y1, x2, y1); } Paint paint = plot.getRangeGridlinePaint(); Stroke stroke = plot.getRangeGridlineStroke(); g2.setPaint(paint != null ? paint : Plot.DEFAULT_OUTLINE_PAINT); g2.setStroke(stroke != null ? stroke : Plot.DEFAULT_OUTLINE_STROKE); g2.draw(line1); g2.draw(line2); } /** * Draws a line perpendicular to the range axis. * * @param g2 the graphics device. * @param plot the plot. * @param axis the value axis. * @param dataArea the area for plotting data (not yet adjusted for any 3D * effect). * @param value the value at which the grid line should be drawn. * @param paint the paint. * @param stroke the stroke. * * @see #drawRangeGridline * * @since 1.0.13 */ @Override public void drawRangeGridline(Graphics2D g2, CategoryPlot plot, ValueAxis axis, Rectangle2D dataArea, double value, Paint paint, Stroke stroke) { Range range = axis.getRange(); if (!range.contains(value)) { return; } Rectangle2D adjusted = new Rectangle2D.Double(dataArea.getX(), dataArea.getY() + getYOffset(), dataArea.getWidth() - getXOffset(), dataArea.getHeight() - getYOffset()); Line2D line1 = null; Line2D line2 = null; PlotOrientation orientation = plot.getOrientation(); if (orientation == PlotOrientation.HORIZONTAL) { double x0 = axis.valueToJava2D(value, adjusted, plot.getRangeAxisEdge()); double x1 = x0 + getXOffset(); double y0 = dataArea.getMaxY(); double y1 = y0 - getYOffset(); double y2 = dataArea.getMinY(); line1 = new Line2D.Double(x0, y0, x1, y1); line2 = new Line2D.Double(x1, y1, x1, y2); } else if (orientation == PlotOrientation.VERTICAL) { double y0 = axis.valueToJava2D(value, adjusted, plot.getRangeAxisEdge()); double y1 = y0 - getYOffset(); double x0 = dataArea.getMinX(); double x1 = x0 + getXOffset(); double x2 = dataArea.getMaxX(); line1 = new Line2D.Double(x0, y0, x1, y1); line2 = new Line2D.Double(x1, y1, x2, y1); } g2.setPaint(paint); g2.setStroke(stroke); g2.draw(line1); g2.draw(line2); } /** * Draws a range marker. * * @param g2 the graphics device. * @param plot the plot. * @param axis the value axis. * @param marker the marker. * @param dataArea the area for plotting data (not including 3D effect). */ @Override public void drawRangeMarker(Graphics2D g2, CategoryPlot plot, ValueAxis axis, Marker marker, Rectangle2D dataArea) { Rectangle2D adjusted = new Rectangle2D.Double(dataArea.getX(), dataArea.getY() + getYOffset(), dataArea.getWidth() - getXOffset(), dataArea.getHeight() - getYOffset()); if (marker instanceof ValueMarker) { ValueMarker vm = (ValueMarker) marker; double value = vm.getValue(); Range range = axis.getRange(); if (!range.contains(value)) { return; } GeneralPath path = null; PlotOrientation orientation = plot.getOrientation(); if (orientation == PlotOrientation.HORIZONTAL) { float x = (float) axis.valueToJava2D(value, adjusted, plot.getRangeAxisEdge()); float y = (float) adjusted.getMaxY(); path = new GeneralPath(); path.moveTo(x, y); path.lineTo((float) (x + getXOffset()), y - (float) getYOffset()); path.lineTo((float) (x + getXOffset()), (float) (adjusted.getMinY() - getYOffset())); path.lineTo(x, (float) adjusted.getMinY()); path.closePath(); } else if (orientation == PlotOrientation.VERTICAL) { float y = (float) axis.valueToJava2D(value, adjusted, plot.getRangeAxisEdge()); float x = (float) dataArea.getX(); path = new GeneralPath(); path.moveTo(x, y); path.lineTo(x + (float) this.xOffset, y - (float) this.yOffset); path.lineTo((float) (adjusted.getMaxX() + this.xOffset), y - (float) this.yOffset); path.lineTo((float) (adjusted.getMaxX()), y); path.closePath(); } g2.setPaint(marker.getPaint()); g2.fill(path); g2.setPaint(marker.getOutlinePaint()); g2.draw(path); String label = marker.getLabel(); RectangleAnchor anchor = marker.getLabelAnchor(); if (label != null) { Font labelFont = marker.getLabelFont(); g2.setFont(labelFont); g2.setPaint(marker.getLabelPaint()); Point2D coordinates = calculateRangeMarkerTextAnchorPoint( g2, orientation, dataArea, path.getBounds2D(), marker.getLabelOffset(), LengthAdjustmentType.EXPAND, anchor); TextUtilities.drawAlignedString(label, g2, (float) coordinates.getX(), (float) coordinates.getY(), marker.getLabelTextAnchor()); } } else { super.drawRangeMarker(g2, plot, axis, marker, adjusted); // TODO: draw the interval marker with a 3D effect } } /** * Draws a 3D bar to represent one data item. * * @param g2 the graphics device. * @param state the renderer state. * @param dataArea the area for plotting the data. * @param plot the plot. * @param domainAxis the domain axis. * @param rangeAxis the range axis. * @param dataset the dataset. * @param row the row index (zero-based). * @param column the column index (zero-based). * @param pass the pass index. */ @Override public void drawItem(Graphics2D g2, CategoryItemRendererState state, Rectangle2D dataArea, CategoryPlot plot, CategoryAxis domainAxis, ValueAxis rangeAxis, CategoryDataset dataset, int row, int column, int pass) { // check the value we are plotting... Number dataValue = dataset.getValue(row, column); if (dataValue == null) { return; } double value = dataValue.doubleValue(); Rectangle2D adjusted = new Rectangle2D.Double(dataArea.getX(), dataArea.getY() + getYOffset(), dataArea.getWidth() - getXOffset(), dataArea.getHeight() - getYOffset()); PlotOrientation orientation = plot.getOrientation(); double barW0 = calculateBarW0(plot, orientation, adjusted, domainAxis, state, row, column); double[] barL0L1 = calculateBarL0L1(value); if (barL0L1 == null) { return; // the bar is not visible } RectangleEdge edge = plot.getRangeAxisEdge(); double transL0 = rangeAxis.valueToJava2D(barL0L1[0], adjusted, edge); double transL1 = rangeAxis.valueToJava2D(barL0L1[1], adjusted, edge); double barL0 = Math.min(transL0, transL1); double barLength = Math.abs(transL1 - transL0); // draw the bar... Rectangle2D bar = null; if (orientation == PlotOrientation.HORIZONTAL) { bar = new Rectangle2D.Double(barL0, barW0, barLength, state.getBarWidth()); } else { bar = new Rectangle2D.Double(barW0, barL0, state.getBarWidth(), barLength); } Paint itemPaint = getItemPaint(row, column); g2.setPaint(itemPaint); g2.fill(bar); double x0 = bar.getMinX(); double x1 = x0 + getXOffset(); double x2 = bar.getMaxX(); double x3 = x2 + getXOffset(); double y0 = bar.getMinY() - getYOffset(); double y1 = bar.getMinY(); double y2 = bar.getMaxY() - getYOffset(); double y3 = bar.getMaxY(); GeneralPath bar3dRight = null; GeneralPath bar3dTop = null; if (barLength > 0.0) { bar3dRight = new GeneralPath(); bar3dRight.moveTo((float) x2, (float) y3); bar3dRight.lineTo((float) x2, (float) y1); bar3dRight.lineTo((float) x3, (float) y0); bar3dRight.lineTo((float) x3, (float) y2); bar3dRight.closePath(); if (itemPaint instanceof Color) { g2.setPaint(((Color) itemPaint).darker()); } g2.fill(bar3dRight); } bar3dTop = new GeneralPath(); bar3dTop.moveTo((float) x0, (float) y1); bar3dTop.lineTo((float) x1, (float) y0); bar3dTop.lineTo((float) x3, (float) y0); bar3dTop.lineTo((float) x2, (float) y1); bar3dTop.closePath(); g2.fill(bar3dTop); if (isDrawBarOutline() && state.getBarWidth() > BAR_OUTLINE_WIDTH_THRESHOLD) { g2.setStroke(getItemOutlineStroke(row, column)); g2.setPaint(getItemOutlinePaint(row, column)); g2.draw(bar); if (bar3dRight != null) { g2.draw(bar3dRight); } if (bar3dTop != null) { g2.draw(bar3dTop); } } CategoryItemLabelGenerator generator = getItemLabelGenerator(row, column); if (generator != null && isItemLabelVisible(row, column)) { drawItemLabel(g2, dataset, row, column, plot, generator, bar, (value < 0.0)); } // add an item entity, if this information is being collected EntityCollection entities = state.getEntityCollection(); if (entities != null) { GeneralPath barOutline = new GeneralPath(); barOutline.moveTo((float) x0, (float) y3); barOutline.lineTo((float) x0, (float) y1); barOutline.lineTo((float) x1, (float) y0); barOutline.lineTo((float) x3, (float) y0); barOutline.lineTo((float) x3, (float) y2); barOutline.lineTo((float) x2, (float) y3); barOutline.closePath(); addItemEntity(entities, dataset, row, column, barOutline); } } /** * Tests this renderer for equality with an arbitrary object. * * @param obj the object (<code>null</code> permitted). * * @return A boolean. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof BarRenderer3D)) { return false; } BarRenderer3D that = (BarRenderer3D) obj; if (this.xOffset != that.xOffset) { return false; } if (this.yOffset != that.yOffset) { return false; } if (!PaintUtilities.equal(this.wallPaint, that.wallPaint)) { return false; } return super.equals(obj); } /** * Provides serialization support. * * @param stream the output stream. * * @throws IOException if there is an I/O error. */ private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); SerialUtilities.writePaint(this.wallPaint, stream); } /** * Provides serialization support. * * @param stream the input stream. * * @throws IOException if there is an I/O error. * @throws ClassNotFoundException if there is a classpath problem. */ private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); this.wallPaint = SerialUtilities.readPaint(stream); } }
31,194
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
BarRenderer.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/renderer/category/BarRenderer.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ---------------- * BarRenderer.java * ---------------- * (C) Copyright 2002-2012, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): Christian W. Zuckschwerdt; * Peter Kolb (patches 2497611, 2791407); * * Changes * ------- * 14-Mar-2002 : Version 1 (DG); * 23-May-2002 : Added tooltip generator to renderer (DG); * 29-May-2002 : Moved tooltip generator to abstract super-class (DG); * 25-Jun-2002 : Changed constructor to protected and removed redundant * code (DG); * 26-Jun-2002 : Added axis to initialise method, and record upper and lower * clip values (DG); * 24-Sep-2002 : Added getLegendItem() method (DG); * 09-Oct-2002 : Modified constructor to include URL generator (DG); * 05-Nov-2002 : Base dataset is now TableDataset not CategoryDataset (DG); * 10-Jan-2003 : Moved get/setItemMargin() method up from subclasses (DG); * 17-Jan-2003 : Moved plot classes into a separate package (DG); * 25-Mar-2003 : Implemented Serializable (DG); * 01-May-2003 : Modified clipping to allow for dual axes and datasets (DG); * 12-May-2003 : Merged horizontal and vertical bar renderers (DG); * 12-Jun-2003 : Updates for item labels (DG); * 30-Jul-2003 : Modified entity constructor (CZ); * 02-Sep-2003 : Changed initialise method to fix bug 790407 (DG); * 16-Sep-2003 : Changed ChartRenderingInfo --> PlotRenderingInfo (DG); * 07-Oct-2003 : Added renderer state (DG); * 27-Oct-2003 : Merged drawHorizontalItem() and drawVerticalItem() * methods (DG); * 28-Oct-2003 : Added support for gradient paint on bars (DG); * 14-Nov-2003 : Added 'maxBarWidth' attribute (DG); * 10-Feb-2004 : Small changes inside drawItem() method to ease cut-and-paste * overriding (DG); * 19-Mar-2004 : Fixed bug introduced with separation of tool tip and item * label generators. Fixed equals() method (DG); * 11-May-2004 : Fix for null pointer exception (bug id 951127) (DG); * 05-Nov-2004 : Modified drawItem() signature (DG); * 26-Jan-2005 : Provided override for getLegendItem() method (DG); * 20-Apr-2005 : Generate legend labels, tooltips and URLs (DG); * 18-May-2005 : Added configurable base value (DG); * 09-Jun-2005 : Use addItemEntity() method from superclass (DG); * 01-Dec-2005 : Update legend item to use/not use outline (DG); * ------------: JFreeChart 1.0.x --------------------------------------------- * 06-Dec-2005 : Fixed bug 1374222 (JDK 1.4 specific code) (DG); * 11-Jan-2006 : Fixed bug 1401856 (bad rendering for non-zero base) (DG); * 04-Aug-2006 : Fixed bug 1467706 (missing item labels for zero value * bars) (DG); * 04-Dec-2006 : Fixed bug in rendering to non-primary axis (DG); * 13-Dec-2006 : Add support for GradientPaint display in legend items (DG); * 20-Apr-2007 : Updated getLegendItem() for renderer change (DG); * 11-May-2007 : Check for visibility in getLegendItem() (DG); * 17-May-2007 : Set datasetIndex and seriesIndex in getLegendItem() (DG); * 18-May-2007 : Set dataset and seriesKey for LegendItem (DG); * 07-May-2008 : If minimumBarLength is > 0.0, extend the non-base end of the * bar (DG); * 17-Jun-2008 : Apply legend shape, font and paint attributes (DG); * 24-Jun-2008 : Added barPainter mechanism (DG); * 26-Jun-2008 : Added crosshair support (DG); * 13-Aug-2008 : Added shadowPaint attribute (DG); * 14-Jan-2009 : Added support for seriesVisible flags (PK); * 03-Feb-2009 : Added defaultShadowsVisible flag - see patch 2511330 (PK); * 15-Jun-2012 : Removed JCommon dependencies (DG); * */ package org.jfree.chart.renderer.category; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Font; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.Shape; import java.awt.Stroke; import java.awt.geom.Line2D; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import org.jfree.chart.LegendItem; import org.jfree.chart.axis.CategoryAxis; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.ui.GradientPaintTransformer; import org.jfree.chart.ui.RectangleEdge; import org.jfree.chart.ui.StandardGradientPaintTransformer; import org.jfree.chart.util.ObjectUtilities; import org.jfree.chart.util.PaintUtilities; import org.jfree.chart.util.PublicCloneable; import org.jfree.chart.entity.EntityCollection; import org.jfree.chart.event.RendererChangeEvent; import org.jfree.chart.labels.CategoryItemLabelGenerator; import org.jfree.chart.labels.ItemLabelAnchor; import org.jfree.chart.labels.ItemLabelPosition; import org.jfree.chart.plot.CategoryPlot; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.PlotRenderingInfo; import org.jfree.chart.text.TextUtilities; import org.jfree.chart.util.SerialUtilities; import org.jfree.data.Range; import org.jfree.data.category.CategoryDataset; /** * A {@link CategoryItemRenderer} that draws individual data items as bars. * The example shown here is generated by the <code>BarChartDemo1.java</code> * program included in the JFreeChart Demo Collection: * <br><br> * <img src="../../../../../images/BarRendererSample.png" * alt="BarRendererSample.png" /> */ public class BarRenderer extends AbstractCategoryItemRenderer implements Cloneable, PublicCloneable, Serializable { /** For serialization. */ private static final long serialVersionUID = 6000649414965887481L; /** The default item margin percentage. */ public static final double DEFAULT_ITEM_MARGIN = 0.20; /** * Constant that controls the minimum width before a bar has an outline * drawn. */ public static final double BAR_OUTLINE_WIDTH_THRESHOLD = 3.0; /** * The default bar painter assigned to each new instance of this renderer. * * @since 1.0.11 */ private static BarPainter defaultBarPainter = new GradientBarPainter(); /** * Returns the default bar painter. * * @return The default bar painter. * * @since 1.0.11 */ public static BarPainter getDefaultBarPainter() { return BarRenderer.defaultBarPainter; } /** * Sets the default bar painter. * * @param painter the painter (<code>null</code> not permitted). * * @since 1.0.11 */ public static void setDefaultBarPainter(BarPainter painter) { if (painter == null) { throw new IllegalArgumentException("Null 'painter' argument."); } BarRenderer.defaultBarPainter = painter; } /** * The default value for the initialisation of the shadowsVisible flag. */ private static boolean defaultShadowsVisible = true; /** * Returns the default value for the <code>shadowsVisible</code> flag. * * @return A boolean. * * @see #setDefaultShadowsVisible(boolean) * * @since 1.0.13 */ public static boolean getDefaultShadowsVisible() { return BarRenderer.defaultShadowsVisible; } /** * Sets the default value for the shadows visible flag. * * @param visible the new value for the default. * * @see #getDefaultShadowsVisible() * * @since 1.0.13 */ public static void setDefaultShadowsVisible(boolean visible) { BarRenderer.defaultShadowsVisible = visible; } /** The margin between items (bars) within a category. */ private double itemMargin; /** A flag that controls whether or not bar outlines are drawn. */ private boolean drawBarOutline; /** The maximum bar width as a percentage of the available space. */ private double maximumBarWidth; /** The minimum bar length (in Java2D units). */ private double minimumBarLength; /** * An optional class used to transform gradient paint objects to fit each * bar. */ private GradientPaintTransformer gradientPaintTransformer; /** * The fallback position if a positive item label doesn't fit inside the * bar. */ private ItemLabelPosition positiveItemLabelPositionFallback; /** * The fallback position if a negative item label doesn't fit inside the * bar. */ private ItemLabelPosition negativeItemLabelPositionFallback; /** The upper clip (axis) value for the axis. */ private double upperClip; // TODO: this needs to move into the renderer state /** The lower clip (axis) value for the axis. */ private double lowerClip; // TODO: this needs to move into the renderer state /** The base value for the bars (defaults to 0.0). */ private double base; /** * A flag that controls whether the base value is included in the range * returned by the findRangeBounds() method. */ private boolean includeBaseInRange; /** * The bar painter (never <code>null</code>). * * @since 1.0.11 */ private BarPainter barPainter; /** * The flag that controls whether or not shadows are drawn for the bars. * * @since 1.0.11 */ private boolean shadowsVisible; /** * The shadow paint. * * @since 1.0.11 */ private transient Paint shadowPaint; /** * The x-offset for the shadow effect. * * @since 1.0.11 */ private double shadowXOffset; /** * The y-offset for the shadow effect. * * @since 1.0.11 */ private double shadowYOffset; /** * Creates a new bar renderer with default settings. */ public BarRenderer() { super(); this.base = 0.0; this.includeBaseInRange = true; this.itemMargin = DEFAULT_ITEM_MARGIN; this.drawBarOutline = false; this.maximumBarWidth = 1.0; // 100 percent, so it will not apply unless changed this.positiveItemLabelPositionFallback = null; this.negativeItemLabelPositionFallback = null; this.gradientPaintTransformer = new StandardGradientPaintTransformer(); this.minimumBarLength = 0.0; setDefaultLegendShape(new Rectangle2D.Double(-4.0, -4.0, 8.0, 8.0)); this.barPainter = getDefaultBarPainter(); this.shadowsVisible = getDefaultShadowsVisible(); this.shadowPaint = Color.GRAY; this.shadowXOffset = 4.0; this.shadowYOffset = 4.0; } /** * Returns the base value for the bars. The default value is * <code>0.0</code>. * * @return The base value for the bars. * * @see #setBase(double) */ public double getBase() { return this.base; } /** * Sets the base value for the bars and sends a {@link RendererChangeEvent} * to all registered listeners. * * @param base the new base value. * * @see #getBase() */ public void setBase(double base) { this.base = base; fireChangeEvent(); } /** * Returns the item margin as a percentage of the available space for all * bars. * * @return The margin percentage (where 0.10 is ten percent). * * @see #setItemMargin(double) */ public double getItemMargin() { return this.itemMargin; } /** * Sets the item margin and sends a {@link RendererChangeEvent} to all * registered listeners. The value is expressed as a percentage of the * available width for plotting all the bars, with the resulting amount to * be distributed between all the bars evenly. * * @param percent the margin (where 0.10 is ten percent). * * @see #getItemMargin() */ public void setItemMargin(double percent) { this.itemMargin = percent; fireChangeEvent(); } /** * Returns a flag that controls whether or not bar outlines are drawn. * * @return A boolean. * * @see #setDrawBarOutline(boolean) */ public boolean isDrawBarOutline() { return this.drawBarOutline; } /** * Sets the flag that controls whether or not bar outlines are drawn and * sends a {@link RendererChangeEvent} to all registered listeners. * * @param draw the flag. * * @see #isDrawBarOutline() */ public void setDrawBarOutline(boolean draw) { this.drawBarOutline = draw; fireChangeEvent(); } /** * Returns the maximum bar width, as a percentage of the available drawing * space. * * @return The maximum bar width. * * @see #setMaximumBarWidth(double) */ public double getMaximumBarWidth() { return this.maximumBarWidth; } /** * Sets the maximum bar width, which is specified as a percentage of the * available space for all bars, and sends a {@link RendererChangeEvent} to * all registered listeners. * * @param percent the percent (where 0.05 is five percent). * * @see #getMaximumBarWidth() */ public void setMaximumBarWidth(double percent) { this.maximumBarWidth = percent; fireChangeEvent(); } /** * Returns the minimum bar length (in Java2D units). The default value is * 0.0. * * @return The minimum bar length. * * @see #setMinimumBarLength(double) */ public double getMinimumBarLength() { return this.minimumBarLength; } /** * Sets the minimum bar length and sends a {@link RendererChangeEvent} to * all registered listeners. The minimum bar length is specified in Java2D * units, and can be used to prevent bars that represent very small data * values from disappearing when drawn on the screen. Typically you would * set this to (say) 0.5 or 1.0 Java 2D units. Use this attribute with * caution, however, because setting it to a non-zero value will * artificially increase the length of bars representing small values, * which may misrepresent your data. * * @param min the minimum bar length (in Java2D units, must be >= 0.0). * * @see #getMinimumBarLength() */ public void setMinimumBarLength(double min) { if (min < 0.0) { throw new IllegalArgumentException("Requires 'min' >= 0.0"); } this.minimumBarLength = min; fireChangeEvent(); } /** * Returns the gradient paint transformer (an object used to transform * gradient paint objects to fit each bar). * * @return A transformer (<code>null</code> possible). * * @see #setGradientPaintTransformer(GradientPaintTransformer) */ public GradientPaintTransformer getGradientPaintTransformer() { return this.gradientPaintTransformer; } /** * Sets the gradient paint transformer and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param transformer the transformer (<code>null</code> permitted). * * @see #getGradientPaintTransformer() */ public void setGradientPaintTransformer( GradientPaintTransformer transformer) { this.gradientPaintTransformer = transformer; fireChangeEvent(); } /** * Returns the fallback position for positive item labels that don't fit * within a bar. * * @return The fallback position (<code>null</code> possible). * * @see #setPositiveItemLabelPositionFallback(ItemLabelPosition) */ public ItemLabelPosition getPositiveItemLabelPositionFallback() { return this.positiveItemLabelPositionFallback; } /** * Sets the fallback position for positive item labels that don't fit * within a bar, and sends a {@link RendererChangeEvent} to all registered * listeners. * * @param position the position (<code>null</code> permitted). * * @see #getPositiveItemLabelPositionFallback() */ public void setPositiveItemLabelPositionFallback( ItemLabelPosition position) { this.positiveItemLabelPositionFallback = position; fireChangeEvent(); } /** * Returns the fallback position for negative item labels that don't fit * within a bar. * * @return The fallback position (<code>null</code> possible). * * @see #setPositiveItemLabelPositionFallback(ItemLabelPosition) */ public ItemLabelPosition getNegativeItemLabelPositionFallback() { return this.negativeItemLabelPositionFallback; } /** * Sets the fallback position for negative item labels that don't fit * within a bar, and sends a {@link RendererChangeEvent} to all registered * listeners. * * @param position the position (<code>null</code> permitted). * * @see #getNegativeItemLabelPositionFallback() */ public void setNegativeItemLabelPositionFallback( ItemLabelPosition position) { this.negativeItemLabelPositionFallback = position; fireChangeEvent(); } /** * Returns the flag that controls whether or not the base value for the * bars is included in the range calculated by * {@link #findRangeBounds(CategoryDataset)}. * * @return <code>true</code> if the base is included in the range, and * <code>false</code> otherwise. * * @since 1.0.1 * * @see #setIncludeBaseInRange(boolean) */ public boolean getIncludeBaseInRange() { return this.includeBaseInRange; } /** * Sets the flag that controls whether or not the base value for the bars * is included in the range calculated by * {@link #findRangeBounds(CategoryDataset)}. If the flag is changed, * a {@link RendererChangeEvent} is sent to all registered listeners. * * @param include the new value for the flag. * * @since 1.0.1 * * @see #getIncludeBaseInRange() */ public void setIncludeBaseInRange(boolean include) { if (this.includeBaseInRange != include) { this.includeBaseInRange = include; fireChangeEvent(); } } /** * Returns the bar painter. * * @return The bar painter (never <code>null</code>). * * @see #setBarPainter(BarPainter) * * @since 1.0.11 */ public BarPainter getBarPainter() { return this.barPainter; } /** * Sets the bar painter for this renderer and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param painter the painter (<code>null</code> not permitted). * * @see #getBarPainter() * * @since 1.0.11 */ public void setBarPainter(BarPainter painter) { if (painter == null) { throw new IllegalArgumentException("Null 'painter' argument."); } this.barPainter = painter; fireChangeEvent(); } /** * Returns the flag that controls whether or not shadows are drawn for * the bars. * * @return A boolean. * * @since 1.0.11 */ public boolean getShadowsVisible() { return this.shadowsVisible; } /** * Sets the flag that controls whether or not shadows are * drawn by the renderer. * * @param visible the new flag value. * * @since 1.0.11 */ public void setShadowVisible(boolean visible) { this.shadowsVisible = visible; fireChangeEvent(); } /** * Returns the shadow paint. * * @return The shadow paint. * * @see #setShadowPaint(Paint) * * @since 1.0.11 */ public Paint getShadowPaint() { return this.shadowPaint; } /** * Sets the shadow paint and sends a {@link RendererChangeEvent} to all * registered listeners. * * @param paint the paint (<code>null</code> not permitted). * * @see #getShadowPaint() * * @since 1.0.11 */ public void setShadowPaint(Paint paint) { if (paint == null) { throw new IllegalArgumentException("Null 'paint' argument."); } this.shadowPaint = paint; fireChangeEvent(); } /** * Returns the shadow x-offset. * * @return The shadow x-offset. * * @since 1.0.11 */ public double getShadowXOffset() { return this.shadowXOffset; } /** * Sets the x-offset for the bar shadow and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param offset the offset. * * @since 1.0.11 */ public void setShadowXOffset(double offset) { this.shadowXOffset = offset; fireChangeEvent(); } /** * Returns the shadow y-offset. * * @return The shadow y-offset. * * @since 1.0.11 */ public double getShadowYOffset() { return this.shadowYOffset; } /** * Sets the y-offset for the bar shadow and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param offset the offset. * * @since 1.0.11 */ public void setShadowYOffset(double offset) { this.shadowYOffset = offset; fireChangeEvent(); } /** * Returns the lower clip value. This value is recalculated in the * initialise() method. * * @return The value. */ public double getLowerClip() { // TODO: this attribute should be transferred to the renderer state. return this.lowerClip; } /** * Returns the upper clip value. This value is recalculated in the * initialise() method. * * @return The value. */ public double getUpperClip() { // TODO: this attribute should be transferred to the renderer state. return this.upperClip; } /** * Initialises the renderer and returns a state object that will be passed * to subsequent calls to the drawItem method. This method gets called * once at the start of the process of drawing a chart. * * @param g2 the graphics device. * @param dataArea the area in which the data is to be plotted. * @param plot the plot. * @param rendererIndex the renderer index. * @param info collects chart rendering information for return to caller. * * @return The renderer state. */ @Override public CategoryItemRendererState initialise(Graphics2D g2, Rectangle2D dataArea, CategoryPlot plot, int rendererIndex, PlotRenderingInfo info) { CategoryItemRendererState state = super.initialise(g2, dataArea, plot, rendererIndex, info); // get the clipping values... ValueAxis rangeAxis = plot.getRangeAxisForDataset(rendererIndex); this.lowerClip = rangeAxis.getRange().getLowerBound(); this.upperClip = rangeAxis.getRange().getUpperBound(); // calculate the bar width calculateBarWidth(plot, dataArea, rendererIndex, state); return state; } /** * Calculates the bar width and stores it in the renderer state. * * @param plot the plot. * @param dataArea the data area. * @param rendererIndex the renderer index. * @param state the renderer state. */ protected void calculateBarWidth(CategoryPlot plot, Rectangle2D dataArea, int rendererIndex, CategoryItemRendererState state) { CategoryAxis domainAxis = getDomainAxis(plot, rendererIndex); CategoryDataset dataset = plot.getDataset(rendererIndex); if (dataset != null) { int columns = dataset.getColumnCount(); int rows = state.getVisibleSeriesCount() >= 0 ? state.getVisibleSeriesCount() : dataset.getRowCount(); double space = 0.0; PlotOrientation orientation = plot.getOrientation(); if (orientation == PlotOrientation.HORIZONTAL) { space = dataArea.getHeight(); } else if (orientation == PlotOrientation.VERTICAL) { space = dataArea.getWidth(); } double maxWidth = space * getMaximumBarWidth(); double categoryMargin = 0.0; double currentItemMargin = 0.0; if (columns > 1) { categoryMargin = domainAxis.getCategoryMargin(); } if (rows > 1) { currentItemMargin = getItemMargin(); } double used = space * (1 - domainAxis.getLowerMargin() - domainAxis.getUpperMargin() - categoryMargin - currentItemMargin); if ((rows * columns) > 0) { state.setBarWidth(Math.min(used / (rows * columns), maxWidth)); } else { state.setBarWidth(Math.min(used, maxWidth)); } } } /** * Calculates the coordinate of the first "side" of a bar. This will be * the minimum x-coordinate for a vertical bar, and the minimum * y-coordinate for a horizontal bar. * * @param plot the plot. * @param orientation the plot orientation. * @param dataArea the data area. * @param domainAxis the domain axis. * @param state the renderer state (has the bar width precalculated). * @param row the row index. * @param column the column index. * * @return The coordinate. */ protected double calculateBarW0(CategoryPlot plot, PlotOrientation orientation, Rectangle2D dataArea, CategoryAxis domainAxis, CategoryItemRendererState state, int row, int column) { // calculate bar width... double space; if (orientation == PlotOrientation.HORIZONTAL) { space = dataArea.getHeight(); } else { space = dataArea.getWidth(); } double barW0 = domainAxis.getCategoryStart(column, getColumnCount(), dataArea, plot.getDomainAxisEdge()); int seriesCount = state.getVisibleSeriesCount() >= 0 ? state.getVisibleSeriesCount() : getRowCount(); int categoryCount = getColumnCount(); if (seriesCount > 1) { double seriesGap = space * getItemMargin() / (categoryCount * (seriesCount - 1)); double seriesW = calculateSeriesWidth(space, domainAxis, categoryCount, seriesCount); barW0 = barW0 + row * (seriesW + seriesGap) + (seriesW / 2.0) - (state.getBarWidth() / 2.0); } else { barW0 = domainAxis.getCategoryMiddle(column, getColumnCount(), dataArea, plot.getDomainAxisEdge()) - state.getBarWidth() / 2.0; } return barW0; } /** * Calculates the coordinates for the length of a single bar. * * @param value the value represented by the bar. * * @return The coordinates for each end of the bar (or <code>null</code> if * the bar is not visible for the current axis range). */ protected double[] calculateBarL0L1(double value) { double lclip = getLowerClip(); double uclip = getUpperClip(); double barLow = Math.min(this.base, value); double barHigh = Math.max(this.base, value); if (barHigh < lclip) { // bar is not visible return null; } if (barLow > uclip) { // bar is not visible return null; } barLow = Math.max(barLow, lclip); barHigh = Math.min(barHigh, uclip); return new double[] {barLow, barHigh}; } /** * Returns the range of values the renderer requires to display all the * items from the specified dataset. This takes into account the range * of values in the dataset, plus the flag that determines whether or not * the base value for the bars should be included in the range. * * @param dataset the dataset (<code>null</code> permitted). * @param includeInterval include the interval if the dataset has one? * * @return The range (or <code>null</code> if the dataset is * <code>null</code> or empty). */ @Override public Range findRangeBounds(CategoryDataset dataset, boolean includeInterval) { if (dataset == null) { return null; } Range result = super.findRangeBounds(dataset, includeInterval); if (result != null) { if (this.includeBaseInRange) { result = Range.expandToInclude(result, this.base); } } return result; } /** * Returns a legend item for a series. * * @param datasetIndex the dataset index (zero-based). * @param series the series index (zero-based). * * @return The legend item (possibly <code>null</code>). */ @Override public LegendItem getLegendItem(int datasetIndex, int series) { CategoryPlot cp = getPlot(); if (cp == null) { return null; } // check that a legend item needs to be displayed... if (!isSeriesVisible(series) || !isSeriesVisibleInLegend(series)) { return null; } CategoryDataset dataset = cp.getDataset(datasetIndex); String label = getLegendItemLabelGenerator().generateLabel(dataset, series); String description = label; String toolTipText = null; if (getLegendItemToolTipGenerator() != null) { toolTipText = getLegendItemToolTipGenerator().generateLabel( dataset, series); } String urlText = null; if (getLegendItemURLGenerator() != null) { urlText = getLegendItemURLGenerator().generateLabel(dataset, series); } Shape shape = lookupLegendShape(series); Paint paint = lookupSeriesPaint(series); Paint outlinePaint = lookupSeriesOutlinePaint(series); Stroke outlineStroke = lookupSeriesOutlineStroke(series); LegendItem result = new LegendItem(label, description, toolTipText, urlText, true, shape, true, paint, isDrawBarOutline(), outlinePaint, outlineStroke, false, new Line2D.Float(), new BasicStroke(1.0f), Color.BLACK); result.setLabelFont(lookupLegendTextFont(series)); Paint labelPaint = lookupLegendTextPaint(series); if (labelPaint != null) { result.setLabelPaint(labelPaint); } result.setDataset(dataset); result.setDatasetIndex(datasetIndex); result.setSeriesKey(dataset.getRowKey(series)); result.setSeriesIndex(series); if (this.gradientPaintTransformer != null) { result.setFillPaintTransformer(this.gradientPaintTransformer); } return result; } /** * Draws the bar for a single (series, category) data item. * * @param g2 the graphics device. * @param state the renderer state. * @param dataArea the data area. * @param plot the plot. * @param domainAxis the domain axis. * @param rangeAxis the range axis. * @param dataset the dataset. * @param row the row index (zero-based). * @param column the column index (zero-based). * @param pass the pass index. */ @Override public void drawItem(Graphics2D g2, CategoryItemRendererState state, Rectangle2D dataArea, CategoryPlot plot, CategoryAxis domainAxis, ValueAxis rangeAxis, CategoryDataset dataset, int row, int column, int pass) { // nothing is drawn if the row index is not included in the list with // the indices of the visible rows... int visibleRow = state.getVisibleSeriesIndex(row); if (visibleRow < 0) { return; } // nothing is drawn for null values... Number dataValue = dataset.getValue(row, column); if (dataValue == null) { return; } final double value = dataValue.doubleValue(); PlotOrientation orientation = plot.getOrientation(); double barW0 = calculateBarW0(plot, orientation, dataArea, domainAxis, state, visibleRow, column); double[] barL0L1 = calculateBarL0L1(value); if (barL0L1 == null) { return; // the bar is not visible } RectangleEdge edge = plot.getRangeAxisEdge(); double transL0 = rangeAxis.valueToJava2D(barL0L1[0], dataArea, edge); double transL1 = rangeAxis.valueToJava2D(barL0L1[1], dataArea, edge); // in the following code, barL0 is (in Java2D coordinates) the LEFT // end of the bar for a horizontal bar chart, and the TOP end of the // bar for a vertical bar chart. Whether this is the BASE of the bar // or not depends also on (a) whether the data value is 'negative' // relative to the base value and (b) whether or not the range axis is // inverted. This only matters if/when we apply the minimumBarLength // attribute, because we should extend the non-base end of the bar boolean positive = (value >= this.base); boolean inverted = rangeAxis.isInverted(); double barL0 = Math.min(transL0, transL1); double barLength = Math.abs(transL1 - transL0); double barLengthAdj = 0.0; if (barLength > 0.0 && barLength < getMinimumBarLength()) { barLengthAdj = getMinimumBarLength() - barLength; } double barL0Adj = 0.0; RectangleEdge barBase; if (orientation == PlotOrientation.HORIZONTAL) { if (positive && inverted || !positive && !inverted) { barL0Adj = barLengthAdj; barBase = RectangleEdge.RIGHT; } else { barBase = RectangleEdge.LEFT; } } else { if (positive && !inverted || !positive && inverted) { barL0Adj = barLengthAdj; barBase = RectangleEdge.BOTTOM; } else { barBase = RectangleEdge.TOP; } } // draw the bar... Rectangle2D bar; if (orientation == PlotOrientation.HORIZONTAL) { bar = new Rectangle2D.Double(barL0 - barL0Adj, barW0, barLength + barLengthAdj, state.getBarWidth()); } else { bar = new Rectangle2D.Double(barW0, barL0 - barL0Adj, state.getBarWidth(), barLength + barLengthAdj); } if (getShadowsVisible()) { this.barPainter.paintBarShadow(g2, this, row, column, bar, barBase, true); } this.barPainter.paintBar(g2, this, row, column, bar, barBase); CategoryItemLabelGenerator generator = getItemLabelGenerator(row, column); if (generator != null && isItemLabelVisible(row, column)) { drawItemLabel(g2, dataset, row, column, plot, generator, bar, (value < 0.0)); } // submit the current data point as a crosshair candidate int datasetIndex = plot.indexOf(dataset); updateCrosshairValues(state.getCrosshairState(), dataset.getRowKey(row), dataset.getColumnKey(column), value, datasetIndex, barW0, barL0, orientation); // add an item entity, if this information is being collected EntityCollection entities = state.getEntityCollection(); if (entities != null) { addItemEntity(entities, dataset, row, column, bar); } } /** * Calculates the available space for each series. * * @param space the space along the entire axis (in Java2D units). * @param axis the category axis. * @param categories the number of categories. * @param series the number of series. * * @return The width of one series. */ protected double calculateSeriesWidth(double space, CategoryAxis axis, int categories, int series) { double factor = 1.0 - getItemMargin() - axis.getLowerMargin() - axis.getUpperMargin(); if (categories > 1) { factor = factor - axis.getCategoryMargin(); } return (space * factor) / (categories * series); } /** * Draws an item label. This method is overridden so that the bar can be * used to calculate the label anchor point. * * @param g2 the graphics device. * @param data the dataset. * @param row the row. * @param column the column. * @param plot the plot. * @param generator the label generator. * @param bar the bar. * @param negative a flag indicating a negative value. */ protected void drawItemLabel(Graphics2D g2, CategoryDataset data, int row, int column, CategoryPlot plot, CategoryItemLabelGenerator generator, Rectangle2D bar, boolean negative) { String label = generator.generateLabel(data, row, column); if (label == null) { return; // nothing to do } Font labelFont = getItemLabelFont(row, column); g2.setFont(labelFont); Paint paint = getItemLabelPaint(row, column); g2.setPaint(paint); // find out where to place the label... ItemLabelPosition position; if (!negative) { position = getPositiveItemLabelPosition(row, column); } else { position = getNegativeItemLabelPosition(row, column); } // work out the label anchor point... Point2D anchorPoint = calculateLabelAnchorPoint( position.getItemLabelAnchor(), bar, plot.getOrientation()); if (isInternalAnchor(position.getItemLabelAnchor())) { Shape bounds = TextUtilities.calculateRotatedStringBounds(label, g2, (float) anchorPoint.getX(), (float) anchorPoint.getY(), position.getTextAnchor(), position.getAngle(), position.getRotationAnchor()); if (bounds != null) { if (!bar.contains(bounds.getBounds2D())) { if (!negative) { position = getPositiveItemLabelPositionFallback(); } else { position = getNegativeItemLabelPositionFallback(); } if (position != null) { anchorPoint = calculateLabelAnchorPoint( position.getItemLabelAnchor(), bar, plot.getOrientation()); } } } } if (position != null) { TextUtilities.drawRotatedString(label, g2, (float) anchorPoint.getX(), (float) anchorPoint.getY(), position.getTextAnchor(), position.getAngle(), position.getRotationAnchor()); } } /** * Calculates the item label anchor point. * * @param anchor the anchor. * @param bar the bar. * @param orientation the plot orientation. * * @return The anchor point. */ private Point2D calculateLabelAnchorPoint(ItemLabelAnchor anchor, Rectangle2D bar, PlotOrientation orientation) { Point2D result = null; double offset = getItemLabelAnchorOffset(); double x0 = bar.getX() - offset; double x1 = bar.getX(); double x2 = bar.getX() + offset; double x3 = bar.getCenterX(); double x4 = bar.getMaxX() - offset; double x5 = bar.getMaxX(); double x6 = bar.getMaxX() + offset; double y0 = bar.getMaxY() + offset; double y1 = bar.getMaxY(); double y2 = bar.getMaxY() - offset; double y3 = bar.getCenterY(); double y4 = bar.getMinY() + offset; double y5 = bar.getMinY(); double y6 = bar.getMinY() - offset; if (anchor == ItemLabelAnchor.CENTER) { result = new Point2D.Double(x3, y3); } else if (anchor == ItemLabelAnchor.INSIDE1) { result = new Point2D.Double(x4, y4); } else if (anchor == ItemLabelAnchor.INSIDE2) { result = new Point2D.Double(x4, y4); } else if (anchor == ItemLabelAnchor.INSIDE3) { result = new Point2D.Double(x4, y3); } else if (anchor == ItemLabelAnchor.INSIDE4) { result = new Point2D.Double(x4, y2); } else if (anchor == ItemLabelAnchor.INSIDE5) { result = new Point2D.Double(x4, y2); } else if (anchor == ItemLabelAnchor.INSIDE6) { result = new Point2D.Double(x3, y2); } else if (anchor == ItemLabelAnchor.INSIDE7) { result = new Point2D.Double(x2, y2); } else if (anchor == ItemLabelAnchor.INSIDE8) { result = new Point2D.Double(x2, y2); } else if (anchor == ItemLabelAnchor.INSIDE9) { result = new Point2D.Double(x2, y3); } else if (anchor == ItemLabelAnchor.INSIDE10) { result = new Point2D.Double(x2, y4); } else if (anchor == ItemLabelAnchor.INSIDE11) { result = new Point2D.Double(x2, y4); } else if (anchor == ItemLabelAnchor.INSIDE12) { result = new Point2D.Double(x3, y4); } else if (anchor == ItemLabelAnchor.OUTSIDE1) { result = new Point2D.Double(x5, y6); } else if (anchor == ItemLabelAnchor.OUTSIDE2) { result = new Point2D.Double(x6, y5); } else if (anchor == ItemLabelAnchor.OUTSIDE3) { result = new Point2D.Double(x6, y3); } else if (anchor == ItemLabelAnchor.OUTSIDE4) { result = new Point2D.Double(x6, y1); } else if (anchor == ItemLabelAnchor.OUTSIDE5) { result = new Point2D.Double(x5, y0); } else if (anchor == ItemLabelAnchor.OUTSIDE6) { result = new Point2D.Double(x3, y0); } else if (anchor == ItemLabelAnchor.OUTSIDE7) { result = new Point2D.Double(x1, y0); } else if (anchor == ItemLabelAnchor.OUTSIDE8) { result = new Point2D.Double(x0, y1); } else if (anchor == ItemLabelAnchor.OUTSIDE9) { result = new Point2D.Double(x0, y3); } else if (anchor == ItemLabelAnchor.OUTSIDE10) { result = new Point2D.Double(x0, y5); } else if (anchor == ItemLabelAnchor.OUTSIDE11) { result = new Point2D.Double(x1, y6); } else if (anchor == ItemLabelAnchor.OUTSIDE12) { result = new Point2D.Double(x3, y6); } return result; } /** * Returns <code>true</code> if the specified anchor point is inside a bar. * * @param anchor the anchor point. * * @return A boolean. */ private boolean isInternalAnchor(ItemLabelAnchor anchor) { return anchor == ItemLabelAnchor.CENTER || anchor == ItemLabelAnchor.INSIDE1 || anchor == ItemLabelAnchor.INSIDE2 || anchor == ItemLabelAnchor.INSIDE3 || anchor == ItemLabelAnchor.INSIDE4 || anchor == ItemLabelAnchor.INSIDE5 || anchor == ItemLabelAnchor.INSIDE6 || anchor == ItemLabelAnchor.INSIDE7 || anchor == ItemLabelAnchor.INSIDE8 || anchor == ItemLabelAnchor.INSIDE9 || anchor == ItemLabelAnchor.INSIDE10 || anchor == ItemLabelAnchor.INSIDE11 || anchor == ItemLabelAnchor.INSIDE12; } /** * Tests this instance for equality with an arbitrary object. * * @param obj the object (<code>null</code> permitted). * * @return A boolean. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof BarRenderer)) { return false; } BarRenderer that = (BarRenderer) obj; if (this.base != that.base) { return false; } if (this.itemMargin != that.itemMargin) { return false; } if (this.drawBarOutline != that.drawBarOutline) { return false; } if (this.maximumBarWidth != that.maximumBarWidth) { return false; } if (this.minimumBarLength != that.minimumBarLength) { return false; } if (!ObjectUtilities.equal(this.gradientPaintTransformer, that.gradientPaintTransformer)) { return false; } if (!ObjectUtilities.equal(this.positiveItemLabelPositionFallback, that.positiveItemLabelPositionFallback)) { return false; } if (!ObjectUtilities.equal(this.negativeItemLabelPositionFallback, that.negativeItemLabelPositionFallback)) { return false; } if (!this.barPainter.equals(that.barPainter)) { return false; } if (this.shadowsVisible != that.shadowsVisible) { return false; } if (!PaintUtilities.equal(this.shadowPaint, that.shadowPaint)) { return false; } if (this.shadowXOffset != that.shadowXOffset) { return false; } if (this.shadowYOffset != that.shadowYOffset) { return false; } return super.equals(obj); } /** * Provides serialization support. * * @param stream the output stream. * * @throws IOException if there is an I/O error. */ private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); SerialUtilities.writePaint(this.shadowPaint, stream); } /** * Provides serialization support. * * @param stream the input stream. * * @throws IOException if there is an I/O error. * @throws ClassNotFoundException if there is a classpath problem. */ private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); this.shadowPaint = SerialUtilities.readPaint(stream); } }
49,102
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
CategoryItemRendererState.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/renderer/category/CategoryItemRendererState.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ------------------------------ * CategoryItemRendererState.java * ------------------------------ * (C) Copyright 2003-2009, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): Peter Kolb (patch 2497611); * * Changes (since 20-Oct-2003): * ---------------------------- * 20-Oct-2003 : Added series running total (DG); * ------------- JFREECHART 1.0.x --------------------------------------------- * 01-Dec-2006 : Updated API docs (DG); * 26-Jun-2008 : Added CrosshairState (DG); * 14-Jan-2009 : Added visibleSeries[] array (PK); * 04-Feb-2009 : Added getVisibleSeriesArray() method (DG); * */ package org.jfree.chart.renderer.category; import org.jfree.chart.plot.CategoryCrosshairState; import org.jfree.chart.plot.PlotRenderingInfo; import org.jfree.chart.renderer.RendererState; /** * An object that retains temporary state information for a * {@link CategoryItemRenderer}. */ public class CategoryItemRendererState extends RendererState { /** The bar width. */ private double barWidth; /** The series running total. */ private double seriesRunningTotal; /** The array with the indices of the visible series.*/ private int[] visibleSeries; /** * State information for crosshairs in the plot (this is updated by the * renderer, but may be passed to several renderers in one chart). * * @since 1.0.11 */ private CategoryCrosshairState crosshairState; /** * Creates a new object for recording temporary state information for a * renderer. * * @param info the plot rendering info (<code>null</code> permitted). */ public CategoryItemRendererState(PlotRenderingInfo info) { super(info); this.barWidth = 0.0; this.seriesRunningTotal = 0.0; } /** * Returns the bar width. * * @return The bar width. * * @see #setBarWidth(double) */ public double getBarWidth() { return this.barWidth; } /** * Sets the bar width. The renderer calculates this value and stores it * here - it is not intended that users can manually set the bar width. * * @param width the width. * * @see #getBarWidth() */ public void setBarWidth(double width) { this.barWidth = width; } /** * Returns the series running total. * * @return The running total. * * @see #setSeriesRunningTotal(double) */ public double getSeriesRunningTotal() { return this.seriesRunningTotal; } /** * Sets the series running total (this method is intended for the use of * the renderer only). * * @param total the new total. * * @see #getSeriesRunningTotal() */ void setSeriesRunningTotal(double total) { this.seriesRunningTotal = total; } /** * Returns the crosshair state, if any. * * @return The crosshair state (possibly <code>null</code>). * * @since 1.0.11 * * @see #setCrosshairState(CategoryCrosshairState) */ public CategoryCrosshairState getCrosshairState() { return this.crosshairState; } /** * Sets the crosshair state. * * @param state the new state (<code>null</code> permitted). * * @since 1.0.11 * * @see #getCrosshairState() */ public void setCrosshairState(CategoryCrosshairState state) { this.crosshairState = state; } /** * Returns the index of the row relative to the visible rows. If no * visible rows have been specified, the original row index is returned. * If the row index is not included in the array of visible rows, * -1 is returned. * * @param rowIndex the row index. * * @return The new row index or -1. * * @since 1.0.13 */ public int getVisibleSeriesIndex(int rowIndex) { if (this.visibleSeries == null) { return rowIndex; } int index = -1; for (int vRow = 0; vRow < this.visibleSeries.length; vRow++) { if (this.visibleSeries[vRow] == rowIndex) { index = vRow; break; } } return index; } /** * Returns the number of visible series or -1 if no visible series have * been specified. * * @return The number or -1. * * @since 1.0.13 */ public int getVisibleSeriesCount() { if (this.visibleSeries == null) { return -1; } return this.visibleSeries.length; } /** * Returns a copy of the visible series array. * * @return The visible series array (possibly <code>null</code>). * * @since 1.0.13 */ public int[] getVisibleSeriesArray() { if (this.visibleSeries == null) { return null; } int[] result = new int[this.visibleSeries.length]; System.arraycopy(this.visibleSeries, 0, result, 0, this.visibleSeries.length); return result; } /** * Sets an array with the indices of the visible rows. * * @param visibleSeries the array (<code>null</code> permitted). * * @since 1.0.13 */ public void setVisibleSeriesArray(int[] visibleSeries) { this.visibleSeries = visibleSeries; } }
6,654
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
StackedBarRenderer3D.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/renderer/category/StackedBarRenderer3D.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ------------------------- * StackedBarRenderer3D.java * ------------------------- * (C) Copyright 2000-2012, by Serge V. Grachov and Contributors. * * Original Author: Serge V. Grachov; * Contributor(s): David Gilbert (for Object Refinery Limited); * Richard Atkinson; * Christian W. Zuckschwerdt; * Max Herfort (patch 1459313); * * Changes * ------- * 31-Oct-2001 : Version 1, contributed by Serge V. Grachov (DG); * 15-Nov-2001 : Modified to allow for null data values (DG); * 13-Dec-2001 : Added tooltips (DG); * 15-Feb-2002 : Added isStacked() method (DG); * 24-May-2002 : Incorporated tooltips into chart entities (DG); * 19-Jun-2002 : Added check for null info in drawCategoryItem method (DG); * 25-Jun-2002 : Removed redundant imports (DG); * 26-Jun-2002 : Small change to entity (DG); * 05-Aug-2002 : Small modification to drawCategoryItem method to support URLs * for HTML image maps (RA); * 26-Sep-2002 : Fixed errors reported by Checkstyle (DG); * 24-Oct-2002 : Amendments for changes in CategoryDataset interface and * CategoryToolTipGenerator interface (DG); * 05-Nov-2002 : Replaced references to CategoryDataset with TableDataset (DG); * 26-Nov-2002 : Replaced isStacked() method with getRangeType() method (DG); * 17-Jan-2003 : Moved plot classes to a separate package (DG); * 25-Mar-2003 : Implemented Serializable (DG); * 01-May-2003 : Added default constructor (bug 726235) and fixed bug * 726260) (DG); * 13-May-2003 : Renamed StackedVerticalBarRenderer3D * --> StackedBarRenderer3D (DG); * 30-Jul-2003 : Modified entity constructor (CZ); * 07-Oct-2003 : Added renderer state (DG); * 21-Nov-2003 : Added a new constructor (DG); * 27-Nov-2003 : Modified code to respect maxBarWidth setting (DG); * 11-Aug-2004 : Fixed bug where isDrawBarOutline() was ignored (DG); * 05-Nov-2004 : Modified drawItem() signature (DG); * 07-Jan-2005 : Renamed getRangeExtent() --> findRangeBounds (DG); * 18-Mar-2005 : Override for getPassCount() method (DG); * 20-Apr-2005 : Renamed CategoryLabelGenerator * --> CategoryItemLabelGenerator (DG); * 09-Jun-2005 : Use addItemEntity() method from superclass (DG); * 22-Sep-2005 : Renamed getMaxBarWidth() --> getMaximumBarWidth() (DG); * ------------- JFREECHART 1.0.x --------------------------------------------- * 31-Mar-2006 : Added renderAsPercentages option - see patch 1459313 submitted * by Max Herfort (DG); * 16-Jan-2007 : Replaced rendering code to draw whole stack at once (DG); * 18-Jan-2007 : Fixed bug handling null values in createStackedValueList() * method (DG); * 18-Jan-2007 : Updated block drawing code to take account of inverted axes, * see bug report 1599652 (DG); * 08-May-2007 : Fixed bugs 1713401 (drawBarOutlines flag) and 1713474 * (shading) (DG); * 15-Aug-2008 : Fixed bug 2031407 - no negative zero for stack encoding (DG); * 03-Feb-2009 : Fixed regression in findRangeBounds() method for null * dataset (DG); * 04-Feb-2009 : Handle seriesVisible flag (DG); * 07-Jul-2009 : Added flag for handling zero values (DG); * 15-Jun-2012 : Removed JCommon dependencies (DG); * */ package org.jfree.chart.renderer.category; import java.awt.Color; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.Shape; import java.awt.geom.GeneralPath; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import org.jfree.chart.HashUtilities; import org.jfree.chart.axis.CategoryAxis; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.util.PublicCloneable; import org.jfree.chart.entity.EntityCollection; import org.jfree.chart.event.RendererChangeEvent; import org.jfree.chart.labels.CategoryItemLabelGenerator; import org.jfree.chart.plot.CategoryPlot; import org.jfree.chart.plot.PlotOrientation; import org.jfree.data.DataUtilities; import org.jfree.data.Range; import org.jfree.data.category.CategoryDataset; import org.jfree.data.general.DatasetUtilities; /** * Renders stacked bars with 3D-effect, for use with the {@link CategoryPlot} * class. The example shown here is generated by the * <code>StackedBarChart3DDemo1.java</code> program included in the * JFreeChart Demo Collection: * <br><br> * <img src="../../../../../images/StackedBarRenderer3DSample.png" * alt="StackedBarRenderer3DSample.png" /> */ public class StackedBarRenderer3D extends BarRenderer3D implements Cloneable, PublicCloneable, Serializable { /** For serialization. */ private static final long serialVersionUID = -5832945916493247123L; /** A flag that controls whether the bars display values or percentages. */ private boolean renderAsPercentages; /** * A flag that controls whether or not zero values are drawn by the * renderer. * * @since 1.0.14 */ private boolean ignoreZeroValues; /** * Creates a new renderer with no tool tip generator and no URL generator. * <P> * The defaults (no tool tip or URL generators) have been chosen to * minimise the processing required to generate a default chart. If you * require tool tips or URLs, then you can easily add the required * generators. */ public StackedBarRenderer3D() { this(false); } /** * Constructs a new renderer with the specified '3D effect'. * * @param xOffset the x-offset for the 3D effect. * @param yOffset the y-offset for the 3D effect. */ public StackedBarRenderer3D(double xOffset, double yOffset) { super(xOffset, yOffset); } /** * Creates a new renderer. * * @param renderAsPercentages a flag that controls whether the data values * are rendered as percentages. * * @since 1.0.2 */ public StackedBarRenderer3D(boolean renderAsPercentages) { super(); this.renderAsPercentages = renderAsPercentages; } /** * Constructs a new renderer with the specified '3D effect'. * * @param xOffset the x-offset for the 3D effect. * @param yOffset the y-offset for the 3D effect. * @param renderAsPercentages a flag that controls whether the data values * are rendered as percentages. * * @since 1.0.2 */ public StackedBarRenderer3D(double xOffset, double yOffset, boolean renderAsPercentages) { super(xOffset, yOffset); this.renderAsPercentages = renderAsPercentages; } /** * Returns <code>true</code> if the renderer displays each item value as * a percentage (so that the stacked bars add to 100%), and * <code>false</code> otherwise. * * @return A boolean. * * @since 1.0.2 */ public boolean getRenderAsPercentages() { return this.renderAsPercentages; } /** * Sets the flag that controls whether the renderer displays each item * value as a percentage (so that the stacked bars add to 100%), and sends * a {@link RendererChangeEvent} to all registered listeners. * * @param asPercentages the flag. * * @since 1.0.2 */ public void setRenderAsPercentages(boolean asPercentages) { this.renderAsPercentages = asPercentages; fireChangeEvent(); } /** * Returns the flag that controls whether or not zero values are drawn * by the renderer. * * @return A boolean. * * @since 1.0.14 */ public boolean getIgnoreZeroValues() { return this.ignoreZeroValues; } /** * Sets a flag that controls whether or not zero values are drawn by the * renderer, and sends a {@link RendererChangeEvent} to all registered * listeners. * * @param ignore the new flag value. * * @since 1.0.14 */ public void setIgnoreZeroValues(boolean ignore) { this.ignoreZeroValues = ignore; notifyListeners(new RendererChangeEvent(this)); } /** * Returns the range of values the renderer requires to display all the * items from the specified dataset. * * @param dataset the dataset (<code>null</code> not permitted). * * @return The range (or <code>null</code> if the dataset is empty). */ @Override public Range findRangeBounds(CategoryDataset dataset) { if (dataset == null) { return null; } if (this.renderAsPercentages) { return new Range(0.0, 1.0); } else { return DatasetUtilities.findStackedRangeBounds(dataset); } } /** * Calculates the bar width and stores it in the renderer state. * * @param plot the plot. * @param dataArea the data area. * @param rendererIndex the renderer index. * @param state the renderer state. */ @Override protected void calculateBarWidth(CategoryPlot plot, Rectangle2D dataArea, int rendererIndex, CategoryItemRendererState state) { // calculate the bar width CategoryAxis domainAxis = getDomainAxis(plot, rendererIndex); CategoryDataset data = plot.getDataset(rendererIndex); if (data != null) { PlotOrientation orientation = plot.getOrientation(); double space = 0.0; if (orientation == PlotOrientation.HORIZONTAL) { space = dataArea.getHeight(); } else if (orientation == PlotOrientation.VERTICAL) { space = dataArea.getWidth(); } double maxWidth = space * getMaximumBarWidth(); int columns = data.getColumnCount(); double categoryMargin = 0.0; if (columns > 1) { categoryMargin = domainAxis.getCategoryMargin(); } double used = space * (1 - domainAxis.getLowerMargin() - domainAxis.getUpperMargin() - categoryMargin); if (columns > 0) { state.setBarWidth(Math.min(used / columns, maxWidth)); } else { state.setBarWidth(Math.min(used, maxWidth)); } } } /** * Returns a list containing the stacked values for the specified series * in the given dataset, plus the supplied base value. * * @param dataset the dataset (<code>null</code> not permitted). * @param category the category key (<code>null</code> not permitted). * @param includedRows the included rows. * @param base the base value. * @param asPercentages a flag that controls whether the values in the * list are converted to percentages of the total. * * @return The value list. * * @since 1.0.13 */ protected List<Object[]> createStackedValueList(CategoryDataset dataset, Comparable category, int[] includedRows, double base, boolean asPercentages) { List<Object[]> result = new ArrayList<Object[]>(); double posBase = base; double negBase = base; double total = 0.0; if (asPercentages) { total = DataUtilities.calculateColumnTotal(dataset, dataset.getColumnIndex(category), includedRows); } int baseIndex = -1; for (int r : includedRows) { Number n = dataset.getValue(dataset.getRowKey(r), category); if (n == null) { continue; } double v = n.doubleValue(); if (asPercentages) { v = v / total; } if ((v > 0.0) || (!this.ignoreZeroValues && v >= 0.0)) { if (baseIndex < 0) { result.add(new Object[]{null, base}); baseIndex = 0; } posBase = posBase + v; result.add(new Object[]{r, posBase}); } else if (v < 0.0) { if (baseIndex < 0) { result.add(new Object[]{null, base}); baseIndex = 0; } negBase = negBase + v; // '+' because v is negative result.add(0, new Object[]{-r - 1, negBase}); baseIndex++; } } return result; } /** * Draws the visual representation of one data item from the chart (in * fact, this method does nothing until it reaches the last item for each * category, at which point it draws all the items for that category). * * @param g2 the graphics device. * @param state the renderer state. * @param dataArea the plot area. * @param plot the plot. * @param domainAxis the domain (category) axis. * @param rangeAxis the range (value) axis. * @param dataset the data. * @param row the row index (zero-based). * @param column the column index (zero-based). * @param pass the pass index. */ @Override public void drawItem(Graphics2D g2, CategoryItemRendererState state, Rectangle2D dataArea, CategoryPlot plot, CategoryAxis domainAxis, ValueAxis rangeAxis, CategoryDataset dataset, int row, int column, int pass) { // wait till we are at the last item for the row then draw the // whole stack at once if (row < dataset.getRowCount() - 1) { return; } Comparable category = dataset.getColumnKey(column); List<Object[]> values = createStackedValueList(dataset, dataset.getColumnKey(column), state.getVisibleSeriesArray(), getBase(), this.renderAsPercentages); Rectangle2D adjusted = new Rectangle2D.Double(dataArea.getX(), dataArea.getY() + getYOffset(), dataArea.getWidth() - getXOffset(), dataArea.getHeight() - getYOffset()); PlotOrientation orientation = plot.getOrientation(); // handle rendering separately for the two plot orientations... if (orientation == PlotOrientation.HORIZONTAL) { drawStackHorizontal(values, category, g2, state, adjusted, plot, domainAxis, rangeAxis, dataset); } else { drawStackVertical(values, category, g2, state, adjusted, plot, domainAxis, rangeAxis, dataset); } } /** * Draws a stack of bars for one category, with a horizontal orientation. * * @param values the value list. * @param category the category. * @param g2 the graphics device. * @param state the state. * @param dataArea the data area (adjusted for the 3D effect). * @param plot the plot. * @param domainAxis the domain axis. * @param rangeAxis the range axis. * @param dataset the dataset. * * @since 1.0.4 */ protected void drawStackHorizontal(List values, Comparable category, Graphics2D g2, CategoryItemRendererState state, Rectangle2D dataArea, CategoryPlot plot, CategoryAxis domainAxis, ValueAxis rangeAxis, CategoryDataset dataset) { int column = dataset.getColumnIndex(category); double barX0 = domainAxis.getCategoryMiddle(column, dataset.getColumnCount(), dataArea, plot.getDomainAxisEdge()) - state.getBarWidth() / 2.0; double barW = state.getBarWidth(); // a list to store the series index and bar region, so we can draw // all the labels at the end... List<Object[]> itemLabelList = new ArrayList<Object[]>(); //FIXME MMC create an internal class to handle the data // draw the blocks boolean inverted = rangeAxis.isInverted(); int blockCount = values.size() - 1; for (int k = 0; k < blockCount; k++) { int index = (inverted ? blockCount - k - 1 : k); Object[] prev = (Object[]) values.get(index); Object[] curr = (Object[]) values.get(index + 1); int series; if (curr[0] == null) { series = -(Integer) prev[0] - 1; } else { series = (Integer) curr[0]; if (series < 0) { series = -(Integer) prev[0] - 1; } } double v0 = (Double) prev[1]; double vv0 = rangeAxis.valueToJava2D(v0, dataArea, plot.getRangeAxisEdge()); double v1 = (Double) curr[1]; double vv1 = rangeAxis.valueToJava2D(v1, dataArea, plot.getRangeAxisEdge()); Shape[] faces = createHorizontalBlock(barX0, barW, vv0, vv1, inverted); Paint fillPaint = getItemPaint(series, column); Paint fillPaintDark = fillPaint; if (fillPaintDark instanceof Color) { fillPaintDark = ((Color) fillPaint).darker(); } boolean drawOutlines = isDrawBarOutline(); Paint outlinePaint = fillPaint; if (drawOutlines) { outlinePaint = getItemOutlinePaint(series, column); g2.setStroke(getItemOutlineStroke(series, column)); } for (int f = 0; f < 6; f++) { if (f == 5) { g2.setPaint(fillPaint); } else { g2.setPaint(fillPaintDark); } g2.fill(faces[f]); if (drawOutlines) { g2.setPaint(outlinePaint); g2.draw(faces[f]); } } itemLabelList.add(new Object[] {series, faces[5].getBounds2D(), v0 < getBase()}); // add an item entity, if this information is being collected EntityCollection entities = state.getEntityCollection(); if (entities != null) { addItemEntity(entities, dataset, series, column, faces[5]); } } for (Object[] record : itemLabelList) { int series = (Integer) record[0]; Rectangle2D bar = (Rectangle2D) record[1]; boolean neg = (Boolean) record[2]; CategoryItemLabelGenerator generator = getItemLabelGenerator(series, column); if (generator != null && isItemLabelVisible(series, column)) { drawItemLabel(g2, dataset, series, column, plot, generator, bar, neg); } } } /** * Creates an array of shapes representing the six sides of a block in a * horizontal stack. * * @param x0 left edge of bar (in Java2D space). * @param width the width of the bar (in Java2D units). * @param y0 the base of the block (in Java2D space). * @param y1 the top of the block (in Java2D space). * @param inverted a flag indicating whether or not the block is inverted * (this changes the order of the faces of the block). * * @return The sides of the block. */ private Shape[] createHorizontalBlock(double x0, double width, double y0, double y1, boolean inverted) { Shape[] result = new Shape[6]; Point2D p00 = new Point2D.Double(y0, x0); Point2D p01 = new Point2D.Double(y0, x0 + width); Point2D p02 = new Point2D.Double(p01.getX() + getXOffset(), p01.getY() - getYOffset()); Point2D p03 = new Point2D.Double(p00.getX() + getXOffset(), p00.getY() - getYOffset()); Point2D p0 = new Point2D.Double(y1, x0); Point2D p1 = new Point2D.Double(y1, x0 + width); Point2D p2 = new Point2D.Double(p1.getX() + getXOffset(), p1.getY() - getYOffset()); Point2D p3 = new Point2D.Double(p0.getX() + getXOffset(), p0.getY() - getYOffset()); GeneralPath bottom = new GeneralPath(); bottom.moveTo((float) p1.getX(), (float) p1.getY()); bottom.lineTo((float) p01.getX(), (float) p01.getY()); bottom.lineTo((float) p02.getX(), (float) p02.getY()); bottom.lineTo((float) p2.getX(), (float) p2.getY()); bottom.closePath(); GeneralPath top = new GeneralPath(); top.moveTo((float) p0.getX(), (float) p0.getY()); top.lineTo((float) p00.getX(), (float) p00.getY()); top.lineTo((float) p03.getX(), (float) p03.getY()); top.lineTo((float) p3.getX(), (float) p3.getY()); top.closePath(); GeneralPath back = new GeneralPath(); back.moveTo((float) p2.getX(), (float) p2.getY()); back.lineTo((float) p02.getX(), (float) p02.getY()); back.lineTo((float) p03.getX(), (float) p03.getY()); back.lineTo((float) p3.getX(), (float) p3.getY()); back.closePath(); GeneralPath front = new GeneralPath(); front.moveTo((float) p0.getX(), (float) p0.getY()); front.lineTo((float) p1.getX(), (float) p1.getY()); front.lineTo((float) p01.getX(), (float) p01.getY()); front.lineTo((float) p00.getX(), (float) p00.getY()); front.closePath(); GeneralPath left = new GeneralPath(); left.moveTo((float) p0.getX(), (float) p0.getY()); left.lineTo((float) p1.getX(), (float) p1.getY()); left.lineTo((float) p2.getX(), (float) p2.getY()); left.lineTo((float) p3.getX(), (float) p3.getY()); left.closePath(); GeneralPath right = new GeneralPath(); right.moveTo((float) p00.getX(), (float) p00.getY()); right.lineTo((float) p01.getX(), (float) p01.getY()); right.lineTo((float) p02.getX(), (float) p02.getY()); right.lineTo((float) p03.getX(), (float) p03.getY()); right.closePath(); result[0] = bottom; result[1] = back; if (inverted) { result[2] = right; result[3] = left; } else { result[2] = left; result[3] = right; } result[4] = top; result[5] = front; return result; } /** * Draws a stack of bars for one category, with a vertical orientation. * * @param values the value list. * @param category the category. * @param g2 the graphics device. * @param state the state. * @param dataArea the data area (adjusted for the 3D effect). * @param plot the plot. * @param domainAxis the domain axis. * @param rangeAxis the range axis. * @param dataset the dataset. * * @since 1.0.4 */ protected void drawStackVertical(List values, Comparable category, Graphics2D g2, CategoryItemRendererState state, Rectangle2D dataArea, CategoryPlot plot, CategoryAxis domainAxis, ValueAxis rangeAxis, CategoryDataset dataset) { int column = dataset.getColumnIndex(category); double barX0 = domainAxis.getCategoryMiddle(column, dataset.getColumnCount(), dataArea, plot.getDomainAxisEdge()) - state.getBarWidth() / 2.0; double barW = state.getBarWidth(); // a list to store the series index and bar region, so we can draw // all the labels at the end... List<Object[]> itemLabelList = new ArrayList<Object[]>(); // draw the blocks boolean inverted = rangeAxis.isInverted(); int blockCount = values.size() - 1; for (int k = 0; k < blockCount; k++) { int index = (inverted ? blockCount - k - 1 : k); Object[] prev = (Object[]) values.get(index); Object[] curr = (Object[]) values.get(index + 1); int series = 0; if (curr[0] == null) { series = -(Integer) prev[0] - 1; } else { series = (Integer) curr[0]; if (series < 0) { series = -(Integer) prev[0] - 1; } } double v0 = (Double) prev[1]; double vv0 = rangeAxis.valueToJava2D(v0, dataArea, plot.getRangeAxisEdge()); double v1 = (Double) curr[1]; double vv1 = rangeAxis.valueToJava2D(v1, dataArea, plot.getRangeAxisEdge()); Shape[] faces = createVerticalBlock(barX0, barW, vv0, vv1, inverted); Paint fillPaint = getItemPaint(series, column); Paint fillPaintDark = fillPaint; if (fillPaintDark instanceof Color) { fillPaintDark = ((Color) fillPaint).darker(); } boolean drawOutlines = isDrawBarOutline(); Paint outlinePaint = fillPaint; if (drawOutlines) { outlinePaint = getItemOutlinePaint(series, column); g2.setStroke(getItemOutlineStroke(series, column)); } for (int f = 0; f < 6; f++) { if (f == 5) { g2.setPaint(fillPaint); } else { g2.setPaint(fillPaintDark); } g2.fill(faces[f]); if (drawOutlines) { g2.setPaint(outlinePaint); g2.draw(faces[f]); } } itemLabelList.add(new Object[] {series, faces[5].getBounds2D(), v0 < getBase()}); // add an item entity, if this information is being collected EntityCollection entities = state.getEntityCollection(); if (entities != null) { addItemEntity(entities, dataset, series, column, faces[5]); } } for (Object[] record : itemLabelList) { int series = (Integer) record[0]; Rectangle2D bar = (Rectangle2D) record[1]; boolean neg = (Boolean) record[2]; CategoryItemLabelGenerator generator = getItemLabelGenerator(series, column); if (generator != null && isItemLabelVisible(series, column)) { drawItemLabel(g2, dataset, series, column, plot, generator, bar, neg); } } } /** * Creates an array of shapes representing the six sides of a block in a * vertical stack. * * @param x0 left edge of bar (in Java2D space). * @param width the width of the bar (in Java2D units). * @param y0 the base of the block (in Java2D space). * @param y1 the top of the block (in Java2D space). * @param inverted a flag indicating whether or not the block is inverted * (this changes the order of the faces of the block). * * @return The sides of the block. */ private Shape[] createVerticalBlock(double x0, double width, double y0, double y1, boolean inverted) { Shape[] result = new Shape[6]; Point2D p00 = new Point2D.Double(x0, y0); Point2D p01 = new Point2D.Double(x0 + width, y0); Point2D p02 = new Point2D.Double(p01.getX() + getXOffset(), p01.getY() - getYOffset()); Point2D p03 = new Point2D.Double(p00.getX() + getXOffset(), p00.getY() - getYOffset()); Point2D p0 = new Point2D.Double(x0, y1); Point2D p1 = new Point2D.Double(x0 + width, y1); Point2D p2 = new Point2D.Double(p1.getX() + getXOffset(), p1.getY() - getYOffset()); Point2D p3 = new Point2D.Double(p0.getX() + getXOffset(), p0.getY() - getYOffset()); GeneralPath right = new GeneralPath(); right.moveTo((float) p1.getX(), (float) p1.getY()); right.lineTo((float) p01.getX(), (float) p01.getY()); right.lineTo((float) p02.getX(), (float) p02.getY()); right.lineTo((float) p2.getX(), (float) p2.getY()); right.closePath(); GeneralPath left = new GeneralPath(); left.moveTo((float) p0.getX(), (float) p0.getY()); left.lineTo((float) p00.getX(), (float) p00.getY()); left.lineTo((float) p03.getX(), (float) p03.getY()); left.lineTo((float) p3.getX(), (float) p3.getY()); left.closePath(); GeneralPath back = new GeneralPath(); back.moveTo((float) p2.getX(), (float) p2.getY()); back.lineTo((float) p02.getX(), (float) p02.getY()); back.lineTo((float) p03.getX(), (float) p03.getY()); back.lineTo((float) p3.getX(), (float) p3.getY()); back.closePath(); GeneralPath front = new GeneralPath(); front.moveTo((float) p0.getX(), (float) p0.getY()); front.lineTo((float) p1.getX(), (float) p1.getY()); front.lineTo((float) p01.getX(), (float) p01.getY()); front.lineTo((float) p00.getX(), (float) p00.getY()); front.closePath(); GeneralPath top = new GeneralPath(); top.moveTo((float) p0.getX(), (float) p0.getY()); top.lineTo((float) p1.getX(), (float) p1.getY()); top.lineTo((float) p2.getX(), (float) p2.getY()); top.lineTo((float) p3.getX(), (float) p3.getY()); top.closePath(); GeneralPath bottom = new GeneralPath(); bottom.moveTo((float) p00.getX(), (float) p00.getY()); bottom.lineTo((float) p01.getX(), (float) p01.getY()); bottom.lineTo((float) p02.getX(), (float) p02.getY()); bottom.lineTo((float) p03.getX(), (float) p03.getY()); bottom.closePath(); result[0] = bottom; result[1] = back; result[2] = left; result[3] = right; result[4] = top; result[5] = front; if (inverted) { result[0] = top; result[4] = bottom; } return result; } /** * Tests this renderer for equality with an arbitrary object. * * @param obj the object (<code>null</code> permitted). * * @return A boolean. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof StackedBarRenderer3D)) { return false; } StackedBarRenderer3D that = (StackedBarRenderer3D) obj; if (this.renderAsPercentages != that.getRenderAsPercentages()) { return false; } if (this.ignoreZeroValues != that.ignoreZeroValues) { return false; } return super.equals(obj); } /** * Returns a hash code for this instance. * * @return A hash code. */ @Override public int hashCode() { int hash = super.hashCode(); hash = HashUtilities.hashCode(hash, this.renderAsPercentages); hash = HashUtilities.hashCode(hash, this.ignoreZeroValues); return hash; } }
32,548
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
GradientBarPainter.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/renderer/category/GradientBarPainter.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ----------------------- * GradientBarPainter.java * ----------------------- * (C) Copyright 2008-2012, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes: * -------- * 19-Jun-2008 : Version 1 (DG); * 15-Aug-2008 : Use outline paint and shadow paint (DG); * 17-Jun-2012 : Removed JCommon dependencies (DG); * */ package org.jfree.chart.renderer.category; import java.awt.Color; import java.awt.GradientPaint; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.Stroke; import java.awt.geom.Rectangle2D; import java.awt.geom.RectangularShape; import java.io.Serializable; import org.jfree.chart.HashUtilities; import org.jfree.chart.ui.RectangleEdge; /** * An implementation of the {@link BarPainter} interface that uses several * gradient fills to enrich the appearance of the bars. * * @since 1.0.11 */ public class GradientBarPainter implements BarPainter, Serializable { /** The division point between the first and second gradient regions. */ private double g1; /** The division point between the second and third gradient regions. */ private double g2; /** The division point between the third and fourth gradient regions. */ private double g3; /** * Creates a new instance. */ public GradientBarPainter() { this(0.10, 0.20, 0.80); } /** * Creates a new instance. * * @param g1 * @param g2 * @param g3 */ public GradientBarPainter(double g1, double g2, double g3) { this.g1 = g1; this.g2 = g2; this.g3 = g3; } /** * Paints a single bar instance. * * @param g2 the graphics target. * @param renderer the renderer. * @param row the row index. * @param column the column index. * @param bar the bar * @param base indicates which side of the rectangle is the base of the * bar. */ @Override public void paintBar(Graphics2D g2, BarRenderer renderer, int row, int column, RectangularShape bar, RectangleEdge base) { Paint itemPaint = renderer.getItemPaint(row, column); Color c0, c1; if (itemPaint instanceof Color) { c0 = (Color) itemPaint; c1 = c0.brighter(); } else if (itemPaint instanceof GradientPaint) { GradientPaint gp = (GradientPaint) itemPaint; c0 = gp.getColor1(); c1 = gp.getColor2(); } else { c0 = Color.BLUE; c1 = Color.BLUE.brighter(); } // as a special case, if the bar colour has alpha == 0, we draw // nothing. if (c0.getAlpha() == 0) { return; } if (base == RectangleEdge.TOP || base == RectangleEdge.BOTTOM) { Rectangle2D[] regions = splitVerticalBar(bar, this.g1, this.g2, this.g3); GradientPaint gp = new GradientPaint((float) regions[0].getMinX(), 0.0f, c0, (float) regions[0].getMaxX(), 0.0f, Color.WHITE); g2.setPaint(gp); g2.fill(regions[0]); gp = new GradientPaint((float) regions[1].getMinX(), 0.0f, Color.WHITE, (float) regions[1].getMaxX(), 0.0f, c0); g2.setPaint(gp); g2.fill(regions[1]); gp = new GradientPaint((float) regions[2].getMinX(), 0.0f, c0, (float) regions[2].getMaxX(), 0.0f, c1); g2.setPaint(gp); g2.fill(regions[2]); gp = new GradientPaint((float) regions[3].getMinX(), 0.0f, c1, (float) regions[3].getMaxX(), 0.0f, c0); g2.setPaint(gp); g2.fill(regions[3]); } else if (base == RectangleEdge.LEFT || base == RectangleEdge.RIGHT) { Rectangle2D[] regions = splitHorizontalBar(bar, this.g1, this.g2, this.g3); GradientPaint gp = new GradientPaint(0.0f, (float) regions[0].getMinY(), c0, 0.0f, (float) regions[0].getMaxY(), Color.WHITE); g2.setPaint(gp); g2.fill(regions[0]); gp = new GradientPaint(0.0f, (float) regions[1].getMinY(), Color.WHITE, 0.0f, (float) regions[1].getMaxY(), c0); g2.setPaint(gp); g2.fill(regions[1]); gp = new GradientPaint(0.0f, (float) regions[2].getMinY(), c0, 0.0f, (float) regions[2].getMaxY(), c1); g2.setPaint(gp); g2.fill(regions[2]); gp = new GradientPaint(0.0f, (float) regions[3].getMinY(), c1, 0.0f, (float) regions[3].getMaxY(), c0); g2.setPaint(gp); g2.fill(regions[3]); } // draw the outline... if (renderer.isDrawBarOutline() /*&& state.getBarWidth() > renderer.BAR_OUTLINE_WIDTH_THRESHOLD*/) { Stroke stroke = renderer.getItemOutlineStroke(row, column); Paint paint = renderer.getItemOutlinePaint(row, column); if (stroke != null && paint != null) { g2.setStroke(stroke); g2.setPaint(paint); g2.draw(bar); } } } /** * Paints a single bar instance. * * @param g2 the graphics target. * @param renderer the renderer. * @param row the row index. * @param column the column index. * @param bar the bar * @param base indicates which side of the rectangle is the base of the * bar. * @param pegShadow peg the shadow to the base of the bar? */ @Override public void paintBarShadow(Graphics2D g2, BarRenderer renderer, int row, int column, RectangularShape bar, RectangleEdge base, boolean pegShadow) { // handle a special case - if the bar colour has alpha == 0, it is // invisible so we shouldn't draw any shadow Paint itemPaint = renderer.getItemPaint(row, column); if (itemPaint instanceof Color) { Color c = (Color) itemPaint; if (c.getAlpha() == 0) { return; } } RectangularShape shadow = createShadow(bar, renderer.getShadowXOffset(), renderer.getShadowYOffset(), base, pegShadow); g2.setPaint(renderer.getShadowPaint()); g2.fill(shadow); } /** * Creates a shadow for the bar. * * @param bar the bar shape. * @param xOffset the x-offset for the shadow. * @param yOffset the y-offset for the shadow. * @param base the edge that is the base of the bar. * @param pegShadow peg the shadow to the base? * * @return A rectangle for the shadow. */ private Rectangle2D createShadow(RectangularShape bar, double xOffset, double yOffset, RectangleEdge base, boolean pegShadow) { double x0 = bar.getMinX(); double x1 = bar.getMaxX(); double y0 = bar.getMinY(); double y1 = bar.getMaxY(); if (base == RectangleEdge.TOP) { x0 += xOffset; x1 += xOffset; if (!pegShadow) { y0 += yOffset; } y1 += yOffset; } else if (base == RectangleEdge.BOTTOM) { x0 += xOffset; x1 += xOffset; y0 += yOffset; if (!pegShadow) { y1 += yOffset; } } else if (base == RectangleEdge.LEFT) { if (!pegShadow) { x0 += xOffset; } x1 += xOffset; y0 += yOffset; y1 += yOffset; } else if (base == RectangleEdge.RIGHT) { x0 += xOffset; if (!pegShadow) { x1 += xOffset; } y0 += yOffset; y1 += yOffset; } return new Rectangle2D.Double(x0, y0, (x1 - x0), (y1 - y0)); } /** * Splits a bar into subregions (elsewhere, these subregions will have * different gradients applied to them). * * @param bar the bar shape. * @param a the first division. * @param b the second division. * @param c the third division. * * @return An array containing four subregions. */ private Rectangle2D[] splitVerticalBar(RectangularShape bar, double a, double b, double c) { Rectangle2D[] result = new Rectangle2D[4]; double x0 = bar.getMinX(); double x1 = Math.rint(x0 + (bar.getWidth() * a)); double x2 = Math.rint(x0 + (bar.getWidth() * b)); double x3 = Math.rint(x0 + (bar.getWidth() * c)); result[0] = new Rectangle2D.Double(bar.getMinX(), bar.getMinY(), x1 - x0, bar.getHeight()); result[1] = new Rectangle2D.Double(x1, bar.getMinY(), x2 - x1, bar.getHeight()); result[2] = new Rectangle2D.Double(x2, bar.getMinY(), x3 - x2, bar.getHeight()); result[3] = new Rectangle2D.Double(x3, bar.getMinY(), bar.getMaxX() - x3, bar.getHeight()); return result; } /** * Splits a bar into subregions (elsewhere, these subregions will have * different gradients applied to them). * * @param bar the bar shape. * @param a the first division. * @param b the second division. * @param c the third division. * * @return An array containing four subregions. */ private Rectangle2D[] splitHorizontalBar(RectangularShape bar, double a, double b, double c) { Rectangle2D[] result = new Rectangle2D[4]; double y0 = bar.getMinY(); double y1 = Math.rint(y0 + (bar.getHeight() * a)); double y2 = Math.rint(y0 + (bar.getHeight() * b)); double y3 = Math.rint(y0 + (bar.getHeight() * c)); result[0] = new Rectangle2D.Double(bar.getMinX(), bar.getMinY(), bar.getWidth(), y1 - y0); result[1] = new Rectangle2D.Double(bar.getMinX(), y1, bar.getWidth(), y2 - y1); result[2] = new Rectangle2D.Double(bar.getMinX(), y2, bar.getWidth(), y3 - y2); result[3] = new Rectangle2D.Double(bar.getMinX(), y3, bar.getWidth(), bar.getMaxY() - y3); return result; } /** * Tests this instance for equality with an arbitrary object. * * @param obj the obj (<code>null</code> permitted). * * @return A boolean. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof GradientBarPainter)) { return false; } GradientBarPainter that = (GradientBarPainter) obj; if (this.g1 != that.g1) { return false; } if (this.g2 != that.g2) { return false; } if (this.g3 != that.g3) { return false; } return true; } /** * Returns a hash code for this instance. * * @return A hash code. */ @Override public int hashCode() { int hash = 37; hash = HashUtilities.hashCode(hash, this.g1); hash = HashUtilities.hashCode(hash, this.g2); hash = HashUtilities.hashCode(hash, this.g3); return hash; } }
12,728
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
DefaultItemRenderingStrategy.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/renderer/item/DefaultItemRenderingStrategy.java
package org.jfree.chart.renderer.item; import java.io.Serializable; import org.jfree.chart.renderer.AbstractRenderer; /* * if necessary this can be improved with respect to speed by implementing the * default cases direct in the abstract renderer. */ /** * A default item rendering strategy defines certain properties e.g. Shape, Paint, ... for individual items. * It should be used with a specific renderer because it is based on its Shape, Paint, ... per Series properties. * * @author zinsmaie */ public abstract class DefaultItemRenderingStrategy implements Serializable { /** generated serial id */ private static final long serialVersionUID = -3637783770791118009L; /** the renderer that uses the strategy. This is necessary to get access to the * get Property Series methods etc. */ protected final AbstractRenderer renderer; /** * creates a new Rendering strategy for the submitted renderer. * @param renderer */ public DefaultItemRenderingStrategy(AbstractRenderer renderer) { this.renderer = renderer; } }
1,102
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
PaintIRS.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/renderer/item/PaintIRS.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2013, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ------------- * PaintIRS.java * ------------- * (C) Copyright 2013, by Michael Zinsmaier. * * Original Author: Michael Zinsmaier; * Contributor(s): -; * * Changes * ------- * 17-Sep-2013 : Version 1 (MZ); * */ package org.jfree.chart.renderer.item; import java.awt.Paint; import java.io.Serializable; import org.jfree.chart.renderer.AbstractRenderer; /** * Defines an interface to control the paint variables for individual items * during rendering. Implementing classes can be used together with subclasses * of {@link AbstractRenderer} to control the rendering process.<br> * Works however only if the descendant of {@link AbstractRenderer} uses per * item methods like {@link AbstractRenderer#getItemPaint(int, int)} * <br> * <br> * Important Paint is not serializable see {@link IRSUtilities}) for the * correct implementation of the custom read and write method. * * @author zinsmaie */ public interface PaintIRS extends Serializable { /** * Specifies an individual item by row, column and returns the item paint. * * @param row the row (or series) index (zero-based). * @param column the column (or category) index (zero-based). * * @return a paint (never <code>null<code>) */ public Paint getItemPaint(int row, int column); /** * Specifies an individual item by row, column and returns the item fill * paint. * * @param row the row (or series) index (zero-based). * @param column the column (or category) index (zero-based). * * @return a paint used to fill the item (never <code>null<code>) */ public Paint getItemFillPaint(int row, int column); /** * Specifies an individual item by row, column and returns the item outline * paint. * * @param row the row (or series) index (zero-based). * @param column the column (or category) index (zero-based). * * @return a paint used for the item outline (never <code>null<code>) */ public Paint getItemOutlinePaint(int row, int column); }
3,311
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
DefaultLabelIRS.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/renderer/item/DefaultLabelIRS.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2013, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * -------------------- * DefaultLabelIRS.java * -------------------- * (C) Copyright 2013, by Michael Zinsmaier. * * Original Author: Michael Zinsmaier; * Contributor(s): -; * * Changes * ------- * 17-Sep-2013 : Version 1 (MZ); * */ package org.jfree.chart.renderer.item; import java.awt.Font; import org.jfree.chart.labels.ItemLabelPosition; import org.jfree.chart.renderer.AbstractRenderer; /** * Implements a per series default item rendering strategy for labels. * {@link DefaultItemRenderingStrategy} * * @author zinsmaie */ public class DefaultLabelIRS extends DefaultItemRenderingStrategy implements LabelIRS { /** a generated serial id */ private static final long serialVersionUID = 5516468638404616499L; /** * Creates a new rendering strategy for the submitted renderer using its * per series properties. * * @param renderer */ public DefaultLabelIRS(AbstractRenderer renderer) { super(renderer); } /** * @return the label font the renderer defines for the series (or the base * item label font if no series font is specified) */ public Font getItemLabelFont(int row, int column) { Font result = renderer.getSeriesItemLabelFont(row); if (result == null) { result = renderer.getDefaultItemLabelFont(); } return result; } /** * @return the visibility the renderer defines for the series */ public boolean isItemLabelVisible(int row, int column) { return renderer.isSeriesItemLabelsVisible(row); } /** * @return the item label position that is defined in the renderer for the * series */ public ItemLabelPosition getPositiveItemLabelPosition(int row, int column) { return renderer.getSeriesPositiveItemLabelPosition(row); } /** * @return the item label position that is defined in the renderer for the $ * series */ public ItemLabelPosition getNegativeItemLabelPosition(int row, int column) { return renderer.getSeriesNegativeItemLabelPosition(row); } }
3,372
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
VisibilityIRS.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/renderer/item/VisibilityIRS.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2013, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ------------------ * VisibilityIRS.java * ------------------ * (C) Copyright 2013, by Michael Zinsmaier. * * Original Author: Michael Zinsmaier; * Contributor(s): -; * * Changes * ------- * 17-Sep-2013 : Version 1 (MZ); * */ package org.jfree.chart.renderer.item; import java.io.Serializable; import org.jfree.chart.renderer.AbstractRenderer; /** * Defines an interface to control the visibility of individual items during * rendering. Implementing classes can be used together with subclasses of * {@link AbstractRenderer} to control the rendering process.<br> * Works however only if the descendant of {@link AbstractRenderer} uses the * per item method {@link AbstractRenderer#getItemVisible(int, int)} * * @author zinsmaie */ public interface VisibilityIRS extends Serializable { /** * Specifies an individual item by row, column and returns true if it is * visible. * * @param row the row (or series) index (zero-based). * @param column the column (or category) index (zero-based). * * @return true if the item is visible */ public boolean getItemVisible(int row, int column); }
2,398
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
DefaultPaintIRS.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/renderer/item/DefaultPaintIRS.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2013, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * -------------------- * DefaultPaintIRS.java * -------------------- * (C) Copyright 2013, by Michael Zinsmaier. * * Original Author: Michael Zinsmaier; * Contributor(s): -; * * Changes * ------- * 17-Sep-2013 : Version 1 (MZ); * */ package org.jfree.chart.renderer.item; import java.awt.Paint; import org.jfree.chart.renderer.AbstractRenderer; /** * Implements a per series default item rendering strategy for the item paint. * {@link DefaultItemRenderingStrategy} * * @author zinsmaie */ public class DefaultPaintIRS extends DefaultItemRenderingStrategy implements PaintIRS { /** a generated serial id */ private static final long serialVersionUID = 2211937902401233033L; /** * Creates a new rendering strategy for the submitted renderer using its * per series properties. * * @param renderer */ public DefaultPaintIRS(AbstractRenderer renderer) { super(renderer); } /** * @return the item paint the renderer defines for the series */ public Paint getItemPaint(int row, int column) { return renderer.lookupSeriesPaint(row); } /** * @return the item fill paint the renderer defines for the series */ public Paint getItemFillPaint(int row, int column) { return renderer.lookupSeriesFillPaint(row); } /** * @return the item outline paint the renderer defines for the series */ public Paint getItemOutlinePaint(int row, int column) { return renderer.lookupSeriesOutlinePaint(row); } }
2,794
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
LabelIRS.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/renderer/item/LabelIRS.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2013, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ------------- * LabelIRS.java * ------------- * (C) Copyright 2013, by Michael Zinsmaier. * * Original Author: Michael Zinsmaier; * Contributor(s): -; * * Changes * ------- * 17-Sep-2013 : Version 1 (MZ); * */ package org.jfree.chart.renderer.item; import java.awt.Font; import java.io.Serializable; import org.jfree.chart.labels.ItemLabelPosition; import org.jfree.chart.renderer.AbstractRenderer; /** * Defines an interface to control the rendering of labels for individual items. * Implementing classes can be used together with subclasses of * {@link AbstractRenderer} to control the rendering process.<br> * Works however only if the descendant of {@link AbstractRenderer} uses per * item methods like {@link AbstractRenderer#getItemLabelFont(int, int)} * * @author zinsmaie */ public interface LabelIRS extends Serializable { /** * Specifies an individual item by row, column and returns the font for its * label. * * @param row the row (or series) index (zero-based). * @param column the column (or category) index (zero-based). * * @return a Font (never <code>null<code>) */ public Font getItemLabelFont(int row, int column); /** * Specifies an individual item by row, column and returns true if its * label should be rendered. * * @param row the row (or series) index (zero-based). * @param column the column (or category) index (zero-based). * * @return true if the label should be rendered */ public boolean isItemLabelVisible(int row, int column); /** * Specifies an individual item by row, column and returns the label * position. * * @param row the row (or series) index (zero-based). * @param column the column (or category) index (zero-based). * * @return The item label position (never <code>null</code>). */ public ItemLabelPosition getPositiveItemLabelPosition(int row, int column); /** * Specifies an individual item by row, column and returns the label * position. * * @param row the row (or series) index (zero-based). * @param column the column (or category) index (zero-based). * * @return The item label position (never <code>null</code>). */ public ItemLabelPosition getNegativeItemLabelPosition(int row, int column); }
3,621
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
StrokeIRS.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/renderer/item/StrokeIRS.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2013, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * -------------- * StrokeIRS.java * -------------- * (C) Copyright 2013, by Michael Zinsmaier. * * Original Author: Michael Zinsmaier; * Contributor(s): -; * * Changes * ------- * 17-Sep-2013 : Version 1 (MZ); * */ package org.jfree.chart.renderer.item; import java.awt.Stroke; import java.io.Serializable; import org.jfree.chart.renderer.AbstractRenderer; /** * Defines an interface to control the stroke for individual items during * rendering. Implementing classes can be used together with subclasses of * {@link AbstractRenderer} to control the rendering process.<br> * Works however only if the descendant of {@link AbstractRenderer} uses per * item methods like {@link AbstractRenderer#getItemStroke(int, int)} * <br> * <br> * Important Stroke is not serializable see {@link IRSUtilities}) for the * correct implementation of the custom read and write method. * * @author zinsmaie */ public interface StrokeIRS extends Serializable { /** * Specifies an individual item by row, column and returns the item stroke * * @param row the row (or series) index (zero-based). * @param column the column (or category) index (zero-based). * * @return a stroke (never <code>null<code>) */ public Stroke getItemStroke(int row, int column); /** * Specifies an individual item by row, column and returns the outline * stroke. * * @param row the row (or series) index (zero-based). * @param column the column (or category) index (zero-based). * * @return a stroke (never <code>null<code>) */ public Stroke getItemOutlineStroke(int row, int column); }
2,908
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
IRSUtilities.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/renderer/item/IRSUtilities.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2013, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ----------------- * IRSUtilities.java * ----------------- * (C) Copyright 2013, by Michael Zinsmaier. * * Original Author: Michael Zinsmaier; * Contributor(s): -; * * Changes * ------- * 17-Sep-2013 : Version 1 (MZ); * */ package org.jfree.chart.renderer.item; import java.awt.Paint; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import org.jfree.chart.renderer.AbstractRenderer; import org.jfree.chart.util.SerialUtilities; import org.jfree.data.category.CategoryDataset; import org.jfree.data.extension.DatasetCursor; import org.jfree.data.extension.DatasetSelectionExtension; import org.jfree.data.extension.impl.CategoryCursor; import org.jfree.data.extension.impl.XYCursor; import org.jfree.data.general.Dataset; import org.jfree.data.xy.XYDataset; /** * A helper class to define simple item rendering strategies. * * Currently provides only support for paint manipulations based on the * selection state of items. * * @author zinsmaie */ public class IRSUtilities { private IRSUtilities() { //static helper class } //Reusable cursors for fast access private static DatasetCursor cursor; private final static XYCursor xyCursor = new XYCursor(); //TODO a type save solution would be nice private final static CategoryCursor categoryCursor = new CategoryCursor(); //Default methods for PaintIRS handling /** * A helper method that installs a {@link PaintIRS} on the specified * renderer. * Highlights selected items by rendering them with the specified paint. * Works only if the renderer determines the outline paint * {@link AbstractRenderer#getItemFillPaint(int, int) per item} * * @param renderer renders the dataset and is enhanced with the created IRS * @param ext access to the selection state the dataset items * @param fillPaint (might be null) defines a highlight color that should * be used for the interior of selected items * @param itemPaint (might be null) defines a highlight color that should * be used for selected items * @param outlinePaint (might be null) defines a highlight color that * should be used for the outline of selected items */ public static void setSelectedItemPaintIRS(final AbstractRenderer renderer, final DatasetSelectionExtension ext, final Paint fillPaint, final Paint itemPaint, final Paint outlinePaint) { PaintIRS irs = new DefaultPaintIRS(renderer) { /** a generated serial id */ private static final long serialVersionUID = -7838213904327581272L; private transient Paint m_fillPaint = fillPaint; private transient Paint m_itemPaint = itemPaint; private transient Paint m_outlinePaint = outlinePaint; private final Dataset dataset = ext.getDataset(); @Override public Paint getItemPaint(int row, int column) { if (m_itemPaint == null || !isSelected(row, column)) { return super.getItemPaint(row, column); } else { return m_itemPaint; } } @Override public Paint getItemOutlinePaint(int row, int column) { if (m_outlinePaint == null || !isSelected(row, column)) { return super.getItemPaint(row, column); } else { return m_outlinePaint; } } @Override public Paint getItemFillPaint(int row, int column) { if (m_fillPaint == null || !isSelected(row, column)) { return super.getItemPaint(row, column); } else { return m_fillPaint; } } private boolean isSelected(int row, int column) { //note that pie plots aren't based on the abstract renderer //=> threat only xy and category if (this.dataset instanceof XYDataset) { xyCursor.setPosition(row, column); cursor = xyCursor; } else if (this.dataset instanceof CategoryDataset) { CategoryDataset d = (CategoryDataset)dataset; categoryCursor.setPosition(d.getRowKey(row), d.getColumnKey(column)); cursor = categoryCursor; } else { return false; } return ext.isSelected(cursor); } /** * Provides serialization support. * * @param stream the output stream. * * @throws IOException if there is an I/O error. */ private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); SerialUtilities.writePaint(m_outlinePaint, stream); SerialUtilities.writePaint(m_fillPaint, stream); SerialUtilities.writePaint(m_itemPaint, stream); } /** * Provides serialization support. * * @param stream the input stream. * * @throws IOException if there is an I/O error. * @throws ClassNotFoundException if there is a classpath problem. */ private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); m_outlinePaint = SerialUtilities.readPaint(stream); m_fillPaint = SerialUtilities.readPaint(stream); m_itemPaint = SerialUtilities.readPaint(stream); } }; //this is where the magic happens renderer.setPaintIRS(irs); } /** * A helper method that installs a {@link PaintIRS} on the specified * renderer. Highlights selected items by rendering their interior with * the specified paint. Works only if the renderer determines the outline * paint {@link AbstractRenderer#getItemFillPaint(int, int) per item} * * @param renderer renders the dataset and is enhanced with the created IRS * @param ext access to the selection state the dataset items * @param fillPaint defines a highlight color that should be used for the * interior of selected items */ public static void setSelectedItemFillPaint(final AbstractRenderer renderer, final DatasetSelectionExtension<?> ext, final Paint fillPaint) { setSelectedItemPaintIRS(renderer, ext, fillPaint, null, null); } /** * A helper method that installs a {@link PaintIRS} on the specified * renderer. Highlights selected items by rendering them with the * specified paint. Works only if the renderer determines the item paint * {@link AbstractRenderer#getItemPaint(int, int) per item} * * @param renderer renders the dataset and is enhanced with the created IRS * @param ext access to the selection state the dataset items * @param itemPaint defines a highlight color that should be used for * selected items */ public static void setSelectedItemPaint(final AbstractRenderer renderer, final DatasetSelectionExtension<?> ext, final Paint itemPaint) { setSelectedItemPaintIRS(renderer, ext, null, itemPaint, null); } /** * A helper method that installs a {@link PaintIRS} on the specified * renderer. Highlights selected items by rendering their outline with the * defined paint. Works only if the renderer determines the outline paint * {@link AbstractRenderer#getItemOutlinePaint(int, int) per item} * * @param renderer renders the dataset and is enhanced with the created IRS * @param ext access to the selection state the dataset items * @param outlinePaint defines a highlight color that should be used for * the outline of selected items */ public static void setSelectedItemOutlinePaint(final AbstractRenderer renderer, final DatasetSelectionExtension<?> ext, final Paint outlinePaint) { setSelectedItemPaintIRS(renderer, ext, null, null, outlinePaint); } }
9,887
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
DefaultShapeIRS.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/renderer/item/DefaultShapeIRS.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2013, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * -------------------- * DefaultShapeIRS.java * -------------------- * (C) Copyright 2013, by Michael Zinsmaier. * * Original Author: Michael Zinsmaier; * Contributor(s): -; * * Changes * ------- * 17-Sep-2013 : Version 1 (MZ); * */ package org.jfree.chart.renderer.item; import java.awt.Shape; import org.jfree.chart.renderer.AbstractRenderer; /** * Implements a per series default item rendering strategy for the item shape. * {@link DefaultItemRenderingStrategy} * * @author zinsmaie */ public class DefaultShapeIRS extends DefaultItemRenderingStrategy implements ShapeIRS { /** a generated serial id */ private static final long serialVersionUID = 7582378597877240617L; /** * Creates a new rendering strategy for the submitted renderer using its * per series properties. * * @param renderer */ public DefaultShapeIRS(AbstractRenderer renderer) { super(renderer); } /** * @return the item shape the renderer defines for the series */ public Shape getItemShape(int row, int column) { return renderer.lookupSeriesShape(row); } }
2,379
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
DefaultVisibilityIRS.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/renderer/item/DefaultVisibilityIRS.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2013, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ------------------------- * DefaultVisibilityIRS.java * ------------------------- * (C) Copyright 2013, by Michael Zinsmaier. * * Original Author: Michael Zinsmaier; * Contributor(s): -; * * Changes * ------- * 17-Sep-2013 : Version 1 (MZ); * */ package org.jfree.chart.renderer.item; import org.jfree.chart.renderer.AbstractRenderer; /** * Implements a per series default item rendering strategy for the item visibility. * {@link DefaultItemRenderingStrategy} * * @author zinsmaie */ public class DefaultVisibilityIRS extends DefaultItemRenderingStrategy implements VisibilityIRS { /** a generated serial id */ private static final long serialVersionUID = 559211600589929630L; /** * creates a new rendering strategy for the submitted renderer using its per series properties * @param renderer */ public DefaultVisibilityIRS(AbstractRenderer renderer) { super(renderer); } /** * @return true if the renderer defines the series as visible */ public boolean getItemVisible(int row, int column) { return renderer.isSeriesVisible(row); } }
2,366
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
ShapeIRS.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/renderer/item/ShapeIRS.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2013, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ------------- * ShapeIRS.java * ------------- * (C) Copyright 2013, by Michael Zinsmaier. * * Original Author: Michael Zinsmaier; * Contributor(s): -; * * Changes * ------- * 17-Sep-2013 : Version 1 (MZ); * */ package org.jfree.chart.renderer.item; import java.awt.Shape; import java.io.Serializable; import org.jfree.chart.renderer.AbstractRenderer; /** * Defines an interface to control the shape of individual items during * rendering. Implementing classes can be used together with subclasses of * {@link AbstractRenderer} to control the rendering process.<br> * Works however only if the descendant of {@link AbstractRenderer} uses the * per item method {@link AbstractRenderer#getItemShape(int, int)} * <br> * <br> * Important Shape is not serializable see {@link IRSUtilities}) for the * correct implementation of the custom read and write method. * * @author zinsmaie */ public interface ShapeIRS extends Serializable { /** * Specifies an individual item by row, column and returns its shape. * * @param row the row (or series) index (zero-based). * @param column the column (or category) index (zero-based). * * @return a shape (never <code>null<code>) */ public Shape getItemShape(int row, int column); }
2,529
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
DefaultStrokeIRS.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/renderer/item/DefaultStrokeIRS.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2013, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * --------------------- * DefaultStrokeIRS.java * --------------------- * (C) Copyright 2013, by Michael Zinsmaier. * * Original Author: Michael Zinsmaier; * Contributor(s): -; * * Changes * ------- * 17-Sep-2013 : Version 1 (MZ); * */ package org.jfree.chart.renderer.item; import java.awt.Stroke; import org.jfree.chart.renderer.AbstractRenderer; /** * Implements a per series default item rendering strategy for the item stroke. * {@link DefaultItemRenderingStrategy} * * @author zinsmaie */ public class DefaultStrokeIRS extends DefaultItemRenderingStrategy implements StrokeIRS { /** a generated serial id */ private static final long serialVersionUID = -8486624082434186176L; /** * Creates a new rendering strategy for the submitted renderer using its * per series properties. * * @param renderer */ public DefaultStrokeIRS(AbstractRenderer renderer) { super(renderer); } /** * @return the item stroke the renderer defines for the series */ public Stroke getItemStroke(int row, int column) { return renderer.lookupSeriesStroke(row); } /** * @return the item outline stroke the renderer defines for the series */ public Stroke getItemOutlineStroke(int row, int column) { return renderer.lookupSeriesOutlineStroke(row); } }
2,608
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
SerialDate.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/date/SerialDate.java
/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2006, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * --------------- * SerialDate.java * --------------- * (C) Copyright 2001-2006, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: SerialDate.java,v 1.9 2011/10/17 20:08:22 mungady Exp $ * * Changes (from 11-Oct-2001) * -------------------------- * 11-Oct-2001 : Re-organised the class and moved it to new package * com.jrefinery.date (DG); * 05-Nov-2001 : Added a getDescription() method, and eliminated NotableDate * class (DG); * 12-Nov-2001 : IBD requires setDescription() method, now that NotableDate * class is gone (DG); Changed getPreviousDayOfWeek(), * getFollowingDayOfWeek() and getNearestDayOfWeek() to correct * bugs (DG); * 05-Dec-2001 : Fixed bug in SpreadsheetDate class (DG); * 29-May-2002 : Moved the month constants into a separate interface * (MonthConstants) (DG); * 27-Aug-2002 : Fixed bug in addMonths() method, thanks to N???levka Petr (DG); * 03-Oct-2002 : Fixed errors reported by Checkstyle (DG); * 13-Mar-2003 : Implemented Serializable (DG); * 29-May-2003 : Fixed bug in addMonths method (DG); * 04-Sep-2003 : Implemented Comparable. Updated the isInRange javadocs (DG); * 05-Jan-2005 : Fixed bug in addYears() method (1096282) (DG); * */ package org.jfree.chart.date; import java.io.Serializable; import java.text.DateFormatSymbols; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.GregorianCalendar; /** * An abstract class that defines our requirements for manipulating dates, * without tying down a particular implementation. * <P> * Requirement 1 : match at least what Excel does for dates; * Requirement 2 : the date represented by the class is immutable; * <P> * Why not just use java.util.Date? We will, when it makes sense. At times, * java.util.Date can be *too* precise - it represents an instant in time, * accurate to 1/1000th of a second (with the date itself depending on the * time-zone). Sometimes we just want to represent a particular day (e.g. 21 * January 2015) without concerning ourselves about the time of day, or the * time-zone, or anything else. That's what we've defined SerialDate for. * <P> * You can call getInstance() to get a concrete subclass of SerialDate, * without worrying about the exact implementation. * * @author David Gilbert */ public abstract class SerialDate implements Comparable, Serializable { /** For serialization. */ private static final long serialVersionUID = -293716040467423637L; /** Date format symbols. */ public static final DateFormatSymbols DATE_FORMAT_SYMBOLS = new SimpleDateFormat().getDateFormatSymbols(); /** The serial number for 1 January 1900. */ public static final int SERIAL_LOWER_BOUND = 2; /** The serial number for 31 December 9999. */ public static final int SERIAL_UPPER_BOUND = 2958465; /** The lowest year value supported by this date format. */ public static final int MINIMUM_YEAR_SUPPORTED = 1900; /** The highest year value supported by this date format. */ public static final int MAXIMUM_YEAR_SUPPORTED = 9999; /** Useful constant for Monday. Equivalent to java.util.Calendar.MONDAY. */ public static final int MONDAY = Calendar.MONDAY; /** * Useful constant for Tuesday. Equivalent to java.util.Calendar.TUESDAY. */ public static final int TUESDAY = Calendar.TUESDAY; /** * Useful constant for Wednesday. Equivalent to * java.util.Calendar.WEDNESDAY. */ public static final int WEDNESDAY = Calendar.WEDNESDAY; /** * Useful constant for Thrusday. Equivalent to java.util.Calendar.THURSDAY. */ public static final int THURSDAY = Calendar.THURSDAY; /** Useful constant for Friday. Equivalent to java.util.Calendar.FRIDAY. */ public static final int FRIDAY = Calendar.FRIDAY; /** * Useful constant for Saturday. Equivalent to java.util.Calendar.SATURDAY. */ public static final int SATURDAY = Calendar.SATURDAY; /** Useful constant for Sunday. Equivalent to java.util.Calendar.SUNDAY. */ public static final int SUNDAY = Calendar.SUNDAY; /** The number of days in each month in non leap years. */ static final int[] LAST_DAY_OF_MONTH = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; /** The number of days in a (non-leap) year up to the end of each month. */ static final int[] AGGREGATE_DAYS_TO_END_OF_MONTH = {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365}; /** The number of days in a year up to the end of the preceding month. */ static final int[] AGGREGATE_DAYS_TO_END_OF_PRECEDING_MONTH = {0, 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365}; /** The number of days in a leap year up to the end of each month. */ static final int[] LEAP_YEAR_AGGREGATE_DAYS_TO_END_OF_MONTH = {0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366}; /** * The number of days in a leap year up to the end of the preceding month. */ static final int[] LEAP_YEAR_AGGREGATE_DAYS_TO_END_OF_PRECEDING_MONTH = {0, 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366}; /** A useful constant for referring to the first week in a month. */ public static final int FIRST_WEEK_IN_MONTH = 1; /** A useful constant for referring to the second week in a month. */ public static final int SECOND_WEEK_IN_MONTH = 2; /** A useful constant for referring to the third week in a month. */ public static final int THIRD_WEEK_IN_MONTH = 3; /** A useful constant for referring to the fourth week in a month. */ public static final int FOURTH_WEEK_IN_MONTH = 4; /** A useful constant for referring to the last week in a month. */ public static final int LAST_WEEK_IN_MONTH = 0; /** Useful range constant. */ public static final int INCLUDE_NONE = 0; /** Useful range constant. */ public static final int INCLUDE_FIRST = 1; /** Useful range constant. */ public static final int INCLUDE_SECOND = 2; /** Useful range constant. */ public static final int INCLUDE_BOTH = 3; /** * Useful constant for specifying a day of the week relative to a fixed * date. */ public static final int PRECEDING = -1; /** * Useful constant for specifying a day of the week relative to a fixed * date. */ public static final int NEAREST = 0; /** * Useful constant for specifying a day of the week relative to a fixed * date. */ public static final int FOLLOWING = 1; /** A description for the date. */ private String description; /** * Default constructor. */ protected SerialDate() { } /** * Returns <code>true</code> if the supplied integer code represents a * valid day-of-the-week, and <code>false</code> otherwise. * * @param code the code being checked for validity. * * @return <code>true</code> if the supplied integer code represents a * valid day-of-the-week, and <code>false</code> otherwise. */ public static boolean isValidWeekdayCode(final int code) { switch(code) { case SUNDAY: case MONDAY: case TUESDAY: case WEDNESDAY: case THURSDAY: case FRIDAY: case SATURDAY: return true; default: return false; } } /** * Converts the supplied string to a day of the week. * * @param s a string representing the day of the week. * * @return <code>-1</code> if the string is not convertable, the day of * the week otherwise. */ public static int stringToWeekdayCode(String s) { final String[] shortWeekdayNames = DATE_FORMAT_SYMBOLS.getShortWeekdays(); final String[] weekDayNames = DATE_FORMAT_SYMBOLS.getWeekdays(); int result = -1; s = s.trim(); for (int i = 0; i < weekDayNames.length; i++) { if (s.equals(shortWeekdayNames[i])) { result = i; break; } if (s.equals(weekDayNames[i])) { result = i; break; } } return result; } /** * Returns a string representing the supplied day-of-the-week. * <P> * Need to find a better approach. * * @param weekday the day of the week. * * @return a string representing the supplied day-of-the-week. */ public static String weekdayCodeToString(final int weekday) { final String[] weekdays = DATE_FORMAT_SYMBOLS.getWeekdays(); return weekdays[weekday]; } /** * Returns an array of month names. * * @return an array of month names. */ public static String[] getMonths() { return getMonths(false); } /** * Returns an array of month names. * * @param shortened a flag indicating that shortened month names should * be returned. * * @return an array of month names. */ public static String[] getMonths(final boolean shortened) { if (shortened) { return DATE_FORMAT_SYMBOLS.getShortMonths(); } else { return DATE_FORMAT_SYMBOLS.getMonths(); } } /** * Returns true if the supplied integer code represents a valid month. * * @param code the code being checked for validity. * * @return <code>true</code> if the supplied integer code represents a * valid month. */ public static boolean isValidMonthCode(final int code) { switch(code) { case MonthConstants.JANUARY: case MonthConstants.FEBRUARY: case MonthConstants.MARCH: case MonthConstants.APRIL: case MonthConstants.MAY: case MonthConstants.JUNE: case MonthConstants.JULY: case MonthConstants.AUGUST: case MonthConstants.SEPTEMBER: case MonthConstants.OCTOBER: case MonthConstants.NOVEMBER: case MonthConstants.DECEMBER: return true; default: return false; } } /** * Returns the quarter for the specified month. * * @param code the month code (1-12). * * @return the quarter that the month belongs to. */ public static int monthCodeToQuarter(final int code) { switch(code) { case MonthConstants.JANUARY: case MonthConstants.FEBRUARY: case MonthConstants.MARCH: return 1; case MonthConstants.APRIL: case MonthConstants.MAY: case MonthConstants.JUNE: return 2; case MonthConstants.JULY: case MonthConstants.AUGUST: case MonthConstants.SEPTEMBER: return 3; case MonthConstants.OCTOBER: case MonthConstants.NOVEMBER: case MonthConstants.DECEMBER: return 4; default: throw new IllegalArgumentException( "SerialDate.monthCodeToQuarter: invalid month code."); } } /** * Returns a string representing the supplied month. * <P> * The string returned is the long form of the month name taken from the * default locale. * * @param month the month. * * @return a string representing the supplied month. */ public static String monthCodeToString(final int month) { return monthCodeToString(month, false); } /** * Returns a string representing the supplied month. * <P> * The string returned is the long or short form of the month name taken * from the default locale. * * @param month the month. * @param shortened if <code>true</code> return the abbreviation of the * month. * * @return a string representing the supplied month. */ public static String monthCodeToString(final int month, final boolean shortened) { // check arguments... if (!isValidMonthCode(month)) { throw new IllegalArgumentException( "SerialDate.monthCodeToString: month outside valid range."); } final String[] months; if (shortened) { months = DATE_FORMAT_SYMBOLS.getShortMonths(); } else { months = DATE_FORMAT_SYMBOLS.getMonths(); } return months[month - 1]; } /** * Converts a string to a month code. * <P> * This method will return one of the constants JANUARY, FEBRUARY, ..., * DECEMBER that corresponds to the string. If the string is not * recognised, this method returns -1. * * @param s the string to parse. * * @return <code>-1</code> if the string is not parseable, the month of the * year otherwise. */ public static int stringToMonthCode(String s) { final String[] shortMonthNames = DATE_FORMAT_SYMBOLS.getShortMonths(); final String[] monthNames = DATE_FORMAT_SYMBOLS.getMonths(); int result = -1; s = s.trim(); // first try parsing the string as an integer (1-12)... try { result = Integer.parseInt(s); } catch (NumberFormatException e) { // suppress } // now search through the month names... if ((result < 1) || (result > 12)) { for (int i = 0; i < monthNames.length; i++) { if (s.equals(shortMonthNames[i])) { result = i + 1; break; } if (s.equals(monthNames[i])) { result = i + 1; break; } } } return result; } /** * Returns true if the supplied integer code represents a valid * week-in-the-month, and false otherwise. * * @param code the code being checked for validity. * @return <code>true</code> if the supplied integer code represents a * valid week-in-the-month. */ public static boolean isValidWeekInMonthCode(final int code) { switch(code) { case FIRST_WEEK_IN_MONTH: case SECOND_WEEK_IN_MONTH: case THIRD_WEEK_IN_MONTH: case FOURTH_WEEK_IN_MONTH: case LAST_WEEK_IN_MONTH: return true; default: return false; } } /** * Determines whether or not the specified year is a leap year. * * @param yyyy the year (in the range 1900 to 9999). * * @return <code>true</code> if the specified year is a leap year. */ public static boolean isLeapYear(final int yyyy) { if ((yyyy % 4) != 0) { return false; } else if ((yyyy % 400) == 0) { return true; } else if ((yyyy % 100) == 0) { return false; } else { return true; } } /** * Returns the number of leap years from 1900 to the specified year * INCLUSIVE. * <P> * Note that 1900 is not a leap year. * * @param yyyy the year (in the range 1900 to 9999). * * @return the number of leap years from 1900 to the specified year. */ public static int leapYearCount(final int yyyy) { final int leap4 = (yyyy - 1896) / 4; final int leap100 = (yyyy - 1800) / 100; final int leap400 = (yyyy - 1600) / 400; return leap4 - leap100 + leap400; } /** * Returns the number of the last day of the month, taking into account * leap years. * * @param month the month. * @param yyyy the year (in the range 1900 to 9999). * * @return the number of the last day of the month. */ public static int lastDayOfMonth(final int month, final int yyyy) { final int result = LAST_DAY_OF_MONTH[month]; if (month != MonthConstants.FEBRUARY) { return result; } else if (isLeapYear(yyyy)) { return result + 1; } else { return result; } } /** * Creates a new date by adding the specified number of days to the base * date. * * @param days the number of days to add (can be negative). * @param base the base date. * * @return a new date. */ public static SerialDate addDays(final int days, final SerialDate base) { final int serialDayNumber = base.toSerial() + days; return SerialDate.createInstance(serialDayNumber); } /** * Creates a new date by adding the specified number of months to the base * date. * <P> * If the base date is close to the end of the month, the day on the result * may be adjusted slightly: 31 May + 1 month = 30 June. * * @param months the number of months to add (can be negative). * @param base the base date. * * @return a new date. */ public static SerialDate addMonths(final int months, final SerialDate base) { final int yy = (12 * base.getYYYY() + base.getMonth() + months - 1) / 12; final int mm = (12 * base.getYYYY() + base.getMonth() + months - 1) % 12 + 1; final int dd = Math.min( base.getDayOfMonth(), SerialDate.lastDayOfMonth(mm, yy) ); return SerialDate.createInstance(dd, mm, yy); } /** * Creates a new date by adding the specified number of years to the base * date. * * @param years the number of years to add (can be negative). * @param base the base date. * * @return A new date. */ public static SerialDate addYears(final int years, final SerialDate base) { final int baseY = base.getYYYY(); final int baseM = base.getMonth(); final int baseD = base.getDayOfMonth(); final int targetY = baseY + years; final int targetD = Math.min( baseD, SerialDate.lastDayOfMonth(baseM, targetY) ); return SerialDate.createInstance(targetD, baseM, targetY); } /** * Returns the latest date that falls on the specified day-of-the-week and * is BEFORE the base date. * * @param targetWeekday a code for the target day-of-the-week. * @param base the base date. * * @return the latest date that falls on the specified day-of-the-week and * is BEFORE the base date. */ public static SerialDate getPreviousDayOfWeek(final int targetWeekday, final SerialDate base) { // check arguments... if (!SerialDate.isValidWeekdayCode(targetWeekday)) { throw new IllegalArgumentException( "Invalid day-of-the-week code." ); } // find the date... final int adjust; final int baseDOW = base.getDayOfWeek(); if (baseDOW > targetWeekday) { adjust = Math.min(0, targetWeekday - baseDOW); } else { adjust = -7 + Math.max(0, targetWeekday - baseDOW); } return SerialDate.addDays(adjust, base); } /** * Returns the earliest date that falls on the specified day-of-the-week * and is AFTER the base date. * * @param targetWeekday a code for the target day-of-the-week. * @param base the base date. * * @return the earliest date that falls on the specified day-of-the-week * and is AFTER the base date. */ public static SerialDate getFollowingDayOfWeek(final int targetWeekday, final SerialDate base) { // check arguments... if (!SerialDate.isValidWeekdayCode(targetWeekday)) { throw new IllegalArgumentException( "Invalid day-of-the-week code." ); } // find the date... final int adjust; final int baseDOW = base.getDayOfWeek(); if (baseDOW > targetWeekday) { adjust = 7 + Math.min(0, targetWeekday - baseDOW); } else { adjust = Math.max(0, targetWeekday - baseDOW); } return SerialDate.addDays(adjust, base); } /** * Returns the date that falls on the specified day-of-the-week and is * CLOSEST to the base date. * * @param targetDOW a code for the target day-of-the-week. * @param base the base date. * * @return the date that falls on the specified day-of-the-week and is * CLOSEST to the base date. */ public static SerialDate getNearestDayOfWeek(final int targetDOW, final SerialDate base) { // check arguments... if (!SerialDate.isValidWeekdayCode(targetDOW)) { throw new IllegalArgumentException( "Invalid day-of-the-week code." ); } // find the date... final int baseDOW = base.getDayOfWeek(); int adjust = -Math.abs(targetDOW - baseDOW); if (adjust >= 4) { adjust = 7 - adjust; } if (adjust <= -4) { adjust = 7 + adjust; } return SerialDate.addDays(adjust, base); } /** * Rolls the date forward to the last day of the month. * * @param base the base date. * * @return a new serial date. */ public SerialDate getEndOfCurrentMonth(final SerialDate base) { final int last = SerialDate.lastDayOfMonth( base.getMonth(), base.getYYYY() ); return SerialDate.createInstance(last, base.getMonth(), base.getYYYY()); } /** * Returns a string corresponding to the week-in-the-month code. * <P> * Need to find a better approach. * * @param count an integer code representing the week-in-the-month. * * @return a string corresponding to the week-in-the-month code. */ public static String weekInMonthToString(final int count) { switch (count) { case SerialDate.FIRST_WEEK_IN_MONTH : return "First"; case SerialDate.SECOND_WEEK_IN_MONTH : return "Second"; case SerialDate.THIRD_WEEK_IN_MONTH : return "Third"; case SerialDate.FOURTH_WEEK_IN_MONTH : return "Fourth"; case SerialDate.LAST_WEEK_IN_MONTH : return "Last"; default : return "SerialDate.weekInMonthToString(): invalid code."; } } /** * Returns a string representing the supplied 'relative'. * <P> * Need to find a better approach. * * @param relative a constant representing the 'relative'. * * @return a string representing the supplied 'relative'. */ public static String relativeToString(final int relative) { switch (relative) { case SerialDate.PRECEDING : return "Preceding"; case SerialDate.NEAREST : return "Nearest"; case SerialDate.FOLLOWING : return "Following"; default : return "ERROR : Relative To String"; } } /** * Factory method that returns an instance of some concrete subclass of * {@link SerialDate}. * * @param day the day (1-31). * @param month the month (1-12). * @param yyyy the year (in the range 1900 to 9999). * * @return An instance of {@link SerialDate}. */ public static SerialDate createInstance(final int day, final int month, final int yyyy) { return new SpreadsheetDate(day, month, yyyy); } /** * Factory method that returns an instance of some concrete subclass of * {@link SerialDate}. * * @param serial the serial number for the day (1 January 1900 = 2). * * @return a instance of SerialDate. */ public static SerialDate createInstance(final int serial) { return new SpreadsheetDate(serial); } /** * Factory method that returns an instance of a subclass of SerialDate. * * @param date A Java date object. * * @return a instance of SerialDate. */ public static SerialDate createInstance(final java.util.Date date) { final GregorianCalendar calendar = new GregorianCalendar(); calendar.setTime(date); return new SpreadsheetDate(calendar.get(Calendar.DATE), calendar.get(Calendar.MONTH) + 1, calendar.get(Calendar.YEAR)); } /** * Returns the serial number for the date, where 1 January 1900 = 2 (this * corresponds, almost, to the numbering system used in Microsoft Excel for * Windows and Lotus 1-2-3). * * @return the serial number for the date. */ public abstract int toSerial(); /** * Returns a java.util.Date. Since java.util.Date has more precision than * SerialDate, we need to define a convention for the 'time of day'. * * @return this as <code>java.util.Date</code>. */ public abstract java.util.Date toDate(); /** * Returns the description that is attached to the date. It is not * required that a date have a description, but for some applications it * is useful. * * @return The description (possibly <code>null</code>). */ public String getDescription() { return this.description; } /** * Sets the description for the date. * * @param description the description for this date (<code>null</code> * permitted). */ public void setDescription(final String description) { this.description = description; } /** * Converts the date to a string. * * @return a string representation of the date. */ @Override public String toString() { return getDayOfMonth() + "-" + SerialDate.monthCodeToString(getMonth()) + "-" + getYYYY(); } /** * Returns the year (assume a valid range of 1900 to 9999). * * @return the year. */ public abstract int getYYYY(); /** * Returns the month (January = 1, February = 2, March = 3). * * @return the month of the year. */ public abstract int getMonth(); /** * Returns the day of the month. * * @return the day of the month. */ public abstract int getDayOfMonth(); /** * Returns the day of the week. * * @return the day of the week. */ public abstract int getDayOfWeek(); /** * Returns the difference (in days) between this date and the specified * 'other' date. * <P> * The result is positive if this date is after the 'other' date and * negative if it is before the 'other' date. * * @param other the date being compared to. * * @return the difference between this and the other date. */ public abstract int compare(SerialDate other); /** * Returns true if this SerialDate represents the same date as the * specified SerialDate. * * @param other the date being compared to. * * @return <code>true</code> if this SerialDate represents the same date as * the specified SerialDate. */ public abstract boolean isOn(SerialDate other); /** * Returns true if this SerialDate represents an earlier date compared to * the specified SerialDate. * * @param other The date being compared to. * * @return <code>true</code> if this SerialDate represents an earlier date * compared to the specified SerialDate. */ public abstract boolean isBefore(SerialDate other); /** * Returns true if this SerialDate represents the same date as the * specified SerialDate. * * @param other the date being compared to. * * @return <code>true</code> if this SerialDate represents the same date * as the specified SerialDate. */ public abstract boolean isOnOrBefore(SerialDate other); /** * Returns true if this SerialDate represents the same date as the * specified SerialDate. * * @param other the date being compared to. * * @return <code>true</code> if this SerialDate represents the same date * as the specified SerialDate. */ public abstract boolean isAfter(SerialDate other); /** * Returns true if this SerialDate represents the same date as the * specified SerialDate. * * @param other the date being compared to. * * @return <code>true</code> if this SerialDate represents the same date * as the specified SerialDate. */ public abstract boolean isOnOrAfter(SerialDate other); /** * Returns <code>true</code> if this {@link SerialDate} is within the * specified range (INCLUSIVE). The date order of d1 and d2 is not * important. * * @param d1 a boundary date for the range. * @param d2 the other boundary date for the range. * * @return A boolean. */ public abstract boolean isInRange(SerialDate d1, SerialDate d2); /** * Returns <code>true</code> if this {@link SerialDate} is within the * specified range (caller specifies whether or not the end-points are * included). The date order of d1 and d2 is not important. * * @param d1 a boundary date for the range. * @param d2 the other boundary date for the range. * @param include a code that controls whether or not the start and end * dates are included in the range. * * @return A boolean. */ public abstract boolean isInRange(SerialDate d1, SerialDate d2, int include); /** * Returns the latest date that falls on the specified day-of-the-week and * is BEFORE this date. * * @param targetDOW a code for the target day-of-the-week. * * @return the latest date that falls on the specified day-of-the-week and * is BEFORE this date. */ public SerialDate getPreviousDayOfWeek(final int targetDOW) { return getPreviousDayOfWeek(targetDOW, this); } /** * Returns the earliest date that falls on the specified day-of-the-week * and is AFTER this date. * * @param targetDOW a code for the target day-of-the-week. * * @return the earliest date that falls on the specified day-of-the-week * and is AFTER this date. */ public SerialDate getFollowingDayOfWeek(final int targetDOW) { return getFollowingDayOfWeek(targetDOW, this); } /** * Returns the nearest date that falls on the specified day-of-the-week. * * @param targetDOW a code for the target day-of-the-week. * * @return the nearest date that falls on the specified day-of-the-week. */ public SerialDate getNearestDayOfWeek(final int targetDOW) { return getNearestDayOfWeek(targetDOW, this); } }
33,028
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
SpreadsheetDate.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/date/SpreadsheetDate.java
/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2006, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * -------------------- * SpreadsheetDate.java * -------------------- * (C) Copyright 2000-2006, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: SpreadsheetDate.java,v 1.10 2006/08/29 13:59:30 mungady Exp $ * * Changes * ------- * 11-Oct-2001 : Version 1 (DG); * 05-Nov-2001 : Added getDescription() and setDescription() methods (DG); * 12-Nov-2001 : Changed name from ExcelDate.java to SpreadsheetDate.java (DG); * Fixed a bug in calculating day, month and year from serial * number (DG); * 24-Jan-2002 : Fixed a bug in calculating the serial number from the day, * month and year. Thanks to Trevor Hills for the report (DG); * 29-May-2002 : Added equals(Object) method (SourceForge ID 558850) (DG); * 03-Oct-2002 : Fixed errors reported by Checkstyle (DG); * 13-Mar-2003 : Implemented Serializable (DG); * 04-Sep-2003 : Completed isInRange() methods (DG); * 05-Sep-2003 : Implemented Comparable (DG); * 21-Oct-2003 : Added hashCode() method (DG); * 29-Aug-2006 : Removed redundant description attribute (DG); * */ package org.jfree.chart.date; import java.util.Calendar; import java.util.Date; /** * Represents a date using an integer, in a similar fashion to the * implementation in Microsoft Excel. The range of dates supported is * 1-Jan-1900 to 31-Dec-9999. * <P> * Be aware that there is a deliberate bug in Excel that recognises the year * 1900 as a leap year when in fact it is not a leap year. You can find more * information on the Microsoft website in article Q181370: * <P> * http://support.microsoft.com/support/kb/articles/Q181/3/70.asp * <P> * Excel uses the convention that 1-Jan-1900 = 1. This class uses the * convention 1-Jan-1900 = 2. * The result is that the day number in this class will be different to the * Excel figure for January and February 1900...but then Excel adds in an extra * day (29-Feb-1900 which does not actually exist!) and from that point forward * the day numbers will match. * * @author David Gilbert */ public class SpreadsheetDate extends SerialDate { /** For serialization. */ private static final long serialVersionUID = -2039586705374454461L; /** * The day number (1-Jan-1900 = 2, 2-Jan-1900 = 3, ..., 31-Dec-9999 = * 2958465). */ private final int serial; /** The day of the month (1 to 28, 29, 30 or 31 depending on the month). */ private final int day; /** The month of the year (1 to 12). */ private final int month; /** The year (1900 to 9999). */ private final int year; /** * Creates a new date instance. * * @param day the day (in the range 1 to 28/29/30/31). * @param month the month (in the range 1 to 12). * @param year the year (in the range 1900 to 9999). */ public SpreadsheetDate(final int day, final int month, final int year) { if ((year >= 1900) && (year <= 9999)) { this.year = year; } else { throw new IllegalArgumentException( "The 'year' argument must be in range 1900 to 9999." ); } if ((month >= MonthConstants.JANUARY) && (month <= MonthConstants.DECEMBER)) { this.month = month; } else { throw new IllegalArgumentException( "The 'month' argument must be in the range 1 to 12." ); } if ((day >= 1) && (day <= SerialDate.lastDayOfMonth(month, year))) { this.day = day; } else { throw new IllegalArgumentException("Invalid 'day' argument."); } // the serial number needs to be synchronised with the day-month-year... this.serial = calcSerial(day, month, year); } /** * Standard constructor - creates a new date object representing the * specified day number (which should be in the range 2 to 2958465. * * @param serial the serial number for the day (range: 2 to 2958465). */ public SpreadsheetDate(final int serial) { if ((serial >= SERIAL_LOWER_BOUND) && (serial <= SERIAL_UPPER_BOUND)) { this.serial = serial; } else { throw new IllegalArgumentException( "SpreadsheetDate: Serial must be in range 2 to 2958465."); } // the day-month-year needs to be synchronised with the serial number... // get the year from the serial date final int days = this.serial - SERIAL_LOWER_BOUND; // overestimated because we ignored leap days final int overestimatedYYYY = 1900 + (days / 365); final int leaps = SerialDate.leapYearCount(overestimatedYYYY); final int nonleapdays = days - leaps; // underestimated because we overestimated years int underestimatedYYYY = 1900 + (nonleapdays / 365); if (underestimatedYYYY == overestimatedYYYY) { this.year = underestimatedYYYY; } else { int ss1 = calcSerial(1, 1, underestimatedYYYY); while (ss1 <= this.serial) { underestimatedYYYY = underestimatedYYYY + 1; ss1 = calcSerial(1, 1, underestimatedYYYY); } this.year = underestimatedYYYY - 1; } final int ss2 = calcSerial(1, 1, this.year); int[] daysToEndOfPrecedingMonth = AGGREGATE_DAYS_TO_END_OF_PRECEDING_MONTH; if (isLeapYear(this.year)) { daysToEndOfPrecedingMonth = LEAP_YEAR_AGGREGATE_DAYS_TO_END_OF_PRECEDING_MONTH; } // get the month from the serial date int mm = 1; int sss = ss2 + daysToEndOfPrecedingMonth[mm] - 1; while (sss < this.serial) { mm = mm + 1; sss = ss2 + daysToEndOfPrecedingMonth[mm] - 1; } this.month = mm - 1; // what's left is d(+1); this.day = this.serial - ss2 - daysToEndOfPrecedingMonth[this.month] + 1; } /** * Returns the serial number for the date, where 1 January 1900 = 2 * (this corresponds, almost, to the numbering system used in Microsoft * Excel for Windows and Lotus 1-2-3). * * @return The serial number of this date. */ @Override public int toSerial() { return this.serial; } /** * Returns a <code>java.util.Date</code> equivalent to this date. * * @return The date. */ @Override public Date toDate() { final Calendar calendar = Calendar.getInstance(); calendar.set(getYYYY(), getMonth() - 1, getDayOfMonth(), 0, 0, 0); return calendar.getTime(); } /** * Returns the year (assume a valid range of 1900 to 9999). * * @return The year. */ @Override public int getYYYY() { return this.year; } /** * Returns the month (January = 1, February = 2, March = 3). * * @return The month of the year. */ @Override public int getMonth() { return this.month; } /** * Returns the day of the month. * * @return The day of the month. */ @Override public int getDayOfMonth() { return this.day; } /** * Returns a code representing the day of the week. * <P> * The codes are defined in the {@link SerialDate} class as: * <code>SUNDAY</code>, <code>MONDAY</code>, <code>TUESDAY</code>, * <code>WEDNESDAY</code>, <code>THURSDAY</code>, <code>FRIDAY</code>, and * <code>SATURDAY</code>. * * @return A code representing the day of the week. */ @Override public int getDayOfWeek() { return (this.serial + 6) % 7 + 1; } /** * Tests the equality of this date with an arbitrary object. * <P> * This method will return true ONLY if the object is an instance of the * {@link SerialDate} base class, and it represents the same day as this * {@link SpreadsheetDate}. * * @param object the object to compare (<code>null</code> permitted). * * @return A boolean. */ @Override public boolean equals(final Object object) { if (object instanceof SerialDate) { final SerialDate s = (SerialDate) object; return (s.toSerial() == this.toSerial()); } else { return false; } } /** * Returns a hash code for this object instance. * * @return A hash code. */ @Override public int hashCode() { return toSerial(); } /** * Returns the difference (in days) between this date and the specified * 'other' date. * * @param other the date being compared to. * * @return The difference (in days) between this date and the specified * 'other' date. */ @Override public int compare(final SerialDate other) { return this.serial - other.toSerial(); } /** * Implements the method required by the Comparable interface. * * @param other the other object (usually another SerialDate). * * @return A negative integer, zero, or a positive integer as this object * is less than, equal to, or greater than the specified object. */ @Override public int compareTo(final Object other) { return compare((SerialDate) other); } /** * Returns true if this SerialDate represents the same date as the * specified SerialDate. * * @param other the date being compared to. * * @return <code>true</code> if this SerialDate represents the same date as * the specified SerialDate. */ @Override public boolean isOn(final SerialDate other) { return (this.serial == other.toSerial()); } /** * Returns true if this SerialDate represents an earlier date compared to * the specified SerialDate. * * @param other the date being compared to. * * @return <code>true</code> if this SerialDate represents an earlier date * compared to the specified SerialDate. */ @Override public boolean isBefore(final SerialDate other) { return (this.serial < other.toSerial()); } /** * Returns true if this SerialDate represents the same date as the * specified SerialDate. * * @param other the date being compared to. * * @return <code>true</code> if this SerialDate represents the same date * as the specified SerialDate. */ @Override public boolean isOnOrBefore(final SerialDate other) { return (this.serial <= other.toSerial()); } /** * Returns true if this SerialDate represents the same date as the * specified SerialDate. * * @param other the date being compared to. * * @return <code>true</code> if this SerialDate represents the same date * as the specified SerialDate. */ @Override public boolean isAfter(final SerialDate other) { return (this.serial > other.toSerial()); } /** * Returns true if this SerialDate represents the same date as the * specified SerialDate. * * @param other the date being compared to. * * @return <code>true</code> if this SerialDate represents the same date as * the specified SerialDate. */ @Override public boolean isOnOrAfter(final SerialDate other) { return (this.serial >= other.toSerial()); } /** * Returns <code>true</code> if this {@link SerialDate} is within the * specified range (INCLUSIVE). The date order of d1 and d2 is not * important. * * @param d1 a boundary date for the range. * @param d2 the other boundary date for the range. * * @return A boolean. */ @Override public boolean isInRange(final SerialDate d1, final SerialDate d2) { return isInRange(d1, d2, SerialDate.INCLUDE_BOTH); } /** * Returns true if this SerialDate is within the specified range (caller * specifies whether or not the end-points are included). The order of d1 * and d2 is not important. * * @param d1 one boundary date for the range. * @param d2 a second boundary date for the range. * @param include a code that controls whether or not the start and end * dates are included in the range. * * @return <code>true</code> if this SerialDate is within the specified * range. */ @Override public boolean isInRange(final SerialDate d1, final SerialDate d2, final int include) { final int s1 = d1.toSerial(); final int s2 = d2.toSerial(); final int start = Math.min(s1, s2); final int end = Math.max(s1, s2); final int s = toSerial(); if (include == SerialDate.INCLUDE_BOTH) { return (s >= start && s <= end); } else if (include == SerialDate.INCLUDE_FIRST) { return (s >= start && s < end); } else if (include == SerialDate.INCLUDE_SECOND) { return (s > start && s <= end); } else { return (s > start && s < end); } } /** * Calculate the serial number from the day, month and year. * <P> * 1-Jan-1900 = 2. * * @param d the day. * @param m the month. * @param y the year. * * @return the serial number from the day, month and year. */ private int calcSerial(final int d, final int m, final int y) { final int yy = ((y - 1900) * 365) + SerialDate.leapYearCount(y - 1); int mm = SerialDate.AGGREGATE_DAYS_TO_END_OF_PRECEDING_MONTH[m]; if (m > MonthConstants.FEBRUARY) { if (SerialDate.isLeapYear(y)) { mm = mm + 1; } } final int dd = d; return yy + mm + dd + 1; } }
15,332
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
MonthConstants.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/date/MonthConstants.java
/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------- * MonthConstants.java * ------------------- * (C) Copyright 2002, 2003, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: MonthConstants.java,v 1.4 2005/11/16 15:58:40 taqua Exp $ * * Changes * ------- * 29-May-2002 : Version 1 (code moved from SerialDate class) (DG); * */ package org.jfree.chart.date; /** * Useful constants for months. Note that these are NOT equivalent to the * constants defined by java.util.Calendar (where JANUARY=0 and DECEMBER=11). * <P> * Used by the SerialDate and RegularTimePeriod classes. * * @author David Gilbert */ public final class MonthConstants { /** Constant for January. */ public static final int JANUARY = 1; /** Constant for February. */ public static final int FEBRUARY = 2; /** Constant for March. */ public static final int MARCH = 3; /** Constant for April. */ public static final int APRIL = 4; /** Constant for May. */ public static final int MAY = 5; /** Constant for June. */ public static final int JUNE = 6; /** Constant for July. */ public static final int JULY = 7; /** Constant for August. */ public static final int AUGUST = 8; /** Constant for September. */ public static final int SEPTEMBER = 9; /** Constant for October. */ public static final int OCTOBER = 10; /** Constant for November. */ public static final int NOVEMBER = 11; /** Constant for December. */ public static final int DECEMBER = 12; }
2,844
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
ShortTextTitle.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/title/ShortTextTitle.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ------------------- * ShortTextTitle.java * ------------------- * (C) Copyright 2008-2012, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 28-Apr-2008 : Version 1 (DG); * 17-Jun-2012 : Removed JCommon dependencies (DG); * */ package org.jfree.chart.title; import java.awt.FontMetrics; import java.awt.Graphics2D; import java.awt.geom.Rectangle2D; import org.jfree.chart.block.LengthConstraintType; import org.jfree.chart.block.RectangleConstraint; import org.jfree.chart.ui.Size2D; import org.jfree.chart.ui.TextAnchor; import org.jfree.chart.text.TextUtilities; import org.jfree.data.Range; /** * A text title that is only displayed if the entire text will be visible * without line wrapping. It is only intended for use with short titles - for * general purpose titles, you should use the {@link TextTitle} class. * * @since 1.0.10 * * @see TextTitle */ public class ShortTextTitle extends TextTitle { /** * Creates a new title. * * @param text the text (<code>null</code> not permitted). */ public ShortTextTitle(String text) { setText(text); } /** * Performs a layout for this title, subject to the supplied constraint, * and returns the dimensions required for the title (if the title * cannot be displayed in the available space, this method will return * zero width and height for the dimensions). * * @param g2 the graphics target. * @param constraint the layout constraints. * * @return The dimensions for the title. */ @Override public Size2D arrange(Graphics2D g2, RectangleConstraint constraint) { RectangleConstraint cc = toContentConstraint(constraint); LengthConstraintType w = cc.getWidthConstraintType(); LengthConstraintType h = cc.getHeightConstraintType(); Size2D contentSize = null; if (w == LengthConstraintType.NONE) { if (h == LengthConstraintType.NONE) { contentSize = arrangeNN(g2); } else if (h == LengthConstraintType.RANGE) { throw new RuntimeException("Not yet implemented."); } else if (h == LengthConstraintType.FIXED) { throw new RuntimeException("Not yet implemented."); } } else if (w == LengthConstraintType.RANGE) { if (h == LengthConstraintType.NONE) { contentSize = arrangeRN(g2, cc.getWidthRange()); } else if (h == LengthConstraintType.RANGE) { contentSize = arrangeRR(g2, cc.getWidthRange(), cc.getHeightRange()); } else if (h == LengthConstraintType.FIXED) { throw new RuntimeException("Not yet implemented."); } } else if (w == LengthConstraintType.FIXED) { if (h == LengthConstraintType.NONE) { contentSize = arrangeFN(g2, cc.getWidth()); } else if (h == LengthConstraintType.RANGE) { throw new RuntimeException("Not yet implemented."); } else if (h == LengthConstraintType.FIXED) { throw new RuntimeException("Not yet implemented."); } } if (contentSize.width <= 0.0 || contentSize.height <= 0.0) { return new Size2D(0.0, 0.0); } else { return new Size2D(calculateTotalWidth(contentSize.getWidth()), calculateTotalHeight(contentSize.getHeight())); } } /** * Arranges the content for this title assuming no bounds on the width * or the height, and returns the required size. * * @param g2 the graphics target. * * @return The content size. */ @Override protected Size2D arrangeNN(Graphics2D g2) { Range max = new Range(0.0, Float.MAX_VALUE); return arrangeRR(g2, max, max); } /** * Arranges the content for this title assuming a range constraint for the * width and no bounds on the height, and returns the required size. * * @param g2 the graphics target. * @param widthRange the range for the width. * * @return The content size. */ @Override protected Size2D arrangeRN(Graphics2D g2, Range widthRange) { Size2D s = arrangeNN(g2); if (widthRange.contains(s.getWidth())) { return s; } double ww = widthRange.constrain(s.getWidth()); return arrangeFN(g2, ww); } /** * Arranges the content for this title assuming a fixed width and no bounds * on the height, and returns the required size. This will reflect the * fact that a text title positioned on the left or right of a chart will * be rotated by 90 degrees. * * @param g2 the graphics target. * @param w the width. * * @return The content size. */ @Override protected Size2D arrangeFN(Graphics2D g2, double w) { g2.setFont(getFont()); FontMetrics fm = g2.getFontMetrics(getFont()); Rectangle2D bounds = TextUtilities.getTextBounds(getText(), g2, fm); if (bounds.getWidth() <= w) { return new Size2D(w, bounds.getHeight()); } else { return new Size2D(0.0, 0.0); } } /** * Returns the content size for the title. * * @param g2 the graphics device. * @param widthRange the width range. * @param heightRange the height range. * * @return The content size. */ @Override protected Size2D arrangeRR(Graphics2D g2, Range widthRange, Range heightRange) { g2.setFont(getFont()); FontMetrics fm = g2.getFontMetrics(getFont()); Rectangle2D bounds = TextUtilities.getTextBounds(getText(), g2, fm); if (bounds.getWidth() <= widthRange.getUpperBound() && bounds.getHeight() <= heightRange.getUpperBound()) { return new Size2D(bounds.getWidth(), bounds.getHeight()); } else { return new Size2D(0.0, 0.0); } } /** * Draws the title using the current font and paint. * * @param g2 the graphics target. * @param area the title area. * @param params optional parameters (ignored here). * * @return <code>null</code>. */ @Override public Object draw(Graphics2D g2, Rectangle2D area, Object params) { if (area.isEmpty()) { return null; } area = trimMargin(area); drawBorder(g2, area); area = trimBorder(area); area = trimPadding(area); g2.setFont(getFont()); g2.setPaint(getPaint()); TextUtilities.drawAlignedString(getText(), g2, (float) area.getMinX(), (float) area.getMinY(), TextAnchor.TOP_LEFT); return null; } }
8,261
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
CompositeTitle.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/title/CompositeTitle.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ------------------- * CompositeTitle.java * ------------------- * (C) Copyright 2005-2012, by David Gilbert and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): Eric Penfold (patch 2006826); * * Changes * ------- * 19-Nov-2004 : Version 1 (DG); * 11-Jan-2005 : Removed deprecated code in preparation for 1.0.0 release (DG); * 04-Feb-2005 : Implemented MAXIMUM_WIDTH in calculateSize (DG); * 20-Apr-2005 : Added new draw() method (DG); * 03-May-2005 : Implemented equals() method (DG); * 02-Jul-2008 : Applied patch 2006826 by Eric Penfold, to enable chart * entities to be generated (DG); * 09-Jul-2008 : Added backgroundPaint field (DG); * 17-Jun-2012 : Removed JCommon dependencies (DG); * */ package org.jfree.chart.title; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.geom.Rectangle2D; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import org.jfree.chart.block.BlockContainer; import org.jfree.chart.block.BorderArrangement; import org.jfree.chart.block.RectangleConstraint; import org.jfree.chart.ui.Size2D; import org.jfree.chart.util.PaintUtilities; import org.jfree.chart.event.TitleChangeEvent; import org.jfree.chart.util.SerialUtilities; /** * A title that contains multiple titles within a {@link BlockContainer}. */ public class CompositeTitle extends Title implements Cloneable, Serializable { /** For serialization. */ private static final long serialVersionUID = -6770854036232562290L; /** * The background paint. * * @since 1.0.11 */ private transient Paint backgroundPaint; /** A container for the individual titles. */ private BlockContainer container; /** * Creates a new composite title with a default border arrangement. */ public CompositeTitle() { this(new BlockContainer(new BorderArrangement())); } /** * Creates a new title using the specified container. * * @param container the container (<code>null</code> not permitted). */ public CompositeTitle(BlockContainer container) { if (container == null) { throw new IllegalArgumentException("Null 'container' argument."); } this.container = container; this.backgroundPaint = null; } /** * Returns the background paint. * * @return The paint (possibly <code>null</code>). * * @since 1.0.11 */ public Paint getBackgroundPaint() { return this.backgroundPaint; } /** * Sets the background paint and sends a {@link TitleChangeEvent} to all * registered listeners. If you set this attribute to <code>null</code>, * no background is painted (which makes the title background transparent). * * @param paint the background paint (<code>null</code> permitted). * * @since 1.0.11 */ public void setBackgroundPaint(Paint paint) { this.backgroundPaint = paint; notifyListeners(new TitleChangeEvent(this)); } /** * Returns the container holding the titles. * * @return The title container (never <code>null</code>). */ public BlockContainer getContainer() { return this.container; } /** * Sets the title container. * * @param container the container (<code>null</code> not permitted). */ public void setTitleContainer(BlockContainer container) { if (container == null) { throw new IllegalArgumentException("Null 'container' argument."); } this.container = container; } /** * Arranges the contents of the block, within the given constraints, and * returns the block size. * * @param g2 the graphics device. * @param constraint the constraint (<code>null</code> not permitted). * * @return The block size (in Java2D units, never <code>null</code>). */ @Override public Size2D arrange(Graphics2D g2, RectangleConstraint constraint) { RectangleConstraint contentConstraint = toContentConstraint(constraint); Size2D contentSize = this.container.arrange(g2, contentConstraint); return new Size2D(calculateTotalWidth(contentSize.getWidth()), calculateTotalHeight(contentSize.getHeight())); } /** * Draws the title on a Java 2D graphics device (such as the screen or a * printer). * * @param g2 the graphics device. * @param area the area allocated for the title. */ @Override public void draw(Graphics2D g2, Rectangle2D area) { draw(g2, area, null); } /** * Draws the block within the specified area. * * @param g2 the graphics device. * @param area the area. * @param params ignored (<code>null</code> permitted). * * @return Always <code>null</code>. */ @Override public Object draw(Graphics2D g2, Rectangle2D area, Object params) { area = trimMargin(area); drawBorder(g2, area); area = trimBorder(area); if (this.backgroundPaint != null) { g2.setPaint(this.backgroundPaint); g2.fill(area); } area = trimPadding(area); return this.container.draw(g2, area, params); } /** * Tests this title for equality with an arbitrary object. * * @param obj the object (<code>null</code> permitted). * * @return A boolean. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof CompositeTitle)) { return false; } CompositeTitle that = (CompositeTitle) obj; if (!this.container.equals(that.container)) { return false; } if (!PaintUtilities.equal(this.backgroundPaint, that.backgroundPaint)) { return false; } return super.equals(obj); } /** * Provides serialization support. * * @param stream the output stream. * * @throws IOException if there is an I/O error. */ private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); SerialUtilities.writePaint(this.backgroundPaint, stream); } /** * Provides serialization support. * * @param stream the input stream. * * @throws IOException if there is an I/O error. * @throws ClassNotFoundException if there is a classpath problem. */ private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); this.backgroundPaint = SerialUtilities.readPaint(stream); } }
8,115
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
package-info.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/title/package-info.java
/** * Classes used to display chart titles and subtitles. */ package org.jfree.chart.title;
94
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
ImageTitle.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/title/ImageTitle.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * --------------- * ImageTitle.java * --------------- * (C) Copyright 2000-2012, by David Berry and Contributors; * * Original Author: David Berry; * Contributor(s): David Gilbert (for Object Refinery Limited); * * Changes (from 18-Sep-2001) * -------------------------- * 18-Sep-2001 : Added standard header (DG); * 07-Nov-2001 : Separated the JCommon Class Library classes, JFreeChart now * requires jcommon.jar (DG); * 09-Jan-2002 : Updated Javadoc comments (DG); * 07-Feb-2002 : Changed blank space around title from Insets --> Spacer, to * allow for relative or absolute spacing (DG); * 25-Jun-2002 : Updated import statements (DG); * 23-Sep-2002 : Fixed errors reported by Checkstyle (DG); * 26-Nov-2002 : Added method for drawing images at left or right (DG); * 22-Sep-2003 : Added checks that the Image can never be null (TM). * 11-Jan-2005 : Removed deprecated code in preparation for the 1.0.0 * release (DG); * 02-Feb-2005 : Changed padding mechanism for all titles (DG); * 20-Apr-2005 : Added new draw() method (DG); * ------------- JFREECHART 1.0.x --------------------------------------------- * 02-Feb-2007 : Removed author tags all over JFreeChart sources (DG); * 11-Apr-2008 : Added arrange() method override to account for margin, border * and padding (DG); * 21-Apr-2008 : Added equals() method override (DG); * 16-Jun-2012 : Removed JCommon dependencies (DG); * */ package org.jfree.chart.title; import java.awt.Graphics2D; import java.awt.Image; import java.awt.geom.Rectangle2D; import org.jfree.chart.block.RectangleConstraint; import org.jfree.chart.ui.HorizontalAlignment; import org.jfree.chart.ui.RectangleEdge; import org.jfree.chart.ui.RectangleInsets; import org.jfree.chart.ui.Size2D; import org.jfree.chart.ui.VerticalAlignment; import org.jfree.chart.util.ObjectUtilities; import org.jfree.chart.event.TitleChangeEvent; /** * A chart title that displays an image. This is useful, for example, if you * have an image of your corporate logo and want to use as a footnote or part * of a title in a chart you create. * <P> * ImageTitle needs an image passed to it in the constructor. For ImageTitle * to work, you must have already loaded this image from its source (disk or * URL). It is recommended you use something like * Toolkit.getDefaultToolkit().getImage() to get the image. Then, use * MediaTracker or some other message to make sure the image is fully loaded * from disk. * <P> * SPECIAL NOTE: this class fails to serialize, so if you are * relying on your charts to be serializable, please avoid using this class. */ public class ImageTitle extends Title { /** The title image. */ private Image image; /** * Creates a new image title. * * @param image the image (<code>null</code> not permitted). */ public ImageTitle(Image image) { this(image, image.getHeight(null), image.getWidth(null), Title.DEFAULT_POSITION, Title.DEFAULT_HORIZONTAL_ALIGNMENT, Title.DEFAULT_VERTICAL_ALIGNMENT, Title.DEFAULT_PADDING); } /** * Creates a new image title. * * @param image the image (<code>null</code> not permitted). * @param position the title position. * @param horizontalAlignment the horizontal alignment. * @param verticalAlignment the vertical alignment. */ public ImageTitle(Image image, RectangleEdge position, HorizontalAlignment horizontalAlignment, VerticalAlignment verticalAlignment) { this(image, image.getHeight(null), image.getWidth(null), position, horizontalAlignment, verticalAlignment, Title.DEFAULT_PADDING); } /** * Creates a new image title with the given image scaled to the given * width and height in the given location. * * @param image the image (<code>null</code> not permitted). * @param height the height used to draw the image. * @param width the width used to draw the image. * @param position the title position. * @param horizontalAlignment the horizontal alignment. * @param verticalAlignment the vertical alignment. * @param padding the amount of space to leave around the outside of the * title. */ public ImageTitle(Image image, int height, int width, RectangleEdge position, HorizontalAlignment horizontalAlignment, VerticalAlignment verticalAlignment, RectangleInsets padding) { super(position, horizontalAlignment, verticalAlignment, padding); if (image == null) { throw new NullPointerException("Null 'image' argument."); } this.image = image; setHeight(height); setWidth(width); } /** * Returns the image for the title. * * @return The image for the title (never <code>null</code>). */ public Image getImage() { return this.image; } /** * Sets the image for the title and notifies registered listeners that the * title has been modified. * * @param image the new image (<code>null</code> not permitted). */ public void setImage(Image image) { if (image == null) { throw new NullPointerException("Null 'image' argument."); } this.image = image; notifyListeners(new TitleChangeEvent(this)); } /** * Arranges the contents of the block, within the given constraints, and * returns the block size. * * @param g2 the graphics device. * @param constraint the constraint (<code>null</code> not permitted). * * @return The block size (in Java2D units, never <code>null</code>). */ @Override public Size2D arrange(Graphics2D g2, RectangleConstraint constraint) { Size2D s = new Size2D(this.image.getWidth(null), this.image.getHeight(null)); return new Size2D(calculateTotalWidth(s.getWidth()), calculateTotalHeight(s.getHeight())); } /** * Draws the title on a Java 2D graphics device (such as the screen or a * printer). * * @param g2 the graphics device. * @param area the area allocated for the title. */ @Override public void draw(Graphics2D g2, Rectangle2D area) { RectangleEdge position = getPosition(); if (position == RectangleEdge.TOP || position == RectangleEdge.BOTTOM) { drawHorizontal(g2, area); } else if (position == RectangleEdge.LEFT || position == RectangleEdge.RIGHT) { drawVertical(g2, area); } else { throw new RuntimeException("Invalid title position."); } } /** * Draws the title on a Java 2D graphics device (such as the screen or a * printer). * * @param g2 the graphics device. * @param chartArea the area within which the title (and plot) should be * drawn. * * @return The size of the area used by the title. */ protected Size2D drawHorizontal(Graphics2D g2, Rectangle2D chartArea) { double startY = 0.0; double topSpace = 0.0; double bottomSpace = 0.0; double leftSpace = 0.0; double rightSpace = 0.0; double w = getWidth(); double h = getHeight(); RectangleInsets padding = getPadding(); topSpace = padding.calculateTopOutset(h); bottomSpace = padding.calculateBottomOutset(h); leftSpace = padding.calculateLeftOutset(w); rightSpace = padding.calculateRightOutset(w); if (getPosition() == RectangleEdge.TOP) { startY = chartArea.getY() + topSpace; } else { startY = chartArea.getY() + chartArea.getHeight() - bottomSpace - h; } // what is our alignment? HorizontalAlignment horizontalAlignment = getHorizontalAlignment(); double startX = 0.0; if (horizontalAlignment == HorizontalAlignment.CENTER) { startX = chartArea.getX() + leftSpace + chartArea.getWidth() / 2.0 - w / 2.0; } else if (horizontalAlignment == HorizontalAlignment.LEFT) { startX = chartArea.getX() + leftSpace; } else if (horizontalAlignment == HorizontalAlignment.RIGHT) { startX = chartArea.getX() + chartArea.getWidth() - rightSpace - w; } g2.drawImage(this.image, (int) startX, (int) startY, (int) w, (int) h, null); return new Size2D(chartArea.getWidth() + leftSpace + rightSpace, h + topSpace + bottomSpace); } /** * Draws the title on a Java 2D graphics device (such as the screen or a * printer). * * @param g2 the graphics device. * @param chartArea the area within which the title (and plot) should be * drawn. * * @return The size of the area used by the title. */ protected Size2D drawVertical(Graphics2D g2, Rectangle2D chartArea) { double startX = 0.0; double topSpace = 0.0; double bottomSpace = 0.0; double leftSpace = 0.0; double rightSpace = 0.0; double w = getWidth(); double h = getHeight(); RectangleInsets padding = getPadding(); if (padding != null) { topSpace = padding.calculateTopOutset(h); bottomSpace = padding.calculateBottomOutset(h); leftSpace = padding.calculateLeftOutset(w); rightSpace = padding.calculateRightOutset(w); } if (getPosition() == RectangleEdge.LEFT) { startX = chartArea.getX() + leftSpace; } else { startX = chartArea.getMaxX() - rightSpace - w; } // what is our alignment? VerticalAlignment alignment = getVerticalAlignment(); double startY = 0.0; if (alignment == VerticalAlignment.CENTER) { startY = chartArea.getMinY() + topSpace + chartArea.getHeight() / 2.0 - h / 2.0; } else if (alignment == VerticalAlignment.TOP) { startY = chartArea.getMinY() + topSpace; } else if (alignment == VerticalAlignment.BOTTOM) { startY = chartArea.getMaxY() - bottomSpace - h; } g2.drawImage(this.image, (int) startX, (int) startY, (int) w, (int) h, null); return new Size2D(chartArea.getWidth() + leftSpace + rightSpace, h + topSpace + bottomSpace); } /** * Draws the block within the specified area. * * @param g2 the graphics device. * @param area the area. * @param params ignored (<code>null</code> permitted). * * @return Always <code>null</code>. */ @Override public Object draw(Graphics2D g2, Rectangle2D area, Object params) { draw(g2, area); return null; } /** * Tests this <code>ImageTitle</code> for equality with an arbitrary * object. Returns <code>true</code> if: * <ul> * <li><code>obj</code> is an instance of <code>ImageTitle</code>; * <li><code>obj</code> references the same image as this * <code>ImageTitle</code>; * <li><code>super.equals(obj)<code> returns <code>true</code>; * </ul> * * @param obj the object (<code>null</code> permitted). * * @return A boolean. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof ImageTitle)) { return false; } ImageTitle that = (ImageTitle) obj; if (!ObjectUtilities.equal(this.image, that.image)) { return false; } return super.equals(obj); } }
13,268
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
LegendTitle.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/title/LegendTitle.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2014, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ---------------- * LegendTitle.java * ---------------- * (C) Copyright 2002-2014, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): Pierre-Marie Le Biot; * * Changes * ------- * 25-Nov-2004 : First working version (DG); * 11-Jan-2005 : Removed deprecated code in preparation for 1.0.0 release (DG); * 08-Feb-2005 : Updated for changes in RectangleConstraint class (DG); * 11-Feb-2005 : Implemented PublicCloneable (DG); * 23-Feb-2005 : Replaced chart reference with LegendItemSource (DG); * 16-Mar-2005 : Added itemFont attribute (DG); * 17-Mar-2005 : Fixed missing fillShape setting (DG); * 20-Apr-2005 : Added new draw() method (DG); * 03-May-2005 : Modified equals() method to ignore sources (DG); * 13-May-2005 : Added settings for legend item label and graphic padding (DG); * 09-Jun-2005 : Fixed serialization bug (DG); * 01-Sep-2005 : Added itemPaint attribute (PMLB); * ------------- JFREECHART 1.0.x --------------------------------------------- * 20-Jul-2006 : Use new LegendItemBlockContainer to restore support for * LegendItemEntities (DG); * 06-Oct-2006 : Add tooltip and URL text to legend item (DG); * 13-Dec-2006 : Added support for GradientPaint in legend items (DG); * 16-Mar-2007 : Updated border drawing for changes in AbstractBlock (DG); * 18-May-2007 : Pass seriesKey and dataset to legend item block (DG); * 15-Aug-2008 : Added getWrapper() method (DG); * 19-Mar-2009 : Added entity support - see patch 2603321 by Peter Kolb (DG); * 11-Mar-2012 : Added sort-order support - patch 3500621 by Simon Kaczor (MH); * 17-Jun-2012 : Removed JCommon dependencies (DG); * 10-Mar-2014 : Removed LegendItemCollection (DG); * */ package org.jfree.chart.title; import org.jfree.chart.LegendItem; import org.jfree.chart.LegendItemSource; import org.jfree.chart.block.*; import org.jfree.chart.entity.EntityCollection; import org.jfree.chart.entity.StandardEntityCollection; import org.jfree.chart.entity.TitleEntity; import org.jfree.chart.event.TitleChangeEvent; import org.jfree.chart.ui.RectangleAnchor; import org.jfree.chart.ui.RectangleEdge; import org.jfree.chart.ui.RectangleInsets; import org.jfree.chart.ui.Size2D; import org.jfree.chart.util.PaintUtilities; import org.jfree.chart.util.PublicCloneable; import org.jfree.chart.util.SerialUtilities; import org.jfree.chart.util.SortOrder; import java.awt.*; import java.awt.geom.Rectangle2D; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.List; /** * A chart title that displays a legend for the data in the chart. * <P> * The title can be populated with legend items manually, or you can assign a * reference to the plot, in which case the legend items will be automatically * created to match the dataset(s). */ public class LegendTitle extends Title implements Cloneable, PublicCloneable, Serializable { /** For serialization. */ private static final long serialVersionUID = 2644010518533854633L; /** The default item font. */ public static final Font DEFAULT_ITEM_FONT = new Font("SansSerif", Font.PLAIN, 12); /** The default item paint. */ public static final Paint DEFAULT_ITEM_PAINT = Color.BLACK; /** The sources for legend items. */ private LegendItemSource[] sources; /** The background paint (possibly <code>null</code>). */ private transient Paint backgroundPaint; /** The edge for the legend item graphic relative to the text. */ private RectangleEdge legendItemGraphicEdge; /** The anchor point for the legend item graphic. */ private RectangleAnchor legendItemGraphicAnchor; /** The legend item graphic location. */ private RectangleAnchor legendItemGraphicLocation; /** The padding for the legend item graphic. */ private RectangleInsets legendItemGraphicPadding; /** The item font. */ private Font itemFont; /** The item paint. */ private transient Paint itemPaint; /** The padding for the item labels. */ private RectangleInsets itemLabelPadding; /** * A container that holds and displays the legend items. */ private BlockContainer items; /** * The layout for the legend when it is positioned at the top or bottom * of the chart. */ private Arrangement hLayout; /** * The layout for the legend when it is positioned at the left or right * of the chart. */ private Arrangement vLayout; /** * An optional container for wrapping the legend items (allows for adding * a title or other text to the legend). */ private BlockContainer wrapper; /** * Whether to render legend items in ascending or descending order. * @since 1.0.15 */ private SortOrder sortOrder; /** * Constructs a new (empty) legend for the specified source. * * @param source the source. */ public LegendTitle(LegendItemSource source) { this(source, new FlowArrangement(), new ColumnArrangement()); } /** * Creates a new legend title with the specified arrangement. * * @param source the source. * @param hLayout the horizontal item arrangement (<code>null</code> not * permitted). * @param vLayout the vertical item arrangement (<code>null</code> not * permitted). */ public LegendTitle(LegendItemSource source, Arrangement hLayout, Arrangement vLayout) { this.sources = new LegendItemSource[] {source}; this.items = new BlockContainer(hLayout); this.hLayout = hLayout; this.vLayout = vLayout; this.backgroundPaint = null; this.legendItemGraphicEdge = RectangleEdge.LEFT; this.legendItemGraphicAnchor = RectangleAnchor.CENTER; this.legendItemGraphicLocation = RectangleAnchor.CENTER; this.legendItemGraphicPadding = new RectangleInsets(2.0, 2.0, 2.0, 2.0); this.itemFont = DEFAULT_ITEM_FONT; this.itemPaint = DEFAULT_ITEM_PAINT; this.itemLabelPadding = new RectangleInsets(2.0, 2.0, 2.0, 2.0); this.sortOrder = SortOrder.ASCENDING; } /** * Returns the legend item sources. * * @return The sources. */ public LegendItemSource[] getSources() { return this.sources; } /** * Sets the legend item sources and sends a {@link TitleChangeEvent} to * all registered listeners. * * @param sources the sources (<code>null</code> not permitted). */ public void setSources(LegendItemSource[] sources) { if (sources == null) { throw new IllegalArgumentException("Null 'sources' argument."); } this.sources = sources; notifyListeners(new TitleChangeEvent(this)); } /** * Returns the background paint. * * @return The background paint (possibly <code>null</code>). */ public Paint getBackgroundPaint() { return this.backgroundPaint; } /** * Sets the background paint for the legend and sends a * {@link TitleChangeEvent} to all registered listeners. * * @param paint the paint (<code>null</code> permitted). */ public void setBackgroundPaint(Paint paint) { this.backgroundPaint = paint; notifyListeners(new TitleChangeEvent(this)); } /** * Returns the location of the shape within each legend item. * * @return The location (never <code>null</code>). */ public RectangleEdge getLegendItemGraphicEdge() { return this.legendItemGraphicEdge; } /** * Sets the location of the shape within each legend item. * * @param edge the edge (<code>null</code> not permitted). */ public void setLegendItemGraphicEdge(RectangleEdge edge) { if (edge == null) { throw new IllegalArgumentException("Null 'edge' argument."); } this.legendItemGraphicEdge = edge; notifyListeners(new TitleChangeEvent(this)); } /** * Returns the legend item graphic anchor. * * @return The graphic anchor (never <code>null</code>). */ public RectangleAnchor getLegendItemGraphicAnchor() { return this.legendItemGraphicAnchor; } /** * Sets the anchor point used for the graphic in each legend item. * * @param anchor the anchor point (<code>null</code> not permitted). */ public void setLegendItemGraphicAnchor(RectangleAnchor anchor) { if (anchor == null) { throw new IllegalArgumentException("Null 'anchor' point."); } this.legendItemGraphicAnchor = anchor; } /** * Returns the legend item graphic location. * * @return The location (never <code>null</code>). */ public RectangleAnchor getLegendItemGraphicLocation() { return this.legendItemGraphicLocation; } /** * Sets the legend item graphic location. * * @param anchor the anchor (<code>null</code> not permitted). */ public void setLegendItemGraphicLocation(RectangleAnchor anchor) { this.legendItemGraphicLocation = anchor; } /** * Returns the padding that will be applied to each item graphic. * * @return The padding (never <code>null</code>). */ public RectangleInsets getLegendItemGraphicPadding() { return this.legendItemGraphicPadding; } /** * Sets the padding that will be applied to each item graphic in the * legend and sends a {@link TitleChangeEvent} to all registered listeners. * * @param padding the padding (<code>null</code> not permitted). */ public void setLegendItemGraphicPadding(RectangleInsets padding) { if (padding == null) { throw new IllegalArgumentException("Null 'padding' argument."); } this.legendItemGraphicPadding = padding; notifyListeners(new TitleChangeEvent(this)); } /** * Returns the item font. * * @return The font (never <code>null</code>). */ public Font getItemFont() { return this.itemFont; } /** * Sets the item font and sends a {@link TitleChangeEvent} to * all registered listeners. * * @param font the font (<code>null</code> not permitted). */ public void setItemFont(Font font) { if (font == null) { throw new IllegalArgumentException("Null 'font' argument."); } this.itemFont = font; notifyListeners(new TitleChangeEvent(this)); } /** * Returns the item paint. * * @return The paint (never <code>null</code>). */ public Paint getItemPaint() { return this.itemPaint; } /** * Sets the item paint. * * @param paint the paint (<code>null</code> not permitted). */ public void setItemPaint(Paint paint) { if (paint == null) { throw new IllegalArgumentException("Null 'paint' argument."); } this.itemPaint = paint; notifyListeners(new TitleChangeEvent(this)); } /** * Returns the padding used for the items labels. * * @return The padding (never <code>null</code>). */ public RectangleInsets getItemLabelPadding() { return this.itemLabelPadding; } /** * Sets the padding used for the item labels in the legend. * * @param padding the padding (<code>null</code> not permitted). */ public void setItemLabelPadding(RectangleInsets padding) { if (padding == null) { throw new IllegalArgumentException("Null 'padding' argument."); } this.itemLabelPadding = padding; notifyListeners(new TitleChangeEvent(this)); } /** * Gets the order used to display legend items. * * @return The order (never <code>null</code>). * @since 1.0.15 */ public SortOrder getSortOrder() { return this.sortOrder; } /** * Sets the order used to display legend items. * * @param order Specifies ascending or descending order (<code>null</code> * not permitted). * @since 1.0.15 */ public void setSortOrder(SortOrder order) { if (order == null) { throw new IllegalArgumentException("Null 'order' argument."); } this.sortOrder = order; notifyListeners(new TitleChangeEvent(this)); } /** * Fetches the latest legend items. */ protected void fetchLegendItems() { this.items.clear(); RectangleEdge p = getPosition(); if (RectangleEdge.isTopOrBottom(p)) { this.items.setArrangement(this.hLayout); } else { this.items.setArrangement(this.vLayout); } if (this.sortOrder.equals(SortOrder.ASCENDING)) { for (LegendItemSource source : this.sources) { List<LegendItem> legendItems = source.getLegendItems(); for (LegendItem item: legendItems) { addItemBlock(item); } } } else { for (int s = this.sources.length - 1; s >= 0; s--) { List<LegendItem> legendItems = this.sources[s].getLegendItems(); for (int i = legendItems.size() - 1; i >= 0; i--) { addItemBlock(legendItems.get(i)); } } } } private void addItemBlock(LegendItem item) { Block block = createLegendItemBlock(item); this.items.add(block); } /** * Creates a legend item block. * * @param item the legend item. * * @return The block. */ protected Block createLegendItemBlock(LegendItem item) { BlockContainer result; LegendGraphic lg = new LegendGraphic(item.getShape(), item.getFillPaint()); lg.setFillPaintTransformer(item.getFillPaintTransformer()); lg.setShapeFilled(item.isShapeFilled()); lg.setLine(item.getLine()); lg.setLineStroke(item.getLineStroke()); lg.setLinePaint(item.getLinePaint()); lg.setLineVisible(item.isLineVisible()); lg.setShapeVisible(item.isShapeVisible()); lg.setShapeOutlineVisible(item.isShapeOutlineVisible()); lg.setOutlinePaint(item.getOutlinePaint()); lg.setOutlineStroke(item.getOutlineStroke()); lg.setPadding(this.legendItemGraphicPadding); LegendItemBlockContainer legendItem = new LegendItemBlockContainer( new BorderArrangement(), item.getDataset(), item.getSeriesKey()); lg.setShapeAnchor(getLegendItemGraphicAnchor()); lg.setShapeLocation(getLegendItemGraphicLocation()); legendItem.add(lg, this.legendItemGraphicEdge); Font textFont = item.getLabelFont(); // TODO need to investigate further and send PR or issue to https://github.com/jfree/jfreechart-fse /*if (textFont == null) {*/ textFont = this.itemFont; /*}*/ Paint textPaint = item.getLabelPaint(); if (textPaint == null) { textPaint = this.itemPaint; } LabelBlock labelBlock = new LabelBlock(item.getLabel(), textFont, textPaint); labelBlock.setPadding(this.itemLabelPadding); legendItem.add(labelBlock); legendItem.setToolTipText(item.getToolTipText()); legendItem.setURLText(item.getURLText()); result = new BlockContainer(new CenterArrangement()); result.add(legendItem); return result; } /** * Returns the container that holds the legend items. * * @return The container for the legend items. */ public BlockContainer getItemContainer() { return this.items; } /** * Arranges the contents of the block, within the given constraints, and * returns the block size. * * @param g2 the graphics device. * @param constraint the constraint (<code>null</code> not permitted). * * @return The block size (in Java2D units, never <code>null</code>). */ @Override public Size2D arrange(Graphics2D g2, RectangleConstraint constraint) { Size2D result = new Size2D(); fetchLegendItems(); if (this.items.isEmpty()) { return result; } BlockContainer container = this.wrapper; if (container == null) { container = this.items; } RectangleConstraint c = toContentConstraint(constraint); Size2D size = container.arrange(g2, c); result.height = calculateTotalHeight(size.height); result.width = calculateTotalWidth(size.width); return result; } /** * Draws the title on a Java 2D graphics device (such as the screen or a * printer). * * @param g2 the graphics device. * @param area the available area for the title. */ @Override public void draw(Graphics2D g2, Rectangle2D area) { draw(g2, area, null); } /** * Draws the block within the specified area. * * @param g2 the graphics device. * @param area the area. * @param params ignored (<code>null</code> permitted). * * @return An {@link org.jfree.chart.block.EntityBlockResult} or * <code>null</code>. */ @Override public Object draw(Graphics2D g2, Rectangle2D area, Object params) { Rectangle2D target = (Rectangle2D) area.clone(); Rectangle2D hotspot = (Rectangle2D) area.clone(); StandardEntityCollection sec = null; if (params instanceof EntityBlockParams && ((EntityBlockParams) params).getGenerateEntities()) { sec = new StandardEntityCollection(); sec.add(new TitleEntity(hotspot, this)); } target = trimMargin(target); if (this.backgroundPaint != null) { g2.setPaint(this.backgroundPaint); g2.fill(target); } BlockFrame border = getFrame(); border.draw(g2, target); border.getInsets().trim(target); BlockContainer container = this.wrapper; if (container == null) { container = this.items; } target = trimPadding(target); Object val = container.draw(g2, target, params); if (val instanceof BlockResult) { EntityCollection ec = ((BlockResult) val).getEntityCollection(); if (ec != null && sec != null) { sec.addAll(ec); ((BlockResult) val).setEntityCollection(sec); } } return val; } /** * Returns the wrapper container, if any. * * @return The wrapper container (possibly <code>null</code>). * * @since 1.0.11 */ public BlockContainer getWrapper() { return this.wrapper; } /** * Sets the wrapper container for the legend. * * @param wrapper the wrapper container. */ public void setWrapper(BlockContainer wrapper) { this.wrapper = wrapper; } /** * Tests this title for equality with an arbitrary object. * * @param obj the object (<code>null</code> permitted). * * @return A boolean. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof LegendTitle)) { return false; } if (!super.equals(obj)) { return false; } LegendTitle that = (LegendTitle) obj; if (!PaintUtilities.equal(this.backgroundPaint, that.backgroundPaint)) { return false; } if (this.legendItemGraphicEdge != that.legendItemGraphicEdge) { return false; } if (this.legendItemGraphicAnchor != that.legendItemGraphicAnchor) { return false; } if (this.legendItemGraphicLocation != that.legendItemGraphicLocation) { return false; } if (!this.itemFont.equals(that.itemFont)) { return false; } if (!this.itemPaint.equals(that.itemPaint)) { return false; } if (!this.hLayout.equals(that.hLayout)) { return false; } if (!this.vLayout.equals(that.vLayout)) { return false; } if (!this.sortOrder.equals(that.sortOrder)) { return false; } return true; } /** * Provides serialization support. * * @param stream the output stream. * * @throws IOException if there is an I/O error. */ private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); SerialUtilities.writePaint(this.backgroundPaint, stream); SerialUtilities.writePaint(this.itemPaint, stream); } /** * Provides serialization support. * * @param stream the input stream. * * @throws IOException if there is an I/O error. * @throws ClassNotFoundException if there is a classpath problem. */ private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); this.backgroundPaint = SerialUtilities.readPaint(stream); this.itemPaint = SerialUtilities.readPaint(stream); } }
22,916
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
LegendGraphic.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/title/LegendGraphic.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ------------------ * LegendGraphic.java * ------------------ * (C) Copyright 2004-2012, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 26-Oct-2004 : Version 1 (DG); * 21-Jan-2005 : Modified return type of RectangleAnchor.coordinates() * method (DG); * 20-Apr-2005 : Added new draw() method (DG); * 13-May-2005 : Fixed to respect margin, border and padding settings (DG); * 01-Sep-2005 : Implemented PublicCloneable (DG); * ------------- JFREECHART 1.0.x --------------------------------------------- * 13-Dec-2006 : Added fillPaintTransformer attribute, so legend graphics can * display gradient paint correctly, updated equals() and * corrected clone() (DG); * 01-Aug-2007 : Updated API docs (DG); * 16-Jun-2012 : Removed JCommon dependencies (DG); * */ package org.jfree.chart.title; import java.awt.GradientPaint; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.Shape; import java.awt.Stroke; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import org.jfree.chart.block.AbstractBlock; import org.jfree.chart.block.Block; import org.jfree.chart.block.LengthConstraintType; import org.jfree.chart.block.RectangleConstraint; import org.jfree.chart.ui.GradientPaintTransformer; import org.jfree.chart.ui.RectangleAnchor; import org.jfree.chart.ui.Size2D; import org.jfree.chart.ui.StandardGradientPaintTransformer; import org.jfree.chart.util.ObjectUtilities; import org.jfree.chart.util.PaintUtilities; import org.jfree.chart.util.PublicCloneable; import org.jfree.chart.util.ShapeUtilities; import org.jfree.chart.util.SerialUtilities; /** * The graphical item within a legend item. */ public class LegendGraphic extends AbstractBlock implements Block, PublicCloneable { /** For serialization. */ static final long serialVersionUID = -1338791523854985009L; /** * A flag that controls whether or not the shape is visible - see also * lineVisible. */ private boolean shapeVisible; /** * The shape to display. To allow for accurate positioning, the center * of the shape should be at (0, 0). */ private transient Shape shape; /** * Defines the location within the block to which the shape will be aligned. */ private RectangleAnchor shapeLocation; /** * Defines the point on the shape's bounding rectangle that will be * aligned to the drawing location when the shape is rendered. */ private RectangleAnchor shapeAnchor; /** A flag that controls whether or not the shape is filled. */ private boolean shapeFilled; /** The fill paint for the shape. */ private transient Paint fillPaint; /** * The fill paint transformer (used if the fillPaint is an instance of * GradientPaint). * * @since 1.0.4 */ private GradientPaintTransformer fillPaintTransformer; /** A flag that controls whether or not the shape outline is visible. */ private boolean shapeOutlineVisible; /** The outline paint for the shape. */ private transient Paint outlinePaint; /** The outline stroke for the shape. */ private transient Stroke outlineStroke; /** * A flag that controls whether or not the line is visible - see also * shapeVisible. */ private boolean lineVisible; /** The line. */ private transient Shape line; /** The line stroke. */ private transient Stroke lineStroke; /** The line paint. */ private transient Paint linePaint; /** * Creates a new legend graphic. * * @param shape the shape (<code>null</code> not permitted). * @param fillPaint the fill paint (<code>null</code> not permitted). */ public LegendGraphic(Shape shape, Paint fillPaint) { if (shape == null) { throw new IllegalArgumentException("Null 'shape' argument."); } if (fillPaint == null) { throw new IllegalArgumentException("Null 'fillPaint' argument."); } this.shapeVisible = true; this.shape = shape; this.shapeAnchor = RectangleAnchor.CENTER; this.shapeLocation = RectangleAnchor.CENTER; this.shapeFilled = true; this.fillPaint = fillPaint; this.fillPaintTransformer = new StandardGradientPaintTransformer(); setPadding(2.0, 2.0, 2.0, 2.0); } /** * Returns a flag that controls whether or not the shape * is visible. * * @return A boolean. * * @see #setShapeVisible(boolean) */ public boolean isShapeVisible() { return this.shapeVisible; } /** * Sets a flag that controls whether or not the shape is * visible. * * @param visible the flag. * * @see #isShapeVisible() */ public void setShapeVisible(boolean visible) { this.shapeVisible = visible; } /** * Returns the shape. * * @return The shape. * * @see #setShape(Shape) */ public Shape getShape() { return this.shape; } /** * Sets the shape. * * @param shape the shape. * * @see #getShape() */ public void setShape(Shape shape) { this.shape = shape; } /** * Returns a flag that controls whether or not the shapes * are filled. * * @return A boolean. * * @see #setShapeFilled(boolean) */ public boolean isShapeFilled() { return this.shapeFilled; } /** * Sets a flag that controls whether or not the shape is * filled. * * @param filled the flag. * * @see #isShapeFilled() */ public void setShapeFilled(boolean filled) { this.shapeFilled = filled; } /** * Returns the paint used to fill the shape. * * @return The fill paint. * * @see #setFillPaint(Paint) */ public Paint getFillPaint() { return this.fillPaint; } /** * Sets the paint used to fill the shape. * * @param paint the paint. * * @see #getFillPaint() */ public void setFillPaint(Paint paint) { this.fillPaint = paint; } /** * Returns the transformer used when the fill paint is an instance of * <code>GradientPaint</code>. * * @return The transformer (never <code>null</code>). * * @since 1.0.4. * * @see #setFillPaintTransformer(GradientPaintTransformer) */ public GradientPaintTransformer getFillPaintTransformer() { return this.fillPaintTransformer; } /** * Sets the transformer used when the fill paint is an instance of * <code>GradientPaint</code>. * * @param transformer the transformer (<code>null</code> not permitted). * * @since 1.0.4 * * @see #getFillPaintTransformer() */ public void setFillPaintTransformer(GradientPaintTransformer transformer) { if (transformer == null) { throw new IllegalArgumentException("Null 'transformer' argument."); } this.fillPaintTransformer = transformer; } /** * Returns a flag that controls whether the shape outline is visible. * * @return A boolean. * * @see #setShapeOutlineVisible(boolean) */ public boolean isShapeOutlineVisible() { return this.shapeOutlineVisible; } /** * Sets a flag that controls whether or not the shape outline * is visible. * * @param visible the flag. * * @see #isShapeOutlineVisible() */ public void setShapeOutlineVisible(boolean visible) { this.shapeOutlineVisible = visible; } /** * Returns the outline paint. * * @return The paint. * * @see #setOutlinePaint(Paint) */ public Paint getOutlinePaint() { return this.outlinePaint; } /** * Sets the outline paint. * * @param paint the paint. * * @see #getOutlinePaint() */ public void setOutlinePaint(Paint paint) { this.outlinePaint = paint; } /** * Returns the outline stroke. * * @return The stroke. * * @see #setOutlineStroke(Stroke) */ public Stroke getOutlineStroke() { return this.outlineStroke; } /** * Sets the outline stroke. * * @param stroke the stroke. * * @see #getOutlineStroke() */ public void setOutlineStroke(Stroke stroke) { this.outlineStroke = stroke; } /** * Returns the shape anchor. * * @return The shape anchor. * * @see #getShapeAnchor() */ public RectangleAnchor getShapeAnchor() { return this.shapeAnchor; } /** * Sets the shape anchor. This defines a point on the shapes bounding * rectangle that will be used to align the shape to a location. * * @param anchor the anchor (<code>null</code> not permitted). * * @see #setShapeAnchor(RectangleAnchor) */ public void setShapeAnchor(RectangleAnchor anchor) { if (anchor == null) { throw new IllegalArgumentException("Null 'anchor' argument."); } this.shapeAnchor = anchor; } /** * Returns the shape location. * * @return The shape location. * * @see #setShapeLocation(RectangleAnchor) */ public RectangleAnchor getShapeLocation() { return this.shapeLocation; } /** * Sets the shape location. This defines a point within the drawing * area that will be used to align the shape to. * * @param location the location (<code>null</code> not permitted). * * @see #getShapeLocation() */ public void setShapeLocation(RectangleAnchor location) { if (location == null) { throw new IllegalArgumentException("Null 'location' argument."); } this.shapeLocation = location; } /** * Returns the flag that controls whether or not the line is visible. * * @return A boolean. * * @see #setLineVisible(boolean) */ public boolean isLineVisible() { return this.lineVisible; } /** * Sets the flag that controls whether or not the line is visible. * * @param visible the flag. * * @see #isLineVisible() */ public void setLineVisible(boolean visible) { this.lineVisible = visible; } /** * Returns the line centered about (0, 0). * * @return The line. * * @see #setLine(Shape) */ public Shape getLine() { return this.line; } /** * Sets the line. A Shape is used here, because then you can use Line2D, * GeneralPath or any other Shape to represent the line. * * @param line the line. * * @see #getLine() */ public void setLine(Shape line) { this.line = line; } /** * Returns the line paint. * * @return The paint. * * @see #setLinePaint(Paint) */ public Paint getLinePaint() { return this.linePaint; } /** * Sets the line paint. * * @param paint the paint. * * @see #getLinePaint() */ public void setLinePaint(Paint paint) { this.linePaint = paint; } /** * Returns the line stroke. * * @return The stroke. * * @see #setLineStroke(Stroke) */ public Stroke getLineStroke() { return this.lineStroke; } /** * Sets the line stroke. * * @param stroke the stroke. * * @see #getLineStroke() */ public void setLineStroke(Stroke stroke) { this.lineStroke = stroke; } /** * Arranges the contents of the block, within the given constraints, and * returns the block size. * * @param g2 the graphics device. * @param constraint the constraint (<code>null</code> not permitted). * * @return The block size (in Java2D units, never <code>null</code>). */ @Override public Size2D arrange(Graphics2D g2, RectangleConstraint constraint) { RectangleConstraint contentConstraint = toContentConstraint(constraint); LengthConstraintType w = contentConstraint.getWidthConstraintType(); LengthConstraintType h = contentConstraint.getHeightConstraintType(); Size2D contentSize = null; if (w == LengthConstraintType.NONE) { if (h == LengthConstraintType.NONE) { contentSize = arrangeNN(g2); } else if (h == LengthConstraintType.RANGE) { throw new RuntimeException("Not yet implemented."); } else if (h == LengthConstraintType.FIXED) { throw new RuntimeException("Not yet implemented."); } } else if (w == LengthConstraintType.RANGE) { if (h == LengthConstraintType.NONE) { throw new RuntimeException("Not yet implemented."); } else if (h == LengthConstraintType.RANGE) { throw new RuntimeException("Not yet implemented."); } else if (h == LengthConstraintType.FIXED) { throw new RuntimeException("Not yet implemented."); } } else if (w == LengthConstraintType.FIXED) { if (h == LengthConstraintType.NONE) { throw new RuntimeException("Not yet implemented."); } else if (h == LengthConstraintType.RANGE) { throw new RuntimeException("Not yet implemented."); } else if (h == LengthConstraintType.FIXED) { contentSize = new Size2D( contentConstraint.getWidth(), contentConstraint.getHeight() ); } } return new Size2D( calculateTotalWidth(contentSize.getWidth()), calculateTotalHeight(contentSize.getHeight()) ); } /** * Performs the layout with no constraint, so the content size is * determined by the bounds of the shape and/or line drawn to represent * the series. * * @param g2 the graphics device. * * @return The content size. */ protected Size2D arrangeNN(Graphics2D g2) { Rectangle2D contentSize = new Rectangle2D.Double(); if (this.line != null) { contentSize.setRect(this.line.getBounds2D()); } if (this.shape != null) { contentSize = contentSize.createUnion(this.shape.getBounds2D()); } return new Size2D(contentSize.getWidth(), contentSize.getHeight()); } /** * Draws the graphic item within the specified area. * * @param g2 the graphics device. * @param area the area. */ @Override public void draw(Graphics2D g2, Rectangle2D area) { area = trimMargin(area); drawBorder(g2, area); area = trimBorder(area); area = trimPadding(area); if (this.lineVisible) { Point2D location = RectangleAnchor.coordinates(area, this.shapeLocation); Shape aLine = ShapeUtilities.createTranslatedShape(getLine(), this.shapeAnchor, location.getX(), location.getY()); g2.setPaint(this.linePaint); g2.setStroke(this.lineStroke); g2.draw(aLine); } if (this.shapeVisible) { Point2D location = RectangleAnchor.coordinates(area, this.shapeLocation); Shape s = ShapeUtilities.createTranslatedShape(this.shape, this.shapeAnchor, location.getX(), location.getY()); if (this.shapeFilled) { Paint p = this.fillPaint; if (p instanceof GradientPaint) { GradientPaint gp = (GradientPaint) this.fillPaint; p = this.fillPaintTransformer.transform(gp, s); } g2.setPaint(p); g2.fill(s); } if (this.shapeOutlineVisible) { g2.setPaint(this.outlinePaint); g2.setStroke(this.outlineStroke); g2.draw(s); } } } /** * Draws the block within the specified area. * * @param g2 the graphics device. * @param area the area. * @param params ignored (<code>null</code> permitted). * * @return Always <code>null</code>. */ @Override public Object draw(Graphics2D g2, Rectangle2D area, Object params) { draw(g2, area); return null; } /** * Tests this <code>LegendGraphic</code> instance for equality with an * arbitrary object. * * @param obj the object (<code>null</code> permitted). * * @return A boolean. */ @Override public boolean equals(Object obj) { if (!(obj instanceof LegendGraphic)) { return false; } LegendGraphic that = (LegendGraphic) obj; if (this.shapeVisible != that.shapeVisible) { return false; } if (!ShapeUtilities.equal(this.shape, that.shape)) { return false; } if (this.shapeFilled != that.shapeFilled) { return false; } if (!PaintUtilities.equal(this.fillPaint, that.fillPaint)) { return false; } if (!ObjectUtilities.equal(this.fillPaintTransformer, that.fillPaintTransformer)) { return false; } if (this.shapeOutlineVisible != that.shapeOutlineVisible) { return false; } if (!PaintUtilities.equal(this.outlinePaint, that.outlinePaint)) { return false; } if (!ObjectUtilities.equal(this.outlineStroke, that.outlineStroke)) { return false; } if (this.shapeAnchor != that.shapeAnchor) { return false; } if (this.shapeLocation != that.shapeLocation) { return false; } if (this.lineVisible != that.lineVisible) { return false; } if (!ShapeUtilities.equal(this.line, that.line)) { return false; } if (!PaintUtilities.equal(this.linePaint, that.linePaint)) { return false; } if (!ObjectUtilities.equal(this.lineStroke, that.lineStroke)) { return false; } return super.equals(obj); } /** * Returns a hash code for this instance. * * @return A hash code. */ @Override public int hashCode() { int result = 193; result = 37 * result + ObjectUtilities.hashCode(this.fillPaint); // FIXME: use other fields too return result; } /** * Returns a clone of this <code>LegendGraphic</code> instance. * * @return A clone of this <code>LegendGraphic</code> instance. * * @throws CloneNotSupportedException if there is a problem cloning. */ @Override public Object clone() throws CloneNotSupportedException { LegendGraphic clone = (LegendGraphic) super.clone(); clone.shape = ShapeUtilities.clone(this.shape); clone.line = ShapeUtilities.clone(this.line); return clone; } /** * Provides serialization support. * * @param stream the output stream. * * @throws IOException if there is an I/O error. */ private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); SerialUtilities.writeShape(this.shape, stream); SerialUtilities.writePaint(this.fillPaint, stream); SerialUtilities.writePaint(this.outlinePaint, stream); SerialUtilities.writeStroke(this.outlineStroke, stream); SerialUtilities.writeShape(this.line, stream); SerialUtilities.writePaint(this.linePaint, stream); SerialUtilities.writeStroke(this.lineStroke, stream); } /** * Provides serialization support. * * @param stream the input stream. * * @throws IOException if there is an I/O error. * @throws ClassNotFoundException if there is a classpath problem. */ private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); this.shape = SerialUtilities.readShape(stream); this.fillPaint = SerialUtilities.readPaint(stream); this.outlinePaint = SerialUtilities.readPaint(stream); this.outlineStroke = SerialUtilities.readStroke(stream); this.line = SerialUtilities.readShape(stream); this.linePaint = SerialUtilities.readPaint(stream); this.lineStroke = SerialUtilities.readStroke(stream); } }
22,447
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
Title.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/title/Title.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ---------- * Title.java * ---------- * (C) Copyright 2000-2012, by David Berry and Contributors. * * Original Author: David Berry; * Contributor(s): David Gilbert (for Object Refinery Limited); * Nicolas Brodu; * * Changes (from 21-Aug-2001) * -------------------------- * 21-Aug-2001 : Added standard header (DG); * 18-Sep-2001 : Updated header (DG); * 14-Nov-2001 : Package com.jrefinery.common.ui.* changed to * com.jrefinery.ui.* (DG); * 07-Feb-2002 : Changed blank space around title from Insets --> Spacer, to * allow for relative or absolute spacing (DG); * 25-Jun-2002 : Removed unnecessary imports (DG); * 01-Oct-2002 : Fixed errors reported by Checkstyle (DG); * 14-Oct-2002 : Changed the event listener storage structure (DG); * 11-Sep-2003 : Took care of listeners while cloning (NB); * 22-Sep-2003 : Spacer cannot be null. Added nullpointer checks for this (TM); * 08-Jan-2003 : Renamed AbstractTitle --> Title and moved to separate * package (DG); * 26-Oct-2004 : Refactored to implement Block interface, and removed redundant * constants (DG); * 11-Jan-2005 : Removed deprecated code in preparation for the 1.0.0 * release (DG); * 02-Feb-2005 : Changed Spacer --> RectangleInsets for padding (DG); * 03-May-2005 : Fixed problem in equals() method (DG); * 19-Sep-2008 : Added visibility flag (DG); * 15-Jun-2012 : Removed JCommon dependencies (DG); * */ package org.jfree.chart.title; import java.awt.Graphics2D; import java.awt.geom.Rectangle2D; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import javax.swing.event.EventListenerList; import org.jfree.chart.block.AbstractBlock; import org.jfree.chart.block.Block; import org.jfree.chart.ui.HorizontalAlignment; import org.jfree.chart.ui.RectangleEdge; import org.jfree.chart.ui.RectangleInsets; import org.jfree.chart.ui.VerticalAlignment; import org.jfree.chart.util.ObjectUtilities; import org.jfree.chart.event.TitleChangeEvent; import org.jfree.chart.event.TitleChangeListener; /** * The base class for all chart titles. A chart can have multiple titles, * appearing at the top, bottom, left or right of the chart. * <P> * Concrete implementations of this class will render text and images, and * hence do the actual work of drawing titles. */ public abstract class Title extends AbstractBlock implements Block, Cloneable, Serializable { /** For serialization. */ private static final long serialVersionUID = -6675162505277817221L; /** The default title position. */ public static final RectangleEdge DEFAULT_POSITION = RectangleEdge.TOP; /** The default horizontal alignment. */ public static final HorizontalAlignment DEFAULT_HORIZONTAL_ALIGNMENT = HorizontalAlignment.CENTER; /** The default vertical alignment. */ public static final VerticalAlignment DEFAULT_VERTICAL_ALIGNMENT = VerticalAlignment.CENTER; /** Default title padding. */ public static final RectangleInsets DEFAULT_PADDING = new RectangleInsets( 1, 1, 1, 1); /** * A flag that controls whether or not the title is visible. * * @since 1.0.11 */ public boolean visible; /** The title position. */ private RectangleEdge position; /** The horizontal alignment of the title content. */ private HorizontalAlignment horizontalAlignment; /** The vertical alignment of the title content. */ private VerticalAlignment verticalAlignment; /** Storage for registered change listeners. */ private transient EventListenerList listenerList; /** * A flag that can be used to temporarily disable the listener mechanism. */ private boolean notify; /** * Creates a new title, using default attributes where necessary. */ protected Title() { this(Title.DEFAULT_POSITION, Title.DEFAULT_HORIZONTAL_ALIGNMENT, Title.DEFAULT_VERTICAL_ALIGNMENT, Title.DEFAULT_PADDING); } /** * Creates a new title, using default attributes where necessary. * * @param position the position of the title (<code>null</code> not * permitted). * @param horizontalAlignment the horizontal alignment of the title * (<code>null</code> not permitted). * @param verticalAlignment the vertical alignment of the title * (<code>null</code> not permitted). */ protected Title(RectangleEdge position, HorizontalAlignment horizontalAlignment, VerticalAlignment verticalAlignment) { this(position, horizontalAlignment, verticalAlignment, Title.DEFAULT_PADDING); } /** * Creates a new title. * * @param position the position of the title (<code>null</code> not * permitted). * @param horizontalAlignment the horizontal alignment of the title (LEFT, * CENTER or RIGHT, <code>null</code> not * permitted). * @param verticalAlignment the vertical alignment of the title (TOP, * MIDDLE or BOTTOM, <code>null</code> not * permitted). * @param padding the amount of space to leave around the outside of the * title (<code>null</code> not permitted). */ protected Title(RectangleEdge position, HorizontalAlignment horizontalAlignment, VerticalAlignment verticalAlignment, RectangleInsets padding) { // check arguments... if (position == null) { throw new IllegalArgumentException("Null 'position' argument."); } if (horizontalAlignment == null) { throw new IllegalArgumentException( "Null 'horizontalAlignment' argument."); } if (verticalAlignment == null) { throw new IllegalArgumentException( "Null 'verticalAlignment' argument."); } if (padding == null) { throw new IllegalArgumentException("Null 'spacer' argument."); } this.visible = true; this.position = position; this.horizontalAlignment = horizontalAlignment; this.verticalAlignment = verticalAlignment; setPadding(padding); this.listenerList = new EventListenerList(); this.notify = true; } /** * Returns a flag that controls whether or not the title should be * drawn. The default value is <code>true</code>. * * @return A boolean. * * @see #setVisible(boolean) * * @since 1.0.11 */ public boolean isVisible() { return this.visible; } /** * Sets a flag that controls whether or not the title should be drawn, and * sends a {@link TitleChangeEvent} to all registered listeners. * * @param visible the new flag value. * * @see #isVisible() * * @since 1.0.11 */ public void setVisible(boolean visible) { this.visible = visible; notifyListeners(new TitleChangeEvent(this)); } /** * Returns the position of the title. * * @return The title position (never <code>null</code>). */ public RectangleEdge getPosition() { return this.position; } /** * Sets the position for the title and sends a {@link TitleChangeEvent} to * all registered listeners. * * @param position the position (<code>null</code> not permitted). */ public void setPosition(RectangleEdge position) { if (position == null) { throw new IllegalArgumentException("Null 'position' argument."); } if (this.position != position) { this.position = position; notifyListeners(new TitleChangeEvent(this)); } } /** * Returns the horizontal alignment of the title. * * @return The horizontal alignment (never <code>null</code>). */ public HorizontalAlignment getHorizontalAlignment() { return this.horizontalAlignment; } /** * Sets the horizontal alignment for the title and sends a * {@link TitleChangeEvent} to all registered listeners. * * @param alignment the horizontal alignment (<code>null</code> not * permitted). */ public void setHorizontalAlignment(HorizontalAlignment alignment) { if (alignment == null) { throw new IllegalArgumentException("Null 'alignment' argument."); } if (this.horizontalAlignment != alignment) { this.horizontalAlignment = alignment; notifyListeners(new TitleChangeEvent(this)); } } /** * Returns the vertical alignment of the title. * * @return The vertical alignment (never <code>null</code>). */ public VerticalAlignment getVerticalAlignment() { return this.verticalAlignment; } /** * Sets the vertical alignment for the title, and notifies any registered * listeners of the change. * * @param alignment the new vertical alignment (TOP, MIDDLE or BOTTOM, * <code>null</code> not permitted). */ public void setVerticalAlignment(VerticalAlignment alignment) { if (alignment == null) { throw new IllegalArgumentException("Null 'alignment' argument."); } if (this.verticalAlignment != alignment) { this.verticalAlignment = alignment; notifyListeners(new TitleChangeEvent(this)); } } /** * Returns the flag that indicates whether or not the notification * mechanism is enabled. * * @return The flag. */ public boolean getNotify() { return this.notify; } /** * Sets the flag that indicates whether or not the notification mechanism * is enabled. There are certain situations (such as cloning) where you * want to turn notification off temporarily. * * @param flag the new value of the flag. */ public void setNotify(boolean flag) { this.notify = flag; if (flag) { notifyListeners(new TitleChangeEvent(this)); } } /** * Draws the title on a Java 2D graphics device (such as the screen or a * printer). * * @param g2 the graphics device. * @param area the area allocated for the title (subclasses should not * draw outside this area). */ @Override public abstract void draw(Graphics2D g2, Rectangle2D area); /** * Returns a clone of the title. * <P> * One situation when this is useful is when editing the title properties - * you can edit a clone, and then it is easier to cancel the changes if * necessary. * * @return A clone of the title. * * @throws CloneNotSupportedException not thrown by this class, but it may * be thrown by subclasses. */ @Override public Object clone() throws CloneNotSupportedException { Title duplicate = (Title) super.clone(); duplicate.listenerList = new EventListenerList(); // RectangleInsets is immutable => same reference in clone OK return duplicate; } /** * Registers an object for notification of changes to the title. * * @param listener the object that is being registered. */ public void addChangeListener(TitleChangeListener listener) { this.listenerList.add(TitleChangeListener.class, listener); } /** * Unregisters an object for notification of changes to the chart title. * * @param listener the object that is being unregistered. */ public void removeChangeListener(TitleChangeListener listener) { this.listenerList.remove(TitleChangeListener.class, listener); } /** * Notifies all registered listeners that the chart title has changed in * some way. * * @param event an object that contains information about the change to * the title. */ protected void notifyListeners(TitleChangeEvent event) { if (this.notify) { Object[] listeners = this.listenerList.getListenerList(); for (int i = listeners.length - 2; i >= 0; i -= 2) { if (listeners[i] == TitleChangeListener.class) { ((TitleChangeListener) listeners[i + 1]).titleChanged( event); } } } } /** * Tests an object for equality with this title. * * @param obj the object (<code>null</code> not permitted). * * @return <code>true</code> or <code>false</code>. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof Title)) { return false; } Title that = (Title) obj; if (this.visible != that.visible) { return false; } if (this.position != that.position) { return false; } if (this.horizontalAlignment != that.horizontalAlignment) { return false; } if (this.verticalAlignment != that.verticalAlignment) { return false; } if (this.notify != that.notify) { return false; } return super.equals(obj); } /** * Returns a hashcode for the title. * * @return The hashcode. */ @Override public int hashCode() { int result = 193; result = 37 * result + ObjectUtilities.hashCode(this.position); result = 37 * result + ObjectUtilities.hashCode(this.horizontalAlignment); result = 37 * result + ObjectUtilities.hashCode(this.verticalAlignment); return result; } /** * Provides serialization support. * * @param stream the output stream. * * @throws IOException if there is an I/O error. */ private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); } /** * Provides serialization support. * * @param stream the input stream. * * @throws IOException if there is an I/O error. * @throws ClassNotFoundException if there is a classpath problem. */ private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); this.listenerList = new EventListenerList(); } }
16,183
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
PaintScaleLegend.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/title/PaintScaleLegend.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * --------------------- * PaintScaleLegend.java * --------------------- * (C) Copyright 2007-2012, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): Peter Kolb - see patch 2686872; * * Changes * ------- * 22-Jan-2007 : Version 1 (DG); * 18-Jun-2008 : Fixed bug drawing scale with log axis (DG); * 16-Apr-2009 : Patch 2686872 implementing AxisChangeListener, and fix for * ignored stripOutlineVisible flag (DG); * 17-Jun-2012 : Removed JCommon dependencies (DG); * */ package org.jfree.chart.title; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.Stroke; import java.awt.geom.Rectangle2D; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import org.jfree.chart.axis.AxisLocation; import org.jfree.chart.axis.AxisSpace; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.block.LengthConstraintType; import org.jfree.chart.block.RectangleConstraint; import org.jfree.chart.ui.RectangleEdge; import org.jfree.chart.ui.Size2D; import org.jfree.chart.util.PaintUtilities; import org.jfree.chart.util.PublicCloneable; import org.jfree.chart.event.AxisChangeEvent; import org.jfree.chart.event.AxisChangeListener; import org.jfree.chart.event.TitleChangeEvent; import org.jfree.chart.plot.Plot; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.renderer.PaintScale; import org.jfree.chart.util.SerialUtilities; import org.jfree.data.Range; /** * A legend that shows a range of values and their associated colors, driven * by an underlying {@link PaintScale} implementation. * * @since 1.0.4 */ public class PaintScaleLegend extends Title implements AxisChangeListener, PublicCloneable { /** For serialization. */ static final long serialVersionUID = -1365146490993227503L; /** The paint scale (never <code>null</code>). */ private PaintScale scale; /** The value axis (never <code>null</code>). */ private ValueAxis axis; /** * The axis location (handles both orientations, never * <code>null</code>). */ private AxisLocation axisLocation; /** The offset between the axis and the paint strip (in Java2D units). */ private double axisOffset; /** The thickness of the paint strip (in Java2D units). */ private double stripWidth; /** * A flag that controls whether or not an outline is drawn around the * paint strip. */ private boolean stripOutlineVisible; /** The paint used to draw an outline around the paint strip. */ private transient Paint stripOutlinePaint; /** The stroke used to draw an outline around the paint strip. */ private transient Stroke stripOutlineStroke; /** The background paint (never <code>null</code>). */ private transient Paint backgroundPaint; /** * The number of subdivisions for the scale when rendering. * * @since 1.0.11 */ private int subdivisions; /** * Creates a new instance. * * @param scale the scale (<code>null</code> not permitted). * @param axis the axis (<code>null</code> not permitted). */ public PaintScaleLegend(PaintScale scale, ValueAxis axis) { if (axis == null) { throw new IllegalArgumentException("Null 'axis' argument."); } this.scale = scale; this.axis = axis; this.axis.addChangeListener(this); this.axisLocation = AxisLocation.BOTTOM_OR_LEFT; this.axisOffset = 0.0; this.axis.setRange(scale.getLowerBound(), scale.getUpperBound()); this.stripWidth = 15.0; this.stripOutlineVisible = true; this.stripOutlinePaint = Color.GRAY; this.stripOutlineStroke = new BasicStroke(0.5f); this.backgroundPaint = Color.WHITE; this.subdivisions = 100; } /** * Returns the scale used to convert values to colors. * * @return The scale (never <code>null</code>). * * @see #setScale(PaintScale) */ public PaintScale getScale() { return this.scale; } /** * Sets the scale and sends a {@link TitleChangeEvent} to all registered * listeners. * * @param scale the scale (<code>null</code> not permitted). * * @see #getScale() */ public void setScale(PaintScale scale) { if (scale == null) { throw new IllegalArgumentException("Null 'scale' argument."); } this.scale = scale; notifyListeners(new TitleChangeEvent(this)); } /** * Returns the axis for the paint scale. * * @return The axis (never <code>null</code>). * * @see #setAxis(ValueAxis) */ public ValueAxis getAxis() { return this.axis; } /** * Sets the axis for the paint scale and sends a {@link TitleChangeEvent} * to all registered listeners. * * @param axis the axis (<code>null</code> not permitted). * * @see #getAxis() */ public void setAxis(ValueAxis axis) { if (axis == null) { throw new IllegalArgumentException("Null 'axis' argument."); } this.axis.removeChangeListener(this); this.axis = axis; this.axis.addChangeListener(this); notifyListeners(new TitleChangeEvent(this)); } /** * Returns the axis location. * * @return The axis location (never <code>null</code>). * * @see #setAxisLocation(AxisLocation) */ public AxisLocation getAxisLocation() { return this.axisLocation; } /** * Sets the axis location and sends a {@link TitleChangeEvent} to all * registered listeners. * * @param location the location (<code>null</code> not permitted). * * @see #getAxisLocation() */ public void setAxisLocation(AxisLocation location) { if (location == null) { throw new IllegalArgumentException("Null 'location' argument."); } this.axisLocation = location; notifyListeners(new TitleChangeEvent(this)); } /** * Returns the offset between the axis and the paint strip. * * @return The offset between the axis and the paint strip. * * @see #setAxisOffset(double) */ public double getAxisOffset() { return this.axisOffset; } /** * Sets the offset between the axis and the paint strip and sends a * {@link TitleChangeEvent} to all registered listeners. * * @param offset the offset. */ public void setAxisOffset(double offset) { this.axisOffset = offset; notifyListeners(new TitleChangeEvent(this)); } /** * Returns the width of the paint strip, in Java2D units. * * @return The width of the paint strip. * * @see #setStripWidth(double) */ public double getStripWidth() { return this.stripWidth; } /** * Sets the width of the paint strip and sends a {@link TitleChangeEvent} * to all registered listeners. * * @param width the width. * * @see #getStripWidth() */ public void setStripWidth(double width) { this.stripWidth = width; notifyListeners(new TitleChangeEvent(this)); } /** * Returns the flag that controls whether or not an outline is drawn * around the paint strip. * * @return A boolean. * * @see #setStripOutlineVisible(boolean) */ public boolean isStripOutlineVisible() { return this.stripOutlineVisible; } /** * Sets the flag that controls whether or not an outline is drawn around * the paint strip, and sends a {@link TitleChangeEvent} to all registered * listeners. * * @param visible the flag. * * @see #isStripOutlineVisible() */ public void setStripOutlineVisible(boolean visible) { this.stripOutlineVisible = visible; notifyListeners(new TitleChangeEvent(this)); } /** * Returns the paint used to draw the outline of the paint strip. * * @return The paint (never <code>null</code>). * * @see #setStripOutlinePaint(Paint) */ public Paint getStripOutlinePaint() { return this.stripOutlinePaint; } /** * Sets the paint used to draw the outline of the paint strip, and sends * a {@link TitleChangeEvent} to all registered listeners. * * @param paint the paint (<code>null</code> not permitted). * * @see #getStripOutlinePaint() */ public void setStripOutlinePaint(Paint paint) { if (paint == null) { throw new IllegalArgumentException("Null 'paint' argument."); } this.stripOutlinePaint = paint; notifyListeners(new TitleChangeEvent(this)); } /** * Returns the stroke used to draw the outline around the paint strip. * * @return The stroke (never <code>null</code>). * * @see #setStripOutlineStroke(Stroke) */ public Stroke getStripOutlineStroke() { return this.stripOutlineStroke; } /** * Sets the stroke used to draw the outline around the paint strip and * sends a {@link TitleChangeEvent} to all registered listeners. * * @param stroke the stroke (<code>null</code> not permitted). * * @see #getStripOutlineStroke() */ public void setStripOutlineStroke(Stroke stroke) { if (stroke == null) { throw new IllegalArgumentException("Null 'stroke' argument."); } this.stripOutlineStroke = stroke; notifyListeners(new TitleChangeEvent(this)); } /** * Returns the background paint. * * @return The background paint. */ public Paint getBackgroundPaint() { return this.backgroundPaint; } /** * Sets the background paint and sends a {@link TitleChangeEvent} to all * registered listeners. * * @param paint the paint (<code>null</code> permitted). */ public void setBackgroundPaint(Paint paint) { this.backgroundPaint = paint; notifyListeners(new TitleChangeEvent(this)); } /** * Returns the number of subdivisions used to draw the scale. * * @return The subdivision count. * * @since 1.0.11 */ public int getSubdivisionCount() { return this.subdivisions; } /** * Sets the subdivision count and sends a {@link TitleChangeEvent} to * all registered listeners. * * @param count the count. * * @since 1.0.11 */ public void setSubdivisionCount(int count) { if (count <= 0) { throw new IllegalArgumentException("Requires 'count' > 0."); } this.subdivisions = count; notifyListeners(new TitleChangeEvent(this)); } /** * Receives notification of an axis change event and responds by firing * a title change event. * * @param event the event. * * @since 1.0.13 */ @Override public void axisChanged(AxisChangeEvent event) { if (this.axis == event.getAxis()) { notifyListeners(new TitleChangeEvent(this)); } } /** * Arranges the contents of the block, within the given constraints, and * returns the block size. * * @param g2 the graphics device. * @param constraint the constraint (<code>null</code> not permitted). * * @return The block size (in Java2D units, never <code>null</code>). */ @Override public Size2D arrange(Graphics2D g2, RectangleConstraint constraint) { RectangleConstraint cc = toContentConstraint(constraint); LengthConstraintType w = cc.getWidthConstraintType(); LengthConstraintType h = cc.getHeightConstraintType(); Size2D contentSize = null; if (w == LengthConstraintType.NONE) { if (h == LengthConstraintType.NONE) { contentSize = new Size2D(getWidth(), getHeight()); } else if (h == LengthConstraintType.RANGE) { throw new RuntimeException("Not yet implemented."); } else if (h == LengthConstraintType.FIXED) { throw new RuntimeException("Not yet implemented."); } } else if (w == LengthConstraintType.RANGE) { if (h == LengthConstraintType.NONE) { throw new RuntimeException("Not yet implemented."); } else if (h == LengthConstraintType.RANGE) { contentSize = arrangeRR(g2, cc.getWidthRange(), cc.getHeightRange()); } else if (h == LengthConstraintType.FIXED) { throw new RuntimeException("Not yet implemented."); } } else if (w == LengthConstraintType.FIXED) { if (h == LengthConstraintType.NONE) { throw new RuntimeException("Not yet implemented."); } else if (h == LengthConstraintType.RANGE) { throw new RuntimeException("Not yet implemented."); } else if (h == LengthConstraintType.FIXED) { throw new RuntimeException("Not yet implemented."); } } return new Size2D(calculateTotalWidth(contentSize.getWidth()), calculateTotalHeight(contentSize.getHeight())); } /** * Returns the content size for the title. This will reflect the fact that * a text title positioned on the left or right of a chart will be rotated * 90 degrees. * * @param g2 the graphics device. * @param widthRange the width range. * @param heightRange the height range. * * @return The content size. */ protected Size2D arrangeRR(Graphics2D g2, Range widthRange, Range heightRange) { RectangleEdge position = getPosition(); if (position == RectangleEdge.TOP || position == RectangleEdge.BOTTOM) { float maxWidth = (float) widthRange.getUpperBound(); // determine the space required for the axis AxisSpace space = this.axis.reserveSpace(g2, null, new Rectangle2D.Double(0, 0, maxWidth, 100), RectangleEdge.BOTTOM, null); return new Size2D(maxWidth, this.stripWidth + this.axisOffset + space.getTop() + space.getBottom()); } else if (position == RectangleEdge.LEFT || position == RectangleEdge.RIGHT) { float maxHeight = (float) heightRange.getUpperBound(); AxisSpace space = this.axis.reserveSpace(g2, null, new Rectangle2D.Double(0, 0, 100, maxHeight), RectangleEdge.RIGHT, null); return new Size2D(this.stripWidth + this.axisOffset + space.getLeft() + space.getRight(), maxHeight); } else { throw new RuntimeException("Unrecognised position."); } } /** * Draws the legend within the specified area. * * @param g2 the graphics target (<code>null</code> not permitted). * @param area the drawing area (<code>null</code> not permitted). */ @Override public void draw(Graphics2D g2, Rectangle2D area) { draw(g2, area, null); } /** * Draws the legend within the specified area. * * @param g2 the graphics target (<code>null</code> not permitted). * @param area the drawing area (<code>null</code> not permitted). * @param params drawing parameters (ignored here). * * @return <code>null</code>. */ @Override public Object draw(Graphics2D g2, Rectangle2D area, Object params) { Rectangle2D target = (Rectangle2D) area.clone(); target = trimMargin(target); if (this.backgroundPaint != null) { g2.setPaint(this.backgroundPaint); g2.fill(target); } getFrame().draw(g2, target); getFrame().getInsets().trim(target); target = trimPadding(target); double base = this.axis.getLowerBound(); double increment = this.axis.getRange().getLength() / this.subdivisions; Rectangle2D r = new Rectangle2D.Double(); if (RectangleEdge.isTopOrBottom(getPosition())) { RectangleEdge axisEdge = Plot.resolveRangeAxisLocation( this.axisLocation, PlotOrientation.HORIZONTAL); if (axisEdge == RectangleEdge.TOP) { for (int i = 0; i < this.subdivisions; i++) { double v = base + (i * increment); Paint p = this.scale.getPaint(v); double vv0 = this.axis.valueToJava2D(v, target, RectangleEdge.TOP); double vv1 = this.axis.valueToJava2D(v + increment, target, RectangleEdge.TOP); double ww = Math.abs(vv1 - vv0) + 1.0; r.setRect(Math.min(vv0, vv1), target.getMaxY() - this.stripWidth, ww, this.stripWidth); g2.setPaint(p); g2.fill(r); } if (isStripOutlineVisible()) { g2.setPaint(this.stripOutlinePaint); g2.setStroke(this.stripOutlineStroke); g2.draw(new Rectangle2D.Double(target.getMinX(), target.getMaxY() - this.stripWidth, target.getWidth(), this.stripWidth)); } this.axis.draw(g2, target.getMaxY() - this.stripWidth - this.axisOffset, target, target, RectangleEdge.TOP, null); } else if (axisEdge == RectangleEdge.BOTTOM) { for (int i = 0; i < this.subdivisions; i++) { double v = base + (i * increment); Paint p = this.scale.getPaint(v); double vv0 = this.axis.valueToJava2D(v, target, RectangleEdge.BOTTOM); double vv1 = this.axis.valueToJava2D(v + increment, target, RectangleEdge.BOTTOM); double ww = Math.abs(vv1 - vv0) + 1.0; r.setRect(Math.min(vv0, vv1), target.getMinY(), ww, this.stripWidth); g2.setPaint(p); g2.fill(r); } if (isStripOutlineVisible()) { g2.setPaint(this.stripOutlinePaint); g2.setStroke(this.stripOutlineStroke); g2.draw(new Rectangle2D.Double(target.getMinX(), target.getMinY(), target.getWidth(), this.stripWidth)); } this.axis.draw(g2, target.getMinY() + this.stripWidth + this.axisOffset, target, target, RectangleEdge.BOTTOM, null); } } else { RectangleEdge axisEdge = Plot.resolveRangeAxisLocation( this.axisLocation, PlotOrientation.VERTICAL); if (axisEdge == RectangleEdge.LEFT) { for (int i = 0; i < this.subdivisions; i++) { double v = base + (i * increment); Paint p = this.scale.getPaint(v); double vv0 = this.axis.valueToJava2D(v, target, RectangleEdge.LEFT); double vv1 = this.axis.valueToJava2D(v + increment, target, RectangleEdge.LEFT); double hh = Math.abs(vv1 - vv0) + 1.0; r.setRect(target.getMaxX() - this.stripWidth, Math.min(vv0, vv1), this.stripWidth, hh); g2.setPaint(p); g2.fill(r); } if (isStripOutlineVisible()) { g2.setPaint(this.stripOutlinePaint); g2.setStroke(this.stripOutlineStroke); g2.draw(new Rectangle2D.Double(target.getMaxX() - this.stripWidth, target.getMinY(), this.stripWidth, target.getHeight())); } this.axis.draw(g2, target.getMaxX() - this.stripWidth - this.axisOffset, target, target, RectangleEdge.LEFT, null); } else if (axisEdge == RectangleEdge.RIGHT) { for (int i = 0; i < this.subdivisions; i++) { double v = base + (i * increment); Paint p = this.scale.getPaint(v); double vv0 = this.axis.valueToJava2D(v, target, RectangleEdge.LEFT); double vv1 = this.axis.valueToJava2D(v + increment, target, RectangleEdge.LEFT); double hh = Math.abs(vv1 - vv0) + 1.0; r.setRect(target.getMinX(), Math.min(vv0, vv1), this.stripWidth, hh); g2.setPaint(p); g2.fill(r); } if (isStripOutlineVisible()) { g2.setPaint(this.stripOutlinePaint); g2.setStroke(this.stripOutlineStroke); g2.draw(new Rectangle2D.Double(target.getMinX(), target.getMinY(), this.stripWidth, target.getHeight())); } this.axis.draw(g2, target.getMinX() + this.stripWidth + this.axisOffset, target, target, RectangleEdge.RIGHT, null); } } return null; } /** * Tests this legend for equality with an arbitrary object. * * @param obj the object (<code>null</code> permitted). * * @return A boolean. */ @Override public boolean equals(Object obj) { if (!(obj instanceof PaintScaleLegend)) { return false; } PaintScaleLegend that = (PaintScaleLegend) obj; if (!this.scale.equals(that.scale)) { return false; } if (!this.axis.equals(that.axis)) { return false; } if (!this.axisLocation.equals(that.axisLocation)) { return false; } if (this.axisOffset != that.axisOffset) { return false; } if (this.stripWidth != that.stripWidth) { return false; } if (this.stripOutlineVisible != that.stripOutlineVisible) { return false; } if (!PaintUtilities.equal(this.stripOutlinePaint, that.stripOutlinePaint)) { return false; } if (!this.stripOutlineStroke.equals(that.stripOutlineStroke)) { return false; } if (!PaintUtilities.equal(this.backgroundPaint, that.backgroundPaint)) { return false; } if (this.subdivisions != that.subdivisions) { return false; } return super.equals(obj); } /** * Provides serialization support. * * @param stream the output stream. * * @throws IOException if there is an I/O error. */ private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); SerialUtilities.writePaint(this.backgroundPaint, stream); SerialUtilities.writePaint(this.stripOutlinePaint, stream); SerialUtilities.writeStroke(this.stripOutlineStroke, stream); } /** * Provides serialization support. * * @param stream the input stream. * * @throws IOException if there is an I/O error. * @throws ClassNotFoundException if there is a classpath problem. */ private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); this.backgroundPaint = SerialUtilities.readPaint(stream); this.stripOutlinePaint = SerialUtilities.readPaint(stream); this.stripOutlineStroke = SerialUtilities.readStroke(stream); } }
25,816
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
DateTitle.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/title/DateTitle.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * -------------- * DateTitle.java * -------------- * (C) Copyright 2000-2012, by David Berry and Contributors. * * Original Author: David Berry; * Contributor(s): David Gilbert (for Object Refinery Limited); * * Changes (from 18-Sep-2001) * -------------------------- * 18-Sep-2001 : Added standard header (DG); * 09-Jan-2002 : Updated Javadoc comments (DG); * 07-Feb-2002 : Changed blank space around title from Insets --> Spacer, to * allow for relative or absolute spacing (DG); * 26-Sep-2002 : Fixed errors reported by Checkstyle (DG); * 31-Jan-2005 : Updated for changes to super class (DG); * ------------- JFREECHART 1.0.x --------------------------------------------- * 02-Feb-2007 : Removed author tags all over JFreeChart sources (DG); * 16-Jun-2012 : Removed JCommon dependencies (DG); * */ package org.jfree.chart.title; import java.awt.Color; import java.awt.Font; import java.awt.Paint; import java.io.Serializable; import java.text.DateFormat; import java.util.Date; import java.util.Locale; import org.jfree.chart.ui.HorizontalAlignment; import org.jfree.chart.ui.RectangleEdge; import org.jfree.chart.ui.RectangleInsets; import org.jfree.chart.ui.VerticalAlignment; /** * A chart title that displays the date. * <p> * Keep in mind that a chart can have several titles, and that they can appear * at the top, left, right or bottom of the chart - a <code>DateTitle</code> * will commonly appear at the bottom of a chart, although you can place it * anywhere. * <P> * By specifying the locale, dates are formatted to the correct standard for * the given locale. For example, a date would appear as "January 17, 2000" in * the US, but "17 January 2000" in most European locales. */ public class DateTitle extends TextTitle implements Serializable { /** For serialization. */ private static final long serialVersionUID = -465434812763159881L; /** * Creates a new chart title that displays the current date in the default * (LONG) format for the locale, positioned to the bottom right of the * chart. * <P> * The color will be black in 12 point, plain Helvetica font (maps to Arial * on Win32 systems without Helvetica). */ public DateTitle() { this(DateFormat.LONG); } /** * Creates a new chart title that displays the current date with the * specified style (for the default locale). * <P> * The date style should be one of: <code>SHORT</code>, * <code>MEDIUM</code>, <code>LONG</code> or <code>FULL</code> * (defined in <code>java.util.DateFormat</code>). * * @param style the date style. */ public DateTitle(int style) { this(style, Locale.getDefault(), new Font("Dialog", Font.PLAIN, 12), Color.BLACK); } /** * Creates a new chart title that displays the current date. * <p> * The date style should be one of: <code>SHORT</code>, * <code>MEDIUM</code>, <code>LONG</code> or <code>FULL</code> (defined * in <code>java.util.DateFormat</code>). * <P> * For the locale, you can use <code>Locale.getDefault()</code> for the * default locale. * * @param style the date style. * @param locale the locale. * @param font the font. * @param paint the text color. */ public DateTitle(int style, Locale locale, Font font, Paint paint) { this(style, locale, font, paint, RectangleEdge.BOTTOM, HorizontalAlignment.RIGHT, VerticalAlignment.CENTER, Title.DEFAULT_PADDING); } /** * Creates a new chart title that displays the current date. * <p> * The date style should be one of: <code>SHORT</code>, * <code>MEDIUM</code>, <code>LONG</code> or <code>FULL</code> (defined * in <code>java.util.DateFormat<code>). * <P> * For the locale, you can use <code>Locale.getDefault()</code> for the * default locale. * * @param style the date style. * @param locale the locale. * @param font the font (not null). * @param paint the text color (not null). * @param position the relative location of this title (use constants in * Title). * @param horizontalAlignment the horizontal text alignment of this title * (use constants in Title). * @param verticalAlignment the vertical text alignment of this title (use * constants in Title). * @param padding determines the blank space around the outside of the * title (not null). */ public DateTitle(int style, Locale locale, Font font, Paint paint, RectangleEdge position, HorizontalAlignment horizontalAlignment, VerticalAlignment verticalAlignment, RectangleInsets padding) { super(DateFormat.getDateInstance(style, locale).format(new Date()), font, paint, position, horizontalAlignment, verticalAlignment, padding); } /** * Set the format of the date. * <P> * The date style should be one of: <code>SHORT</code>, * <code>MEDIUM</code>, <code>LONG</code> or <code>FULL</code> (defined * in <code>java.util.DateFormat</code>). * <P> * For the locale, you can use <code>Locale.getDefault()</code> for the * default locale. * * @param style the date style. * @param locale the locale. */ public void setDateFormat(int style, Locale locale) { setText(DateFormat.getDateInstance(style, locale).format(new Date())); } }
6,933
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
TextTitle.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/title/TextTitle.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * -------------- * TextTitle.java * -------------- * (C) Copyright 2000-2012, by David Berry and Contributors. * * Original Author: David Berry; * Contributor(s): David Gilbert (for Object Refinery Limited); * Nicolas Brodu; * Peter Kolb - patch 2603321; * * Changes (from 18-Sep-2001) * -------------------------- * 18-Sep-2001 : Added standard header (DG); * 07-Nov-2001 : Separated the JCommon Class Library classes, JFreeChart now * requires jcommon.jar (DG); * 09-Jan-2002 : Updated Javadoc comments (DG); * 07-Feb-2002 : Changed Insets --> Spacer in AbstractTitle.java (DG); * 06-Mar-2002 : Updated import statements (DG); * 25-Jun-2002 : Removed redundant imports (DG); * 18-Sep-2002 : Fixed errors reported by Checkstyle (DG); * 28-Oct-2002 : Small modifications while changing JFreeChart class (DG); * 13-Mar-2003 : Changed width used for relative spacing to fix bug 703050 (DG); * 26-Mar-2003 : Implemented Serializable (DG); * 15-Jul-2003 : Fixed null pointer exception (DG); * 11-Sep-2003 : Implemented Cloneable (NB) * 22-Sep-2003 : Added checks for null values and throw nullpointer * exceptions (TM); * Background paint was not serialized. * 07-Oct-2003 : Added fix for exception caused by empty string in title (DG); * 29-Oct-2003 : Added workaround for text alignment in PDF output (DG); * 03-Feb-2004 : Fixed bug in getPreferredWidth() method (DG); * 17-Feb-2004 : Added clone() method and fixed bug in equals() method (DG); * 01-Apr-2004 : Changed java.awt.geom.Dimension2D to org.jfree.ui.Size2D * because of JDK bug 4976448 which persists on JDK 1.3.1. Also * fixed bug in getPreferredHeight() method (DG); * 29-Apr-2004 : Fixed bug in getPreferredWidth() method - see bug id * 944173 (DG); * 11-Jan-2005 : Removed deprecated code in preparation for the 1.0.0 * release (DG); * 08-Feb-2005 : Updated for changes in RectangleConstraint class (DG); * 11-Feb-2005 : Implemented PublicCloneable (DG); * 20-Apr-2005 : Added support for tooltips (DG); * 26-Apr-2005 : Removed LOGGER (DG); * 06-Jun-2005 : Modified equals() to handle GradientPaint (DG); * 06-Jul-2005 : Added flag to control whether or not the title expands to * fit the available space (DG); * 07-Oct-2005 : Added textAlignment attribute (DG); * ------------- JFREECHART 1.0.x RELEASED ------------------------------------ * 13-Dec-2005 : Fixed bug 1379331 - incorrect drawing with LEFT or RIGHT * title placement (DG); * 19-Dec-2007 : Implemented some of the missing arrangement options (DG); * 28-Apr-2008 : Added option for maximum lines, and fixed minor bugs in * equals() method (DG); * 19-Mar-2009 : Changed ChartEntity to TitleEntity - see patch 2603321 by * Peter Kolb (DG); * 15-Jun-2012 : Removed JCommon dependencies (DG); * */ package org.jfree.chart.title; import java.awt.Color; import java.awt.Font; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.geom.Rectangle2D; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import org.jfree.chart.block.BlockResult; import org.jfree.chart.block.EntityBlockParams; import org.jfree.chart.block.LengthConstraintType; import org.jfree.chart.block.RectangleConstraint; import org.jfree.chart.ui.HorizontalAlignment; import org.jfree.chart.ui.RectangleEdge; import org.jfree.chart.ui.RectangleInsets; import org.jfree.chart.ui.Size2D; import org.jfree.chart.ui.VerticalAlignment; import org.jfree.chart.util.ObjectUtilities; import org.jfree.chart.util.PaintUtilities; import org.jfree.chart.util.PublicCloneable; import org.jfree.chart.entity.ChartEntity; import org.jfree.chart.entity.EntityCollection; import org.jfree.chart.entity.StandardEntityCollection; import org.jfree.chart.entity.TitleEntity; import org.jfree.chart.event.TitleChangeEvent; import org.jfree.chart.text.G2TextMeasurer; import org.jfree.chart.text.TextBlock; import org.jfree.chart.text.TextBlockAnchor; import org.jfree.chart.text.TextUtilities; import org.jfree.chart.util.SerialUtilities; import org.jfree.data.Range; /** * A chart title that displays a text string with automatic wrapping as * required. */ public class TextTitle extends Title implements Serializable, Cloneable, PublicCloneable { /** For serialization. */ private static final long serialVersionUID = 8372008692127477443L; /** The default font. */ public static final Font DEFAULT_FONT = new Font("SansSerif", Font.BOLD, 12); /** The default text color. */ public static final Paint DEFAULT_TEXT_PAINT = Color.BLACK; /** The title text. */ private String text; /** The font used to display the title. */ private Font font; /** The text alignment. */ private HorizontalAlignment textAlignment; /** The paint used to display the title text. */ private transient Paint paint; /** The background paint. */ private transient Paint backgroundPaint; /** The tool tip text (can be <code>null</code>). */ private String toolTipText; /** The URL text (can be <code>null</code>). */ private String urlText; /** The content. */ private TextBlock content; /** * A flag that controls whether the title expands to fit the available * space.. */ private boolean expandToFitSpace = false; /** * The maximum number of lines to display. * * @since 1.0.10 */ private int maximumLinesToDisplay = Integer.MAX_VALUE; /** * Creates a new title, using default attributes where necessary. */ public TextTitle() { this(""); } /** * Creates a new title, using default attributes where necessary. * * @param text the title text (<code>null</code> not permitted). */ public TextTitle(String text) { this(text, TextTitle.DEFAULT_FONT, TextTitle.DEFAULT_TEXT_PAINT, Title.DEFAULT_POSITION, Title.DEFAULT_HORIZONTAL_ALIGNMENT, Title.DEFAULT_VERTICAL_ALIGNMENT, Title.DEFAULT_PADDING); } /** * Creates a new title, using default attributes where necessary. * * @param text the title text (<code>null</code> not permitted). * @param font the title font (<code>null</code> not permitted). */ public TextTitle(String text, Font font) { this(text, font, TextTitle.DEFAULT_TEXT_PAINT, Title.DEFAULT_POSITION, Title.DEFAULT_HORIZONTAL_ALIGNMENT, Title.DEFAULT_VERTICAL_ALIGNMENT, Title.DEFAULT_PADDING); } /** * Creates a new title. * * @param text the text for the title (<code>null</code> not permitted). * @param font the title font (<code>null</code> not permitted). * @param paint the title paint (<code>null</code> not permitted). * @param position the title position (<code>null</code> not permitted). * @param horizontalAlignment the horizontal alignment (<code>null</code> * not permitted). * @param verticalAlignment the vertical alignment (<code>null</code> not * permitted). * @param padding the space to leave around the outside of the title. */ public TextTitle(String text, Font font, Paint paint, RectangleEdge position, HorizontalAlignment horizontalAlignment, VerticalAlignment verticalAlignment, RectangleInsets padding) { super(position, horizontalAlignment, verticalAlignment, padding); if (text == null) { throw new NullPointerException("Null 'text' argument."); } if (font == null) { throw new NullPointerException("Null 'font' argument."); } if (paint == null) { throw new NullPointerException("Null 'paint' argument."); } this.text = text; this.font = font; this.paint = paint; // the textAlignment and the horizontalAlignment are separate things, // but it makes sense for the default textAlignment to match the // title's horizontal alignment... this.textAlignment = horizontalAlignment; this.backgroundPaint = null; this.content = null; this.toolTipText = null; this.urlText = null; } /** * Returns the title text. * * @return The text (never <code>null</code>). * * @see #setText(String) */ public String getText() { return this.text; } /** * Sets the title to the specified text and sends a * {@link TitleChangeEvent} to all registered listeners. * * @param text the text (<code>null</code> not permitted). */ public void setText(String text) { if (text == null) { throw new IllegalArgumentException("Null 'text' argument."); } if (!this.text.equals(text)) { this.text = text; notifyListeners(new TitleChangeEvent(this)); } } /** * Returns the text alignment. This controls how the text is aligned * within the title's bounds, whereas the title's horizontal alignment * controls how the title's bounding rectangle is aligned within the * drawing space. * * @return The text alignment. */ public HorizontalAlignment getTextAlignment() { return this.textAlignment; } /** * Sets the text alignment and sends a {@link TitleChangeEvent} to * all registered listeners. * * @param alignment the alignment (<code>null</code> not permitted). */ public void setTextAlignment(HorizontalAlignment alignment) { if (alignment == null) { throw new IllegalArgumentException("Null 'alignment' argument."); } this.textAlignment = alignment; notifyListeners(new TitleChangeEvent(this)); } /** * Returns the font used to display the title string. * * @return The font (never <code>null</code>). * * @see #setFont(Font) */ public Font getFont() { return this.font; } /** * Sets the font used to display the title string. Registered listeners * are notified that the title has been modified. * * @param font the new font (<code>null</code> not permitted). * * @see #getFont() */ public void setFont(Font font) { if (font == null) { throw new IllegalArgumentException("Null 'font' argument."); } if (!this.font.equals(font)) { this.font = font; notifyListeners(new TitleChangeEvent(this)); } } /** * Returns the paint used to display the title string. * * @return The paint (never <code>null</code>). * * @see #setPaint(Paint) */ public Paint getPaint() { return this.paint; } /** * Sets the paint used to display the title string. Registered listeners * are notified that the title has been modified. * * @param paint the new paint (<code>null</code> not permitted). * * @see #getPaint() */ public void setPaint(Paint paint) { if (paint == null) { throw new IllegalArgumentException("Null 'paint' argument."); } if (!this.paint.equals(paint)) { this.paint = paint; notifyListeners(new TitleChangeEvent(this)); } } /** * Returns the background paint. * * @return The paint (possibly <code>null</code>). */ public Paint getBackgroundPaint() { return this.backgroundPaint; } /** * Sets the background paint and sends a {@link TitleChangeEvent} to all * registered listeners. If you set this attribute to <code>null</code>, * no background is painted (which makes the title background transparent). * * @param paint the background paint (<code>null</code> permitted). */ public void setBackgroundPaint(Paint paint) { this.backgroundPaint = paint; notifyListeners(new TitleChangeEvent(this)); } /** * Returns the tool tip text. * * @return The tool tip text (possibly <code>null</code>). */ public String getToolTipText() { return this.toolTipText; } /** * Sets the tool tip text to the specified text and sends a * {@link TitleChangeEvent} to all registered listeners. * * @param text the text (<code>null</code> permitted). */ public void setToolTipText(String text) { this.toolTipText = text; notifyListeners(new TitleChangeEvent(this)); } /** * Returns the URL text. * * @return The URL text (possibly <code>null</code>). */ public String getURLText() { return this.urlText; } /** * Sets the URL text to the specified text and sends a * {@link TitleChangeEvent} to all registered listeners. * * @param text the text (<code>null</code> permitted). */ public void setURLText(String text) { this.urlText = text; notifyListeners(new TitleChangeEvent(this)); } /** * Returns the flag that controls whether or not the title expands to fit * the available space. * * @return The flag. */ public boolean getExpandToFitSpace() { return this.expandToFitSpace; } /** * Sets the flag that controls whether the title expands to fit the * available space, and sends a {@link TitleChangeEvent} to all registered * listeners. * * @param expand the flag. */ public void setExpandToFitSpace(boolean expand) { this.expandToFitSpace = expand; notifyListeners(new TitleChangeEvent(this)); } /** * Returns the maximum number of lines to display. * * @return The maximum. * * @since 1.0.10 * * @see #setMaximumLinesToDisplay(int) */ public int getMaximumLinesToDisplay() { return this.maximumLinesToDisplay; } /** * Sets the maximum number of lines to display and sends a * {@link TitleChangeEvent} to all registered listeners. * * @param max the maximum. * * @since 1.0.10. * * @see #getMaximumLinesToDisplay() */ public void setMaximumLinesToDisplay(int max) { this.maximumLinesToDisplay = max; notifyListeners(new TitleChangeEvent(this)); } /** * Arranges the contents of the block, within the given constraints, and * returns the block size. * * @param g2 the graphics device. * @param constraint the constraint (<code>null</code> not permitted). * * @return The block size (in Java2D units, never <code>null</code>). */ @Override public Size2D arrange(Graphics2D g2, RectangleConstraint constraint) { RectangleConstraint cc = toContentConstraint(constraint); LengthConstraintType w = cc.getWidthConstraintType(); LengthConstraintType h = cc.getHeightConstraintType(); Size2D contentSize = null; if (w == LengthConstraintType.NONE) { if (h == LengthConstraintType.NONE) { contentSize = arrangeNN(g2); } else if (h == LengthConstraintType.RANGE) { throw new RuntimeException("Not yet implemented."); } else if (h == LengthConstraintType.FIXED) { throw new RuntimeException("Not yet implemented."); } } else if (w == LengthConstraintType.RANGE) { if (h == LengthConstraintType.NONE) { contentSize = arrangeRN(g2, cc.getWidthRange()); } else if (h == LengthConstraintType.RANGE) { contentSize = arrangeRR(g2, cc.getWidthRange(), cc.getHeightRange()); } else if (h == LengthConstraintType.FIXED) { throw new RuntimeException("Not yet implemented."); } } else if (w == LengthConstraintType.FIXED) { if (h == LengthConstraintType.NONE) { contentSize = arrangeFN(g2, cc.getWidth()); } else if (h == LengthConstraintType.RANGE) { throw new RuntimeException("Not yet implemented."); } else if (h == LengthConstraintType.FIXED) { throw new RuntimeException("Not yet implemented."); } } return new Size2D(calculateTotalWidth(contentSize.getWidth()), calculateTotalHeight(contentSize.getHeight())); } /** * Arranges the content for this title assuming no bounds on the width * or the height, and returns the required size. This will reflect the * fact that a text title positioned on the left or right of a chart will * be rotated by 90 degrees. * * @param g2 the graphics target. * * @return The content size. * * @since 1.0.9 */ protected Size2D arrangeNN(Graphics2D g2) { Range max = new Range(0.0, Float.MAX_VALUE); return arrangeRR(g2, max, max); } /** * Arranges the content for this title assuming a fixed width and no bounds * on the height, and returns the required size. This will reflect the * fact that a text title positioned on the left or right of a chart will * be rotated by 90 degrees. * * @param g2 the graphics target. * @param w the width. * * @return The content size. * * @since 1.0.9 */ protected Size2D arrangeFN(Graphics2D g2, double w) { RectangleEdge position = getPosition(); if (position == RectangleEdge.TOP || position == RectangleEdge.BOTTOM) { float maxWidth = (float) w; g2.setFont(this.font); this.content = TextUtilities.createTextBlock(this.text, this.font, this.paint, maxWidth, this.maximumLinesToDisplay, new G2TextMeasurer(g2)); this.content.setLineAlignment(this.textAlignment); Size2D contentSize = this.content.calculateDimensions(g2); if (this.expandToFitSpace) { return new Size2D(maxWidth, contentSize.getHeight()); } else { return contentSize; } } else if (position == RectangleEdge.LEFT || position == RectangleEdge.RIGHT) { float maxWidth = Float.MAX_VALUE; g2.setFont(this.font); this.content = TextUtilities.createTextBlock(this.text, this.font, this.paint, maxWidth, this.maximumLinesToDisplay, new G2TextMeasurer(g2)); this.content.setLineAlignment(this.textAlignment); Size2D contentSize = this.content.calculateDimensions(g2); // transpose the dimensions, because the title is rotated if (this.expandToFitSpace) { return new Size2D(contentSize.getHeight(), maxWidth); } else { return new Size2D(contentSize.height, contentSize.width); } } else { throw new RuntimeException("Unrecognised exception."); } } /** * Arranges the content for this title assuming a range constraint for the * width and no bounds on the height, and returns the required size. This * will reflect the fact that a text title positioned on the left or right * of a chart will be rotated by 90 degrees. * * @param g2 the graphics target. * @param widthRange the range for the width. * * @return The content size. * * @since 1.0.9 */ protected Size2D arrangeRN(Graphics2D g2, Range widthRange) { Size2D s = arrangeNN(g2); if (widthRange.contains(s.getWidth())) { return s; } double ww = widthRange.constrain(s.getWidth()); return arrangeFN(g2, ww); } /** * Returns the content size for the title. This will reflect the fact that * a text title positioned on the left or right of a chart will be rotated * 90 degrees. * * @param g2 the graphics device. * @param widthRange the width range. * @param heightRange the height range. * * @return The content size. */ protected Size2D arrangeRR(Graphics2D g2, Range widthRange, Range heightRange) { RectangleEdge position = getPosition(); if (position == RectangleEdge.TOP || position == RectangleEdge.BOTTOM) { float maxWidth = (float) widthRange.getUpperBound(); g2.setFont(this.font); this.content = TextUtilities.createTextBlock(this.text, this.font, this.paint, maxWidth, this.maximumLinesToDisplay, new G2TextMeasurer(g2)); this.content.setLineAlignment(this.textAlignment); Size2D contentSize = this.content.calculateDimensions(g2); if (this.expandToFitSpace) { return new Size2D(maxWidth, contentSize.getHeight()); } else { return contentSize; } } else if (position == RectangleEdge.LEFT || position == RectangleEdge.RIGHT) { float maxWidth = (float) heightRange.getUpperBound(); g2.setFont(this.font); this.content = TextUtilities.createTextBlock(this.text, this.font, this.paint, maxWidth, this.maximumLinesToDisplay, new G2TextMeasurer(g2)); this.content.setLineAlignment(this.textAlignment); Size2D contentSize = this.content.calculateDimensions(g2); // transpose the dimensions, because the title is rotated if (this.expandToFitSpace) { return new Size2D(contentSize.getHeight(), maxWidth); } else { return new Size2D(contentSize.height, contentSize.width); } } else { throw new RuntimeException("Unrecognised exception."); } } /** * Draws the title on a Java 2D graphics device (such as the screen or a * printer). * * @param g2 the graphics device. * @param area the area allocated for the title. */ @Override public void draw(Graphics2D g2, Rectangle2D area) { draw(g2, area, null); } /** * Draws the block within the specified area. * * @param g2 the graphics device. * @param area the area. * @param params if this is an instance of {@link EntityBlockParams} it * is used to determine whether or not an * {@link EntityCollection} is returned by this method. * * @return An {@link EntityCollection} containing a chart entity for the * title, or <code>null</code>. */ @Override public Object draw(Graphics2D g2, Rectangle2D area, Object params) { if (this.content == null) { return null; } area = trimMargin(area); drawBorder(g2, area); if (this.text.equals("")) { return null; } ChartEntity entity = null; if (params instanceof EntityBlockParams) { EntityBlockParams p = (EntityBlockParams) params; if (p.getGenerateEntities()) { entity = new TitleEntity(area, this, this.toolTipText, this.urlText); } } area = trimBorder(area); if (this.backgroundPaint != null) { g2.setPaint(this.backgroundPaint); g2.fill(area); } area = trimPadding(area); RectangleEdge position = getPosition(); if (position == RectangleEdge.TOP || position == RectangleEdge.BOTTOM) { drawHorizontal(g2, area); } else if (position == RectangleEdge.LEFT || position == RectangleEdge.RIGHT) { drawVertical(g2, area); } BlockResult result = new BlockResult(); if (entity != null) { StandardEntityCollection sec = new StandardEntityCollection(); sec.add(entity); result.setEntityCollection(sec); } return result; } /** * Draws a the title horizontally within the specified area. This method * will be called from the {@link #draw(Graphics2D, Rectangle2D) draw} * method. * * @param g2 the graphics device. * @param area the area for the title. */ protected void drawHorizontal(Graphics2D g2, Rectangle2D area) { Rectangle2D titleArea = (Rectangle2D) area.clone(); g2.setFont(this.font); g2.setPaint(this.paint); TextBlockAnchor anchor = null; float x = 0.0f; HorizontalAlignment horizontalAlignment = getHorizontalAlignment(); if (horizontalAlignment == HorizontalAlignment.LEFT) { x = (float) titleArea.getX(); anchor = TextBlockAnchor.TOP_LEFT; } else if (horizontalAlignment == HorizontalAlignment.RIGHT) { x = (float) titleArea.getMaxX(); anchor = TextBlockAnchor.TOP_RIGHT; } else if (horizontalAlignment == HorizontalAlignment.CENTER) { x = (float) titleArea.getCenterX(); anchor = TextBlockAnchor.TOP_CENTER; } float y = 0.0f; RectangleEdge position = getPosition(); if (position == RectangleEdge.TOP) { y = (float) titleArea.getY(); } else if (position == RectangleEdge.BOTTOM) { y = (float) titleArea.getMaxY(); if (horizontalAlignment == HorizontalAlignment.LEFT) { anchor = TextBlockAnchor.BOTTOM_LEFT; } else if (horizontalAlignment == HorizontalAlignment.CENTER) { anchor = TextBlockAnchor.BOTTOM_CENTER; } else if (horizontalAlignment == HorizontalAlignment.RIGHT) { anchor = TextBlockAnchor.BOTTOM_RIGHT; } } this.content.draw(g2, x, y, anchor); } /** * Draws a the title vertically within the specified area. This method * will be called from the {@link #draw(Graphics2D, Rectangle2D) draw} * method. * * @param g2 the graphics device. * @param area the area for the title. */ protected void drawVertical(Graphics2D g2, Rectangle2D area) { Rectangle2D titleArea = (Rectangle2D) area.clone(); g2.setFont(this.font); g2.setPaint(this.paint); TextBlockAnchor anchor = null; float y = 0.0f; VerticalAlignment verticalAlignment = getVerticalAlignment(); if (verticalAlignment == VerticalAlignment.TOP) { y = (float) titleArea.getY(); anchor = TextBlockAnchor.TOP_RIGHT; } else if (verticalAlignment == VerticalAlignment.BOTTOM) { y = (float) titleArea.getMaxY(); anchor = TextBlockAnchor.TOP_LEFT; } else if (verticalAlignment == VerticalAlignment.CENTER) { y = (float) titleArea.getCenterY(); anchor = TextBlockAnchor.TOP_CENTER; } float x = 0.0f; RectangleEdge position = getPosition(); if (position == RectangleEdge.LEFT) { x = (float) titleArea.getX(); } else if (position == RectangleEdge.RIGHT) { x = (float) titleArea.getMaxX(); if (verticalAlignment == VerticalAlignment.TOP) { anchor = TextBlockAnchor.BOTTOM_RIGHT; } else if (verticalAlignment == VerticalAlignment.CENTER) { anchor = TextBlockAnchor.BOTTOM_CENTER; } else if (verticalAlignment == VerticalAlignment.BOTTOM) { anchor = TextBlockAnchor.BOTTOM_LEFT; } } this.content.draw(g2, x, y, anchor, x, y, -Math.PI / 2.0); } /** * Tests this title for equality with another object. * * @param obj the object (<code>null</code> permitted). * * @return <code>true</code> or <code>false</code>. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof TextTitle)) { return false; } TextTitle that = (TextTitle) obj; if (!ObjectUtilities.equal(this.text, that.text)) { return false; } if (!ObjectUtilities.equal(this.font, that.font)) { return false; } if (!PaintUtilities.equal(this.paint, that.paint)) { return false; } if (this.textAlignment != that.textAlignment) { return false; } if (!PaintUtilities.equal(this.backgroundPaint, that.backgroundPaint)) { return false; } if (this.maximumLinesToDisplay != that.maximumLinesToDisplay) { return false; } if (this.expandToFitSpace != that.expandToFitSpace) { return false; } if (!ObjectUtilities.equal(this.toolTipText, that.toolTipText)) { return false; } if (!ObjectUtilities.equal(this.urlText, that.urlText)) { return false; } return super.equals(obj); } /** * Returns a hash code. * * @return A hash code. */ @Override public int hashCode() { int result = super.hashCode(); result = 29 * result + (this.text != null ? this.text.hashCode() : 0); result = 29 * result + (this.font != null ? this.font.hashCode() : 0); result = 29 * result + (this.paint != null ? this.paint.hashCode() : 0); result = 29 * result + (this.backgroundPaint != null ? this.backgroundPaint.hashCode() : 0); return result; } /** * Returns a clone of this object. * * @return A clone. * * @throws CloneNotSupportedException never. */ @Override public Object clone() throws CloneNotSupportedException { return super.clone(); } /** * Provides serialization support. * * @param stream the output stream. * * @throws IOException if there is an I/O error. */ private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); SerialUtilities.writePaint(this.paint, stream); SerialUtilities.writePaint(this.backgroundPaint, stream); } /** * Provides serialization support. * * @param stream the input stream. * * @throws IOException if there is an I/O error. * @throws ClassNotFoundException if there is a classpath problem. */ private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); this.paint = SerialUtilities.readPaint(stream); this.backgroundPaint = SerialUtilities.readPaint(stream); } }
32,829
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
LegendItemBlockContainer.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/title/LegendItemBlockContainer.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ----------------------------- * LegendItemBlockContainer.java * ----------------------------- * (C) Copyright 2006-2008, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 20-Jul-2006 : Version 1 (DG); * 06-Oct-2006 : Added tooltip and URL text fields (DG); * 18-May-2007 : Added seriesKey and dataset fields (DG); * */ package org.jfree.chart.title; import java.awt.Graphics2D; import java.awt.Shape; import java.awt.geom.Rectangle2D; import org.jfree.chart.block.Arrangement; import org.jfree.chart.block.BlockContainer; import org.jfree.chart.block.BlockResult; import org.jfree.chart.block.EntityBlockParams; import org.jfree.chart.block.EntityBlockResult; import org.jfree.chart.entity.EntityCollection; import org.jfree.chart.entity.LegendItemEntity; import org.jfree.chart.entity.StandardEntityCollection; import org.jfree.data.general.Dataset; /** * A container that holds all the pieces of a single legend item. * * @since 1.0.2 */ public class LegendItemBlockContainer extends BlockContainer { /** * The dataset. * * @since 1.0.6 */ private Dataset dataset; /** * The series key. * * @since 1.0.6 */ private Comparable seriesKey; /** The dataset index. */ private int datasetIndex; /** The series index. */ private int series; /** The tool tip text (can be <code>null</code>). */ private String toolTipText; /** The URL text (can be <code>null</code>). */ private String urlText; /** * Creates a new legend item block. * * @param arrangement the arrangement. * @param dataset the dataset. * @param seriesKey the series key. * * @since 1.0.6 */ public LegendItemBlockContainer(Arrangement arrangement, Dataset dataset, Comparable seriesKey) { super(arrangement); this.dataset = dataset; this.seriesKey = seriesKey; } /** * Returns a reference to the dataset for the associated legend item. * * @return A dataset reference. * * @since 1.0.6 */ public Dataset getDataset() { return this.dataset; } /** * Returns the series key. * * @return The series key. * * @since 1.0.6 */ public Comparable getSeriesKey() { return this.seriesKey; } /** * Returns the series index. * * @return The series index. */ public int getSeriesIndex() { return this.series; } /** * Returns the tool tip text. * * @return The tool tip text (possibly <code>null</code>). * * @since 1.0.3 */ public String getToolTipText() { return this.toolTipText; } /** * Sets the tool tip text. * * @param text the text (<code>null</code> permitted). * * @since 1.0.3 */ public void setToolTipText(String text) { this.toolTipText = text; } /** * Returns the URL text. * * @return The URL text (possibly <code>null</code>). * * @since 1.0.3 */ public String getURLText() { return this.urlText; } /** * Sets the URL text. * * @param text the text (<code>null</code> permitted). * * @since 1.0.3 */ public void setURLText(String text) { this.urlText = text; } /** * Draws the block within the specified area. * * @param g2 the graphics device. * @param area the area. * @param params passed on to blocks within the container * (<code>null</code> permitted). * * @return An instance of {@link EntityBlockResult}, or <code>null</code>. */ @Override public Object draw(Graphics2D g2, Rectangle2D area, Object params) { // draw the block without collecting entities super.draw(g2, area, null); EntityBlockParams ebp = null; BlockResult r = new BlockResult(); if (params instanceof EntityBlockParams) { ebp = (EntityBlockParams) params; if (ebp.getGenerateEntities()) { EntityCollection ec = new StandardEntityCollection(); LegendItemEntity entity = new LegendItemEntity( (Shape) area.clone()); entity.setSeriesKey(this.seriesKey); entity.setDataset(this.dataset); entity.setToolTipText(getToolTipText()); entity.setURLText(getURLText()); ec.add(entity); r.setEntityCollection(ec); } } return r; } }
5,958
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
StandardPieToolTipGenerator.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/labels/StandardPieToolTipGenerator.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * -------------------------------- * StandardPieToolTipGenerator.java * -------------------------------- * (C) Copyright 2001-2012, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): Richard Atkinson; * Andreas Schroeder; * * Changes * ------- * 13-Dec-2001 : Version 1 (DG); * 16-Jan-2002 : Completed Javadocs (DG); * 29-Aug-2002 : Changed to format numbers using default locale (RA); * 26-Sep-2002 : Fixed errors reported by Checkstyle (DG); * 30-Oct-2002 : Changed PieToolTipGenerator interface (DG); * 21-Mar-2003 : Implemented Serializable (DG); * 13-Aug-2003 : Implemented Cloneable (DG); * 19-Aug-2003 : Renamed StandardPieToolTipGenerator --> * StandardPieItemLabelGenerator (DG); * 10-Mar-2004 : Modified to use MessageFormat class (DG); * 31-Mar-2004 : Added javadocs for the MessageFormat usage (AS); * 15-Apr-2004 : Split PieItemLabelGenerator interface into * PieSectionLabelGenerator and PieToolTipGenerator (DG); * 25-Nov-2004 : Moved some code into abstract super class (DG); * 29-Jul-2005 : Removed implementation of PieSectionLabelGenerator * interface (DG); * 10-Jul-2007 : Added constructors with locale argument (DG); * 17-Jun-2012 : Removed JCommon dependencies (DG); * */ package org.jfree.chart.labels; import java.io.Serializable; import java.text.NumberFormat; import java.util.Locale; import org.jfree.chart.util.PublicCloneable; import org.jfree.data.general.PieDataset; /** * A standard item label generator for plots that use data from a * {@link PieDataset}. * <p> * For the label format, use {0} where the pie section key should be inserted, * {1} for the absolute section value and {2} for the percent amount of the pie * section, e.g. <code>"{0} = {1} ({2})"</code> will display as * <code>apple = 120 (5%)</code>. */ public class StandardPieToolTipGenerator extends AbstractPieItemLabelGenerator implements PieToolTipGenerator, Cloneable, PublicCloneable, Serializable { /** For serialization. */ private static final long serialVersionUID = 2995304200445733779L; /** The default tooltip format. */ public static final String DEFAULT_TOOLTIP_FORMAT = "{0}: ({1}, {2})"; /** * Creates an item label generator using default number formatters. */ public StandardPieToolTipGenerator() { this(DEFAULT_TOOLTIP_FORMAT); } /** * Creates a pie tool tip generator for the specified locale, using the * default format string. * * @param locale the locale (<code>null</code> not permitted). * * @since 1.0.7 */ public StandardPieToolTipGenerator(Locale locale) { this(DEFAULT_TOOLTIP_FORMAT, locale); } /** * Creates a pie tool tip generator for the default locale. * * @param labelFormat the label format (<code>null</code> not permitted). */ public StandardPieToolTipGenerator(String labelFormat) { this(labelFormat, Locale.getDefault()); } /** * Creates a pie tool tip generator for the specified locale. * * @param labelFormat the label format (<code>null</code> not permitted). * @param locale the locale (<code>null</code> not permitted). * * @since 1.0.7 */ public StandardPieToolTipGenerator(String labelFormat, Locale locale) { this(labelFormat, NumberFormat.getNumberInstance(locale), NumberFormat.getPercentInstance(locale)); } /** * Creates an item label generator using the specified number formatters. * * @param labelFormat the label format string (<code>null</code> not * permitted). * @param numberFormat the format object for the values (<code>null</code> * not permitted). * @param percentFormat the format object for the percentages * (<code>null</code> not permitted). */ public StandardPieToolTipGenerator(String labelFormat, NumberFormat numberFormat, NumberFormat percentFormat) { super(labelFormat, numberFormat, percentFormat); } /** * Generates a tool tip text item for one section in a pie chart. * * @param dataset the dataset (<code>null</code> not permitted). * @param key the section key (<code>null</code> not permitted). * * @return The tool tip text (possibly <code>null</code>). */ @Override public String generateToolTip(PieDataset dataset, Comparable key) { return generateSectionLabel(dataset, key); } /** * Returns an independent copy of the generator. * * @return A clone. * * @throws CloneNotSupportedException should not happen. */ @Override public Object clone() throws CloneNotSupportedException { return super.clone(); } }
6,187
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
StandardCategoryToolTipGenerator.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/labels/StandardCategoryToolTipGenerator.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ------------------------------------- * StandardCategoryToolTipGenerator.java * ------------------------------------- * (C) Copyright 2004-2008, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 11-May-2004 : Version 1 (DG); * ------------- JFREECHART 1.0.x --------------------------------------------- * 03-May-2006 : Added equals() method to fix bug 1481087 (DG); * */ package org.jfree.chart.labels; import java.io.Serializable; import java.text.DateFormat; import java.text.NumberFormat; import org.jfree.data.category.CategoryDataset; /** * A standard tool tip generator that can be used with a * {@link org.jfree.chart.renderer.category.CategoryItemRenderer}. */ public class StandardCategoryToolTipGenerator extends AbstractCategoryItemLabelGenerator implements CategoryToolTipGenerator, Serializable { /** For serialization. */ private static final long serialVersionUID = -6768806592218710764L; /** The default format string. */ public static final String DEFAULT_TOOL_TIP_FORMAT_STRING = "({0}, {1}) = {2}"; /** * Creates a new generator with a default number formatter. */ public StandardCategoryToolTipGenerator() { super(DEFAULT_TOOL_TIP_FORMAT_STRING, NumberFormat.getInstance()); } /** * Creates a new generator with the specified number formatter. * * @param labelFormat the label format string (<code>null</code> not * permitted). * @param formatter the number formatter (<code>null</code> not permitted). */ public StandardCategoryToolTipGenerator(String labelFormat, NumberFormat formatter) { super(labelFormat, formatter); } /** * Creates a new generator with the specified date formatter. * * @param labelFormat the label format string (<code>null</code> not * permitted). * @param formatter the date formatter (<code>null</code> not permitted). */ public StandardCategoryToolTipGenerator(String labelFormat, DateFormat formatter) { super(labelFormat, formatter); } /** * Generates the tool tip text for an item in a dataset. Note: in the * current dataset implementation, each row is a series, and each column * contains values for a particular category. * * @param dataset the dataset (<code>null</code> not permitted). * @param row the row index (zero-based). * @param column the column index (zero-based). * * @return The tooltip text (possibly <code>null</code>). */ @Override public String generateToolTip(CategoryDataset dataset, int row, int column) { return generateLabelString(dataset, row, column); } /** * Tests this generator for equality with an arbitrary object. * * @param obj the object (<code>null</code> permitted). * * @return A boolean. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof StandardCategoryToolTipGenerator)) { return false; } return super.equals(obj); } }
4,643
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
StandardXYSeriesLabelGenerator.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/labels/StandardXYSeriesLabelGenerator.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ----------------------------------- * StandardXYSeriesLabelGenerator.java * ----------------------------------- * (C) Copyright 2004-2012, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 16-Nov-2004 : Version 1 (DG); * ------------- JFREECHART 1.0.x --------------------------------------------- * 24-Nov-2006 : Fixed equals() method and updated API docs (DG); * 31-Mar-2008 : Added hashCode() method to appease FindBugs (DG); * 17-Jun-2012 : Removed JCommon dependencies (DG); * */ package org.jfree.chart.labels; import java.io.Serializable; import java.text.MessageFormat; import org.jfree.chart.HashUtilities; import org.jfree.chart.util.PublicCloneable; import org.jfree.data.xy.XYDataset; /** * A standard series label generator for plots that use data from * an {@link org.jfree.data.xy.XYDataset}. * <br><br> * This class implements <code>PublicCloneable</code> by mistake but we retain * this for the sake of backward compatibility. */ public class StandardXYSeriesLabelGenerator implements XYSeriesLabelGenerator, Cloneable, PublicCloneable, Serializable { /** For serialization. */ private static final long serialVersionUID = 1916017081848400024L; /** The default item label format. */ public static final String DEFAULT_LABEL_FORMAT = "{0}"; /** The format pattern. */ private String formatPattern; /** * Creates a default series label generator (uses * {@link #DEFAULT_LABEL_FORMAT}). */ public StandardXYSeriesLabelGenerator() { this(DEFAULT_LABEL_FORMAT); } /** * Creates a new series label generator. * * @param format the format pattern (<code>null</code> not permitted). */ public StandardXYSeriesLabelGenerator(String format) { if (format == null) { throw new IllegalArgumentException("Null 'format' argument."); } this.formatPattern = format; } /** * Generates a label for the specified series. This label will be * used for the chart legend. * * @param dataset the dataset (<code>null</code> not permitted). * @param series the series. * * @return A series label. */ @Override public String generateLabel(XYDataset dataset, int series) { if (dataset == null) { throw new IllegalArgumentException("Null 'dataset' argument."); } String label = MessageFormat.format( this.formatPattern, createItemArray(dataset, series) ); return label; } /** * Creates the array of items that can be passed to the * {@link MessageFormat} class for creating labels. * * @param dataset the dataset (<code>null</code> not permitted). * @param series the series (zero-based index). * * @return The items (never <code>null</code>). */ protected Object[] createItemArray(XYDataset dataset, int series) { Object[] result = new Object[1]; result[0] = dataset.getSeriesKey(series).toString(); return result; } /** * Returns an independent copy of the generator. This is unnecessary, * because instances are immutable anyway, but we retain this * behaviour for backwards compatibility. * * @return A clone. * * @throws CloneNotSupportedException if cloning is not supported. */ @Override public Object clone() throws CloneNotSupportedException { return super.clone(); } /** * Tests this object for equality with an arbitrary object. * * @param obj the other object (<code>null</code> permitted). * * @return A boolean. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof StandardXYSeriesLabelGenerator)) { return false; } StandardXYSeriesLabelGenerator that = (StandardXYSeriesLabelGenerator) obj; if (!this.formatPattern.equals(that.formatPattern)) { return false; } return true; } /** * Returns a hash code for this instance. * * @return A hash code. */ @Override public int hashCode() { int result = 127; result = HashUtilities.hashCode(result, this.formatPattern); return result; } }
5,715
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
package-info.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/labels/package-info.java
/** * Generators and other classes used for the display of item labels and tooltips. */ package org.jfree.chart.labels;
122
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
CustomXYToolTipGenerator.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/labels/CustomXYToolTipGenerator.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ------------------------------- * CustomXYItemLabelGenerator.java * ------------------------------- * (C) Copyright 2002-2012, by Richard Atkinson and Contributors. * * Original Author: Richard Atkinson; * Contributor(s): David Gilbert (for Object Refinery Limited); * * Changes: * -------- * 05-Aug-2002 : Version 1, contributed by Richard Atkinson (RA); * 26-Sep-2002 : Fixed errors reported by Checkstyle (DG); * 21-Mar-2003 : Implemented Serializable (DG); * 13-Aug-2003 : Implemented Cloneable (DG); * 17-Nov-2003 : Implemented PublicCloneable (DG); * 25-Feb-2004 : Renamed XYToolTipGenerator --> XYItemLabelGenerator (DG); * 02-Feb-2007 : Removed author tags all over JFreeChart sources (DG); * 17-Jun-2012 : Removed JCommon dependencies (DG); * */ package org.jfree.chart.labels; import java.io.Serializable; import java.util.List; import org.jfree.chart.util.PublicCloneable; import org.jfree.data.xy.XYDataset; /** * A tool tip generator that stores custom tooltips. The dataset passed into * the generateToolTip method is ignored. */ public class CustomXYToolTipGenerator implements XYToolTipGenerator, Cloneable, PublicCloneable, Serializable { /** For serialization. */ private static final long serialVersionUID = 8636030004670141362L; /** Storage for the tooltip lists. */ private List<List<String>> toolTipSeries = new java.util.ArrayList<List<String>>(); /** * Default constructor. */ public CustomXYToolTipGenerator() { super(); } /** * Returns the number of tool tip lists stored by the renderer. * * @return The list count. */ public int getListCount() { return this.toolTipSeries.size(); } /** * Returns the number of tool tips in a given list. * * @param list the list index (zero based). * * @return The tooltip count. */ public int getToolTipCount(int list) { int result = 0; List<String> tooltips = this.toolTipSeries.get(list); if (tooltips != null) { result = tooltips.size(); } return result; } /** * Returns the tool tip text for an item. * * @param series the series index. * @param item the item index. * * @return The tool tip text. */ public String getToolTipText(int series, int item) { String result = null; if (series < getListCount()) { List<String> tooltips = this.toolTipSeries.get(series); if (tooltips != null) { if (item < tooltips.size()) { result = tooltips.get(item); } } } return result; } /** * Adds a list of tooltips for a series. * * @param toolTips the list of tool tips. */ public void addToolTipSeries(List<String> toolTips) { this.toolTipSeries.add(toolTips); } /** * Generates a tool tip text item for a particular item within a series. * * @param data the dataset (ignored in this implementation). * @param series the series (zero-based index). * @param item the item (zero-based index). * * @return The tooltip text. */ @Override public String generateToolTip(XYDataset data, int series, int item) { return getToolTipText(series, item); } /** * Returns an independent copy of the generator. * * @return A clone. * * @throws CloneNotSupportedException if cloning is not supported. */ @Override public Object clone() throws CloneNotSupportedException { CustomXYToolTipGenerator clone = (CustomXYToolTipGenerator) super.clone(); if (this.toolTipSeries != null) { clone.toolTipSeries = new java.util.ArrayList<List<String>>(this.toolTipSeries); } return clone; } /** * Tests if this object is equal to another. * * @param obj the other object. * * @return A boolean. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (obj instanceof CustomXYToolTipGenerator) { CustomXYToolTipGenerator generator = (CustomXYToolTipGenerator) obj; boolean result = true; for (int series = 0; series < getListCount(); series++) { for (int item = 0; item < getToolTipCount(series); item++) { String t1 = getToolTipText(series, item); String t2 = generator.getToolTipText(series, item); if (t1 != null) { result = result && t1.equals(t2); } else { result = result && (t2 == null); } } } return result; } return false; } }
6,191
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
StandardCategoryItemLabelGenerator.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/labels/StandardCategoryItemLabelGenerator.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * --------------------------------------- * StandardCategoryItemLabelGenerator.java * --------------------------------------- * (C) Copyright 2004-2012, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 11-May-2004 : Version 1 (DG); * 20-Apr-2005 : Renamed StandardCategoryLabelGenerator * --> StandardCategoryItemLabelGenerator (DG); * ------------- JFREECHART 1.0.0 --------------------------------------------- * 03-May-2005 : Added equals() implementation, to fix bug 1481087 (DG); * 17-Jun-2012 : Removed JCommon dependencies (DG); * */ package org.jfree.chart.labels; import java.io.Serializable; import java.text.DateFormat; import java.text.NumberFormat; import org.jfree.chart.util.PublicCloneable; import org.jfree.data.category.CategoryDataset; /** * A standard label generator that can be used with a * {@link org.jfree.chart.renderer.category.CategoryItemRenderer}. */ public class StandardCategoryItemLabelGenerator extends AbstractCategoryItemLabelGenerator implements CategoryItemLabelGenerator, Cloneable, PublicCloneable, Serializable { /** For serialization. */ private static final long serialVersionUID = 3499701401211412882L; /** The default format string. */ public static final String DEFAULT_LABEL_FORMAT_STRING = "{2}"; /** * Creates a new generator with a default number formatter. */ public StandardCategoryItemLabelGenerator() { super(DEFAULT_LABEL_FORMAT_STRING, NumberFormat.getInstance()); } /** * Creates a new generator with the specified number formatter. * * @param labelFormat the label format string (<code>null</code> not * permitted). * @param formatter the number formatter (<code>null</code> not permitted). */ public StandardCategoryItemLabelGenerator(String labelFormat, NumberFormat formatter) { super(labelFormat, formatter); } /** * Creates a new generator with the specified number formatter. * * @param labelFormat the label format string (<code>null</code> not * permitted). * @param formatter the number formatter (<code>null</code> not permitted). * @param percentFormatter the percent formatter (<code>null</code> not * permitted). * * @since 1.0.2 */ public StandardCategoryItemLabelGenerator(String labelFormat, NumberFormat formatter, NumberFormat percentFormatter) { super(labelFormat, formatter, percentFormatter); } /** * Creates a new generator with the specified date formatter. * * @param labelFormat the label format string (<code>null</code> not * permitted). * @param formatter the date formatter (<code>null</code> not permitted). */ public StandardCategoryItemLabelGenerator(String labelFormat, DateFormat formatter) { super(labelFormat, formatter); } /** * Generates the label for an item in a dataset. Note: in the current * dataset implementation, each row is a series, and each column contains * values for a particular category. * * @param dataset the dataset (<code>null</code> not permitted). * @param row the row index (zero-based). * @param column the column index (zero-based). * * @return The label (possibly <code>null</code>). */ @Override public String generateLabel(CategoryDataset dataset, int row, int column) { return generateLabelString(dataset, row, column); } /** * Tests this generator for equality with an arbitrary object. * * @param obj the object (<code>null</code> permitted). * * @return <code>true</code> if this generator is equal to * <code>obj</code>, and <code>false</code> otherwise. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof StandardCategoryItemLabelGenerator)) { return false; } return super.equals(obj); } }
5,548
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
MultipleXYSeriesLabelGenerator.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/labels/MultipleXYSeriesLabelGenerator.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ----------------------------------- * MultipleXYSeriesLabelGenerator.java * ----------------------------------- * (C) Copyright 2004-2012, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 19-Nov-2004 : Version 1 (DG); * 18-Apr-2005 : Use StringBuffer (DG); * 20-Feb-2007 : Fixed for equals() and cloning() (DG); * 31-Mar-2008 : Added hashCode() method to appease FindBugs (DG); * 17-Jun-2012 : Removed JCommon dependencies (DG); * */ package org.jfree.chart.labels; import java.io.Serializable; import java.text.MessageFormat; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.jfree.chart.HashUtilities; import org.jfree.chart.util.PublicCloneable; import org.jfree.data.xy.XYDataset; /** * A series label generator for plots that use data from * an {@link org.jfree.data.xy.XYDataset}. */ public class MultipleXYSeriesLabelGenerator implements XYSeriesLabelGenerator, Cloneable, PublicCloneable, Serializable { /** For serialization. */ private static final long serialVersionUID = 138976236941898560L; /** The default item label format. */ public static final String DEFAULT_LABEL_FORMAT = "{0}"; /** The format pattern for the initial part of the label. */ private String formatPattern; /** The format pattern for additional labels. */ private String additionalFormatPattern; /** Storage for the additional series labels. */ private Map<Integer, List<String>> seriesLabelLists; /** * Creates an item label generator using default number formatters. */ public MultipleXYSeriesLabelGenerator() { this(DEFAULT_LABEL_FORMAT); } /** * Creates a new series label generator. * * @param format the format pattern (<code>null</code> not permitted). */ public MultipleXYSeriesLabelGenerator(String format) { if (format == null) { throw new IllegalArgumentException("Null 'format' argument."); } this.formatPattern = format; this.additionalFormatPattern = "\n{0}"; this.seriesLabelLists = new HashMap<Integer, List<String>>(); } /** * Adds an extra label for the specified series. * * @param series the series index. * @param label the label. */ public void addSeriesLabel(int series, String label) { Integer key = series; List<String> labelList = this.seriesLabelLists.get(key); if (labelList == null) { labelList = new java.util.ArrayList<String>(); this.seriesLabelLists.put(key, labelList); } labelList.add(label); } /** * Clears the extra labels for the specified series. * * @param series the series index. */ public void clearSeriesLabels(int series) { Integer key = series; this.seriesLabelLists.put(key, null); } /** * Generates a label for the specified series. This label will be * used for the chart legend. * * @param dataset the dataset (<code>null</code> not permitted). * @param series the series. * * @return A series label. */ @Override public String generateLabel(XYDataset dataset, int series) { if (dataset == null) { throw new IllegalArgumentException("Null 'dataset' argument."); } StringBuilder label = new StringBuilder(); label.append(MessageFormat.format(this.formatPattern, createItemArray(dataset, series))); Integer key = series; List<String> extraLabels = this.seriesLabelLists.get(key); if (extraLabels != null) { for (String extraLabel : extraLabels) { String labelAddition = MessageFormat.format( this.additionalFormatPattern, extraLabel); label.append(labelAddition); } } return label.toString(); } /** * Creates the array of items that can be passed to the * {@link MessageFormat} class for creating labels. * * @param dataset the dataset (<code>null</code> not permitted). * @param series the series (zero-based index). * * @return The items (never <code>null</code>). */ protected Object[] createItemArray(XYDataset dataset, int series) { Object[] result = new Object[1]; result[0] = dataset.getSeriesKey(series).toString(); return result; } /** * Returns an independent copy of the generator. * * @return A clone. * * @throws CloneNotSupportedException if cloning is not supported. */ @Override public Object clone() throws CloneNotSupportedException { MultipleXYSeriesLabelGenerator clone = (MultipleXYSeriesLabelGenerator) super.clone(); clone.seriesLabelLists = new HashMap<Integer, List<String>>(); Set<Integer> keys = this.seriesLabelLists.keySet(); for (Integer key : keys) { List<String> entry = this.seriesLabelLists.get(key); List<String> toAdd = entry; if (entry instanceof PublicCloneable) { PublicCloneable pc = (PublicCloneable) entry; toAdd = (List<String>) pc.clone(); } clone.seriesLabelLists.put(key, toAdd); } return clone; } /** * Tests this object for equality with an arbitrary object. * * @param obj the other object (<code>null</code> permitted). * * @return A boolean. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof MultipleXYSeriesLabelGenerator)) { return false; } MultipleXYSeriesLabelGenerator that = (MultipleXYSeriesLabelGenerator) obj; if (!this.formatPattern.equals(that.formatPattern)) { return false; } if (!this.additionalFormatPattern.equals( that.additionalFormatPattern)) { return false; } if (!this.seriesLabelLists.equals(that.seriesLabelLists)) { return false; } return true; } /** * Returns a hash code for this instance. * * @return A hash code. */ @Override public int hashCode() { int result = 127; result = HashUtilities.hashCode(result, this.formatPattern); result = HashUtilities.hashCode(result, this.additionalFormatPattern); result = HashUtilities.hashCode(result, this.seriesLabelLists); return result; } }
8,003
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
StandardXYToolTipGenerator.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/labels/StandardXYToolTipGenerator.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ------------------------------- * StandardXYToolTipGenerator.java * ------------------------------- * (C) Copyright 2004-2012, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 12-May-2004 : Version 1 (DG); * ------------- JFREECHART 1.0.x --------------------------------------------- * 25-Jan-2007 : Added new constructor - see bug 1624067 (DG); * 17-Jun-2012 : Removed JCommon dependencies (DG); * */ package org.jfree.chart.labels; import java.io.Serializable; import java.text.DateFormat; import java.text.NumberFormat; import org.jfree.chart.util.PublicCloneable; import org.jfree.data.xy.XYDataset; /** * A standard tool tip generator for use with an * {@link org.jfree.chart.renderer.xy.XYItemRenderer}. */ public class StandardXYToolTipGenerator extends AbstractXYItemLabelGenerator implements XYToolTipGenerator, Cloneable, PublicCloneable, Serializable { /** For serialization. */ private static final long serialVersionUID = -3564164459039540784L; /** The default tooltip format. */ public static final String DEFAULT_TOOL_TIP_FORMAT = "{0}: ({1}, {2})"; /** * Returns a tool tip generator that formats the x-values as dates and the * y-values as numbers. * * @return A tool tip generator (never <code>null</code>). */ public static StandardXYToolTipGenerator getTimeSeriesInstance() { return new StandardXYToolTipGenerator(DEFAULT_TOOL_TIP_FORMAT, DateFormat.getInstance(), NumberFormat.getInstance()); } /** * Creates a tool tip generator using default number formatters. */ public StandardXYToolTipGenerator() { this(DEFAULT_TOOL_TIP_FORMAT, NumberFormat.getNumberInstance(), NumberFormat.getNumberInstance()); } /** * Creates a tool tip generator using the specified number formatters. * * @param formatString the item label format string (<code>null</code> not * permitted). * @param xFormat the format object for the x values (<code>null</code> * not permitted). * @param yFormat the format object for the y values (<code>null</code> * not permitted). */ public StandardXYToolTipGenerator(String formatString, NumberFormat xFormat, NumberFormat yFormat) { super(formatString, xFormat, yFormat); } /** * Creates a tool tip generator using the specified number formatters. * * @param formatString the label format string (<code>null</code> not * permitted). * @param xFormat the format object for the x values (<code>null</code> * not permitted). * @param yFormat the format object for the y values (<code>null</code> * not permitted). */ public StandardXYToolTipGenerator(String formatString, DateFormat xFormat, NumberFormat yFormat) { super(formatString, xFormat, yFormat); } /** * Creates a tool tip generator using the specified formatters (a * number formatter for the x-values and a date formatter for the * y-values). * * @param formatString the item label format string (<code>null</code> * not permitted). * @param xFormat the format object for the x values (<code>null</code> * permitted). * @param yFormat the format object for the y values (<code>null</code> * not permitted). * * @since 1.0.4 */ public StandardXYToolTipGenerator(String formatString, NumberFormat xFormat, DateFormat yFormat) { super(formatString, xFormat, yFormat); } /** * Creates a tool tip generator using the specified date formatters. * * @param formatString the label format string (<code>null</code> not * permitted). * @param xFormat the format object for the x values (<code>null</code> * not permitted). * @param yFormat the format object for the y values (<code>null</code> * not permitted). */ public StandardXYToolTipGenerator(String formatString, DateFormat xFormat, DateFormat yFormat) { super(formatString, xFormat, yFormat); } /** * Generates the tool tip text for an item in a dataset. * * @param dataset the dataset (<code>null</code> not permitted). * @param series the series index (zero-based). * @param item the item index (zero-based). * * @return The tooltip text (possibly <code>null</code>). */ @Override public String generateToolTip(XYDataset dataset, int series, int item) { return generateLabelString(dataset, series, item); } /** * Tests this object for equality with an arbitrary object. * * @param obj the other object (<code>null</code> permitted). * * @return A boolean. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof StandardXYToolTipGenerator)) { return false; } return super.equals(obj); } /** * Returns an independent copy of the generator. * * @return A clone. * * @throws CloneNotSupportedException if cloning is not supported. */ @Override public Object clone() throws CloneNotSupportedException { return super.clone(); } }
6,914
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
CategorySeriesLabelGenerator.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/labels/CategorySeriesLabelGenerator.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * --------------------------------- * CategorySeriesLabelGenerator.java * --------------------------------- * (C) Copyright 2005-2008, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 20-Apr-2005 : Version 1 (DG); * ------------- JFREECHART 1.0.x --------------------------------------------- * 24-Nov-2006 : Updated API docs (DG); * */ package org.jfree.chart.labels; import org.jfree.data.category.CategoryDataset; /** * A generator that creates labels for the series in a {@link CategoryDataset}. * <P> * Classes that implement this interface should be either (a) immutable, or * (b) cloneable via the <code>PublicCloneable</code> interface (defined in * the JCommon class library). This provides a mechanism for the referring * renderer to clone the generator if necessary. */ public interface CategorySeriesLabelGenerator { /** * Generates a label for the specified series. * * @param dataset the dataset (<code>null</code> not permitted). * @param series the series index. * * @return A series label. */ public String generateLabel(CategoryDataset dataset, int series); }
2,468
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
HighLowItemLabelGenerator.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/labels/HighLowItemLabelGenerator.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ------------------------------ * HighLowItemLabelGenerator.java * ------------------------------ * (C) Copyright 2001-2012, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): David Basten; * * Changes * ------- * 13-Dec-2001 : Version 1 (DG); * 16-Jan-2002 : Completed Javadocs (DG); * 23-Apr-2002 : Added date to the tooltip string (DG); * 26-Sep-2002 : Fixed errors reported by Checkstyle (DG); * 21-Mar-2003 : Implemented Serializable (DG); * 13-Aug-2003 : Implemented Cloneable (DG); * 17-Nov-2003 : Implemented PublicCloneable (DG); * 25-Feb-2004 : Renamed XYToolTipGenerator --> XYItemLabelGenerator (DG); * 25-May-2004 : Added number formatter (see patch 890496) (DG); * 15-Jul-2004 : Switched getX() with getXValue() and getY() with * getYValue() (DG); * 20-Apr-2005 : Renamed XYLabelGenerator --> XYItemLabelGenerator (DG); * 31-Mar-2008 : Added hashCode() method to appease FindBugs (DG); * 17-Jun-2012 : Removed JCommon dependencies (DG); * */ package org.jfree.chart.labels; import java.io.Serializable; import java.text.DateFormat; import java.text.NumberFormat; import java.util.Date; import org.jfree.chart.HashUtilities; import org.jfree.chart.util.PublicCloneable; import org.jfree.data.xy.OHLCDataset; import org.jfree.data.xy.XYDataset; /** * A standard item label generator for plots that use data from a * {@link OHLCDataset}. */ public class HighLowItemLabelGenerator implements XYItemLabelGenerator, XYToolTipGenerator, Cloneable, PublicCloneable, Serializable { /** For serialization. */ private static final long serialVersionUID = 5617111754832211830L; /** The date formatter. */ private DateFormat dateFormatter; /** The number formatter. */ private NumberFormat numberFormatter; /** * Creates an item label generator using the default date and number * formats. */ public HighLowItemLabelGenerator() { this(DateFormat.getInstance(), NumberFormat.getInstance()); } /** * Creates a tool tip generator using the supplied date formatter. * * @param dateFormatter the date formatter (<code>null</code> not * permitted). * @param numberFormatter the number formatter (<code>null</code> not * permitted). */ public HighLowItemLabelGenerator(DateFormat dateFormatter, NumberFormat numberFormatter) { if (dateFormatter == null) { throw new IllegalArgumentException( "Null 'dateFormatter' argument."); } if (numberFormatter == null) { throw new IllegalArgumentException( "Null 'numberFormatter' argument."); } this.dateFormatter = dateFormatter; this.numberFormatter = numberFormatter; } /** * Generates a tooltip text item for a particular item within a series. * * @param dataset the dataset. * @param series the series (zero-based index). * @param item the item (zero-based index). * * @return The tooltip text. */ @Override public String generateToolTip(XYDataset dataset, int series, int item) { String result = null; if (dataset instanceof OHLCDataset) { OHLCDataset d = (OHLCDataset) dataset; Number high = d.getHigh(series, item); Number low = d.getLow(series, item); Number open = d.getOpen(series, item); Number close = d.getClose(series, item); Number x = d.getX(series, item); result = d.getSeriesKey(series).toString(); if (x != null) { Date date = new Date(x.longValue()); result = result + "--> Date=" + this.dateFormatter.format(date); if (high != null) { result = result + " High=" + this.numberFormatter.format(high.doubleValue()); } if (low != null) { result = result + " Low=" + this.numberFormatter.format(low.doubleValue()); } if (open != null) { result = result + " Open=" + this.numberFormatter.format(open.doubleValue()); } if (close != null) { result = result + " Close=" + this.numberFormatter.format(close.doubleValue()); } } } return result; } /** * Generates a label for the specified item. The label is typically a * formatted version of the data value, but any text can be used. * * @param dataset the dataset (<code>null</code> not permitted). * @param series the series index (zero-based). * @param category the category index (zero-based). * * @return The label (possibly <code>null</code>). */ @Override public String generateLabel(XYDataset dataset, int series, int category) { return null; //TODO: implement this method properly } /** * Returns an independent copy of the generator. * * @return A clone. * * @throws CloneNotSupportedException if cloning is not supported. */ @Override public Object clone() throws CloneNotSupportedException { HighLowItemLabelGenerator clone = (HighLowItemLabelGenerator) super.clone(); if (this.dateFormatter != null) { clone.dateFormatter = (DateFormat) this.dateFormatter.clone(); } if (this.numberFormatter != null) { clone.numberFormatter = (NumberFormat) this.numberFormatter.clone(); } return clone; } /** * Tests if this object is equal to another. * * @param obj the other object. * * @return A boolean. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof HighLowItemLabelGenerator)) { return false; } HighLowItemLabelGenerator generator = (HighLowItemLabelGenerator) obj; if (!this.dateFormatter.equals(generator.dateFormatter)) { return false; } if (!this.numberFormatter.equals(generator.numberFormatter)) { return false; } return true; } /** * Returns a hash code for this instance. * * @return A hash code. */ @Override public int hashCode() { int result = 127; result = HashUtilities.hashCode(result, this.dateFormatter); result = HashUtilities.hashCode(result, this.numberFormatter); return result; } }
8,130
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
BubbleXYItemLabelGenerator.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/labels/BubbleXYItemLabelGenerator.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ------------------------------- * BubbleXYItemLabelGenerator.java * ------------------------------- * (C) Copyright 2005-2012, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 13-Dec-2005 : Version 1, based on StandardXYZToolTipGenerator (DG); * 26-Jan-2006 : Renamed StandardXYZItemLabelGenerator * --> BubbleXYItemLabelGenerator (DG); * 23-Nov-2007 : Implemented hashCode() (DG); * 23-Apr-2008 : Implemented PublicCloneable (DG); * 17-Jun-2012 : Removed JCommon dependencies (DG); * */ package org.jfree.chart.labels; import java.io.Serializable; import java.text.DateFormat; import java.text.MessageFormat; import java.text.NumberFormat; import org.jfree.chart.HashUtilities; import org.jfree.chart.util.ObjectUtilities; import org.jfree.chart.util.PublicCloneable; import org.jfree.chart.renderer.xy.XYBubbleRenderer; import org.jfree.data.xy.XYDataset; import org.jfree.data.xy.XYZDataset; /** * An item label generator defined for use with the {@link XYBubbleRenderer} * class, or any other class that uses an {@link XYZDataset}. * * @since 1.0.1 */ public class BubbleXYItemLabelGenerator extends AbstractXYItemLabelGenerator implements XYItemLabelGenerator, PublicCloneable, Serializable { /** For serialization. */ static final long serialVersionUID = -8458568928021240922L; /** The default item label format. */ public static final String DEFAULT_FORMAT_STRING = "{3}"; /** * A number formatter for the z value - if this is <code>null</code>, then * zDateFormat must be non-null. */ private NumberFormat zFormat; /** * A date formatter for the z-value - if this is null, then zFormat must be * non-null. */ private DateFormat zDateFormat; /** * Creates a new tool tip generator using default number formatters for the * x, y and z-values. */ public BubbleXYItemLabelGenerator() { this(DEFAULT_FORMAT_STRING, NumberFormat.getNumberInstance(), NumberFormat.getNumberInstance(), NumberFormat.getNumberInstance()); } /** * Constructs a new tool tip generator using the specified number * formatters. * * @param formatString the format string. * @param xFormat the format object for the x values (<code>null</code> * not permitted). * @param yFormat the format object for the y values (<code>null</code> * not permitted). * @param zFormat the format object for the z values (<code>null</code> * not permitted). */ public BubbleXYItemLabelGenerator(String formatString, NumberFormat xFormat, NumberFormat yFormat, NumberFormat zFormat) { super(formatString, xFormat, yFormat); if (zFormat == null) { throw new IllegalArgumentException("Null 'zFormat' argument."); } this.zFormat = zFormat; } /** * Constructs a new item label generator using the specified date * formatters. * * @param formatString the format string. * @param xFormat the format object for the x values (<code>null</code> * not permitted). * @param yFormat the format object for the y values (<code>null</code> * not permitted). * @param zFormat the format object for the z values (<code>null</code> * not permitted). */ public BubbleXYItemLabelGenerator(String formatString, DateFormat xFormat, DateFormat yFormat, DateFormat zFormat) { super(formatString, xFormat, yFormat); if (zFormat == null) { throw new IllegalArgumentException("Null 'zFormat' argument."); } this.zDateFormat = zFormat; } /** * Returns the number formatter for the z-values. * * @return The number formatter (possibly <code>null</code>). */ public NumberFormat getZFormat() { return this.zFormat; } /** * Returns the date formatter for the z-values. * * @return The date formatter (possibly <code>null</code>). */ public DateFormat getZDateFormat() { return this.zDateFormat; } /** * Generates an item label for a particular item within a series. * * @param dataset the dataset (<code>null</code> not permitted). * @param series the series index (zero-based). * @param item the item index (zero-based). * * @return The item label (possibly <code>null</code>). */ @Override public String generateLabel(XYDataset dataset, int series, int item) { return generateLabelString(dataset, series, item); } /** * Generates a label string for an item in the dataset. * * @param dataset the dataset (<code>null</code> not permitted). * @param series the series (zero-based index). * @param item the item (zero-based index). * * @return The label (possibly <code>null</code>). */ @Override public String generateLabelString(XYDataset dataset, int series, int item) { String result = null; Object[] items = null; if (dataset instanceof XYZDataset) { items = createItemArray((XYZDataset) dataset, series, item); } else { items = createItemArray(dataset, series, item); } result = MessageFormat.format(getFormatString(), items); return result; } /** * Creates the array of items that can be passed to the * {@link MessageFormat} class for creating labels. * * @param dataset the dataset (<code>null</code> not permitted). * @param series the series (zero-based index). * @param item the item (zero-based index). * * @return The items (never <code>null</code>). */ protected Object[] createItemArray(XYZDataset dataset, int series, int item) { Object[] result = new Object[4]; result[0] = dataset.getSeriesKey(series).toString(); Number x = dataset.getX(series, item); DateFormat xf = getXDateFormat(); if (xf != null) { result[1] = xf.format(x); } else { result[1] = getXFormat().format(x); } Number y = dataset.getY(series, item); DateFormat yf = getYDateFormat(); if (yf != null) { result[2] = yf.format(y); } else { result[2] = getYFormat().format(y); } Number z = dataset.getZ(series, item); if (this.zDateFormat != null) { result[3] = this.zDateFormat.format(z); } else { result[3] = this.zFormat.format(z); } return result; } /** * Tests this object for equality with an arbitrary object. * * @param obj the other object (<code>null</code> permitted). * * @return A boolean. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof BubbleXYItemLabelGenerator)) { return false; } if (!super.equals(obj)) { return false; } BubbleXYItemLabelGenerator that = (BubbleXYItemLabelGenerator) obj; if (!ObjectUtilities.equal(this.zFormat, that.zFormat)) { return false; } if (!ObjectUtilities.equal(this.zDateFormat, that.zDateFormat)) { return false; } return true; } /** * Returns a hash code for this instance. * * @return A hash code. */ @Override public int hashCode() { int h = super.hashCode(); h = HashUtilities.hashCode(h, this.zFormat); h = HashUtilities.hashCode(h, this.zDateFormat); return h; } }
9,246
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
XYToolTipGenerator.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/labels/XYToolTipGenerator.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ----------------------- * XYToolTipGenerator.java * ----------------------- * (C) Copyright 2001-2008, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 15-Apr-2004 : Extracted the generateToolTip() method from the * XYItemLabelGenerator interface and put it into this new * interface (DG); * */ package org.jfree.chart.labels; import org.jfree.data.xy.XYDataset; /** * Interface for a tooltip generator for plots that use data from an * {@link XYDataset}. */ public interface XYToolTipGenerator { /** * Generates the tooltip text for the specified item. * * @param dataset the dataset (<code>null</code> not permitted). * @param series the series index (zero-based). * @param item the item index (zero-based). * * @return The tooltip text (possibly <code>null</code>). */ public String generateToolTip(XYDataset dataset, int series, int item); }
2,267
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
CategoryToolTipGenerator.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/labels/CategoryToolTipGenerator.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ----------------------------- * CategoryToolTipGenerator.java * ----------------------------- * (C) Copyright 2001-2008, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 15-Apr-2004 : Separated tool tip method from CategoryItemLabelGenerator * interface (DG); * */ package org.jfree.chart.labels; import org.jfree.data.category.CategoryDataset; /** * A <i>category tool tip generator</i> is an object that can be assigned to a * {@link org.jfree.chart.renderer.category.CategoryItemRenderer} and that * assumes responsibility for creating text items to be used as tooltips for the * items in a {@link org.jfree.chart.plot.CategoryPlot}. * <p> * To assist with cloning charts, classes that implement this interface should * also implement the <code>org.jfree.util.PublicCloneable</code> interface (in * JCommon). */ public interface CategoryToolTipGenerator { /** * Generates the tool tip text for an item in a dataset. Note: in the * current dataset implementation, each row is a series, and each column * contains values for a particular category. * * @param dataset the dataset (<code>null</code> not permitted). * @param row the row index (zero-based). * @param column the column index (zero-based). * * @return The tooltip text (possibly <code>null</code>). */ public String generateToolTip(CategoryDataset dataset, int row, int column); }
2,767
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
IntervalCategoryToolTipGenerator.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/labels/IntervalCategoryToolTipGenerator.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ------------------------------------- * IntervalCategoryToolTipGenerator.java * ------------------------------------- * (C) Copyright 2004-2008, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 11-May-2004 : Version 1, split from IntervalCategoryItemLabelGenerator (DG); * 08-Oct-2008 : Override equals() method (DG); * */ package org.jfree.chart.labels; import java.text.DateFormat; import java.text.NumberFormat; import org.jfree.data.category.CategoryDataset; import org.jfree.data.category.IntervalCategoryDataset; /** * A tooltip generator for plots that use data from an * {@link IntervalCategoryDataset}. */ public class IntervalCategoryToolTipGenerator extends StandardCategoryToolTipGenerator { /** For serialization. */ private static final long serialVersionUID = -3853824986520333437L; /** The default format string. */ public static final String DEFAULT_TOOL_TIP_FORMAT_STRING = "({0}, {1}) = {3} - {4}"; /** * Creates a new generator with a default number formatter. */ public IntervalCategoryToolTipGenerator() { super(DEFAULT_TOOL_TIP_FORMAT_STRING, NumberFormat.getInstance()); } /** * Creates a new generator with the specified number formatter. * * @param labelFormat the label format string (<code>null</code> not * permitted). * @param formatter the number formatter (<code>null</code> not permitted). */ public IntervalCategoryToolTipGenerator(String labelFormat, NumberFormat formatter) { super(labelFormat, formatter); } /** * Creates a new generator with the specified date formatter. * * @param labelFormat the label format string (<code>null</code> not * permitted). * @param formatter the date formatter (<code>null</code> not permitted). */ public IntervalCategoryToolTipGenerator(String labelFormat, DateFormat formatter) { super(labelFormat, formatter); } /** * Creates the array of items that can be passed to the * <code>MessageFormat</code> class for creating labels. * * @param dataset the dataset (<code>null</code> not permitted). * @param row the row index (zero-based). * @param column the column index (zero-based). * * @return The items (never <code>null</code>). */ @Override protected Object[] createItemArray(CategoryDataset dataset, int row, int column) { Object[] result = new Object[5]; result[0] = dataset.getRowKey(row).toString(); result[1] = dataset.getColumnKey(column).toString(); Number value = dataset.getValue(row, column); if (getNumberFormat() != null) { result[2] = getNumberFormat().format(value); } else if (getDateFormat() != null) { result[2] = getDateFormat().format(value); } if (dataset instanceof IntervalCategoryDataset) { IntervalCategoryDataset icd = (IntervalCategoryDataset) dataset; Number start = icd.getStartValue(row, column); Number end = icd.getEndValue(row, column); if (getNumberFormat() != null) { result[3] = getNumberFormat().format(start); result[4] = getNumberFormat().format(end); } else if (getDateFormat() != null) { result[3] = getDateFormat().format(start); result[4] = getDateFormat().format(end); } } return result; } /** * Tests this tool tip generator for equality with an arbitrary * object. * * @param obj the object (<code>null</code> permitted). * * @return A boolean. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof IntervalCategoryToolTipGenerator)) { return false; } // no fields to test return super.equals(obj); } }
5,508
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
XYSeriesLabelGenerator.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/labels/XYSeriesLabelGenerator.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * --------------------------- * XYSeriesLabelGenerator.java * --------------------------- * (C) Copyright 2004-2008, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 16-Nov-2004 : Version 1 (DG); * ------------- JFREECHART 1.0.x --------------------------------------------- * 24-Nov-2006 : Updated API docs (DG); * */ package org.jfree.chart.labels; import org.jfree.data.xy.XYDataset; /** * A generator that creates labels for the series in an {@link XYDataset}. * <P> * Classes that implement this interface should be either (a) immutable, or * (b) cloneable via the <code>PublicCloneable</code> interface (defined in * the JCommon class library). This provides a mechanism for the referring * renderer to clone the generator if necessary. */ public interface XYSeriesLabelGenerator { /** * Generates a label for the specified series. This label will be * used for the chart legend. * * @param dataset the dataset (<code>null</code> not permitted). * @param series the series. * * @return A series label. */ public String generateLabel(XYDataset dataset, int series); }
2,469
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
AbstractCategoryItemLabelGenerator.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/labels/AbstractCategoryItemLabelGenerator.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * --------------------------------------- * AbstractCategoryItemLabelGenerator.java * --------------------------------------- * (C) Copyright 2005-2012, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 11-May-2004 : Version 1, distilled from StandardCategoryLabelGenerator (DG); * 31-Jan-2005 : Added methods to return row and column labels (DG); * 17-May-2005 : Added percentage to item array (DG); * ------------- JFREECHART 1.0.x --------------------------------------------- * 03-May-2006 : Added new constructor (DG); * 23-Nov-2007 : Implemented hashCode() (DG); * 16-Jun-2012 : Removed JCommon dependencies (DG); * */ package org.jfree.chart.labels; import java.io.Serializable; import java.text.DateFormat; import java.text.MessageFormat; import java.text.NumberFormat; import org.jfree.chart.HashUtilities; import org.jfree.chart.util.ObjectUtilities; import org.jfree.chart.util.PublicCloneable; import org.jfree.data.DataUtilities; import org.jfree.data.category.CategoryDataset; /** * A base class that can be used to create a label or tooltip generator that * can be assigned to a * {@link org.jfree.chart.renderer.category.CategoryItemRenderer}. */ public abstract class AbstractCategoryItemLabelGenerator implements PublicCloneable, Cloneable, Serializable { /** For serialization. */ private static final long serialVersionUID = -7108591260223293197L; /** * The label format string used by a <code>MessageFormat</code> object to * combine the standard items: {0} = series name, {1} = category, * {2} = value, {3} = value as a percentage of the column total. */ private String labelFormat; /** The string used to represent a null value. */ private String nullValueString; /** * A number formatter used to preformat the value before it is passed to * the MessageFormat object. */ private NumberFormat numberFormat; /** * A date formatter used to preformat the value before it is passed to the * MessageFormat object. */ private DateFormat dateFormat; /** * A number formatter used to preformat the percentage value before it is * passed to the MessageFormat object. */ private NumberFormat percentFormat; /** * Creates a label generator with the specified number formatter. * * @param labelFormat the label format string (<code>null</code> not * permitted). * @param formatter the number formatter (<code>null</code> not permitted). */ protected AbstractCategoryItemLabelGenerator(String labelFormat, NumberFormat formatter) { this(labelFormat, formatter, NumberFormat.getPercentInstance()); } /** * Creates a label generator with the specified number formatter. * * @param labelFormat the label format string (<code>null</code> not * permitted). * @param formatter the number formatter (<code>null</code> not permitted). * @param percentFormatter the percent formatter (<code>null</code> not * permitted). * * @since 1.0.2 */ protected AbstractCategoryItemLabelGenerator(String labelFormat, NumberFormat formatter, NumberFormat percentFormatter) { if (labelFormat == null) { throw new IllegalArgumentException("Null 'labelFormat' argument."); } if (formatter == null) { throw new IllegalArgumentException("Null 'formatter' argument."); } if (percentFormatter == null) { throw new IllegalArgumentException( "Null 'percentFormatter' argument."); } this.labelFormat = labelFormat; this.numberFormat = formatter; this.percentFormat = percentFormatter; this.dateFormat = null; this.nullValueString = "-"; } /** * Creates a label generator with the specified date formatter. * * @param labelFormat the label format string (<code>null</code> not * permitted). * @param formatter the date formatter (<code>null</code> not permitted). */ protected AbstractCategoryItemLabelGenerator(String labelFormat, DateFormat formatter) { if (labelFormat == null) { throw new IllegalArgumentException("Null 'labelFormat' argument."); } if (formatter == null) { throw new IllegalArgumentException("Null 'formatter' argument."); } this.labelFormat = labelFormat; this.numberFormat = null; this.percentFormat = NumberFormat.getPercentInstance(); this.dateFormat = formatter; this.nullValueString = "-"; } /** * Generates a label for the specified row. * * @param dataset the dataset (<code>null</code> not permitted). * @param row the row index (zero-based). * * @return The label. */ public String generateRowLabel(CategoryDataset dataset, int row) { return dataset.getRowKey(row).toString(); } /** * Generates a label for the specified row. * * @param dataset the dataset (<code>null</code> not permitted). * @param column the column index (zero-based). * * @return The label. */ public String generateColumnLabel(CategoryDataset dataset, int column) { return dataset.getColumnKey(column).toString(); } /** * Returns the label format string. * * @return The label format string (never <code>null</code>). */ public String getLabelFormat() { return this.labelFormat; } /** * Returns the number formatter. * * @return The number formatter (possibly <code>null</code>). */ public NumberFormat getNumberFormat() { return this.numberFormat; } /** * Returns the date formatter. * * @return The date formatter (possibly <code>null</code>). */ public DateFormat getDateFormat() { return this.dateFormat; } /** * Generates a for the specified item. * * @param dataset the dataset (<code>null</code> not permitted). * @param row the row index (zero-based). * @param column the column index (zero-based). * * @return The label (possibly <code>null</code>). */ protected String generateLabelString(CategoryDataset dataset, int row, int column) { if (dataset == null) { throw new IllegalArgumentException("Null 'dataset' argument."); } String result = null; Object[] items = createItemArray(dataset, row, column); result = MessageFormat.format(this.labelFormat, items); return result; } /** * Creates the array of items that can be passed to the * {@link MessageFormat} class for creating labels. * * @param dataset the dataset (<code>null</code> not permitted). * @param row the row index (zero-based). * @param column the column index (zero-based). * * @return The items (never <code>null</code>). */ protected Object[] createItemArray(CategoryDataset dataset, int row, int column) { Object[] result = new Object[4]; result[0] = dataset.getRowKey(row).toString(); result[1] = dataset.getColumnKey(column).toString(); Number value = dataset.getValue(row, column); if (value != null) { if (this.numberFormat != null) { result[2] = this.numberFormat.format(value); } else if (this.dateFormat != null) { result[2] = this.dateFormat.format(value); } } else { result[2] = this.nullValueString; } if (value != null) { double total = DataUtilities.calculateColumnTotal(dataset, column); double percent = value.doubleValue() / total; result[3] = this.percentFormat.format(percent); } return result; } /** * Tests this object for equality with an arbitrary object. * * @param obj the other object (<code>null</code> permitted). * * @return A boolean. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof AbstractCategoryItemLabelGenerator)) { return false; } AbstractCategoryItemLabelGenerator that = (AbstractCategoryItemLabelGenerator) obj; if (!this.labelFormat.equals(that.labelFormat)) { return false; } if (!ObjectUtilities.equal(this.dateFormat, that.dateFormat)) { return false; } if (!ObjectUtilities.equal(this.numberFormat, that.numberFormat)) { return false; } return true; } /** * Returns a hash code for this instance. * * @return A hash code. */ @Override public int hashCode() { int result = 127; result = HashUtilities.hashCode(result, this.labelFormat); result = HashUtilities.hashCode(result, this.nullValueString); result = HashUtilities.hashCode(result, this.dateFormat); result = HashUtilities.hashCode(result, this.numberFormat); result = HashUtilities.hashCode(result, this.percentFormat); return result; } /** * Returns an independent copy of the generator. * * @return A clone. * * @throws CloneNotSupportedException should not happen. */ @Override public Object clone() throws CloneNotSupportedException { AbstractCategoryItemLabelGenerator clone = (AbstractCategoryItemLabelGenerator) super.clone(); if (this.numberFormat != null) { clone.numberFormat = (NumberFormat) this.numberFormat.clone(); } if (this.dateFormat != null) { clone.dateFormat = (DateFormat) this.dateFormat.clone(); } return clone; } }
11,562
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
StandardCategorySeriesLabelGenerator.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/labels/StandardCategorySeriesLabelGenerator.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ----------------------------------------- * StandardCategorySeriesLabelGenerator.java * ----------------------------------------- * (C) Copyright 2005-2012, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 20-Apr-2005 : Version 1 (DG); * ------------- JFREECHART 1.0.x --------------------------------------------- * 03-May-2006 : Fixed equals() method (bug 1481102) (DG); * 31-Mar-2008 : Added hashCode() method to appease FindBugs (DG); * 17-Jun-2012 : Removed JCommon dependencies (DG); * */ package org.jfree.chart.labels; import java.io.Serializable; import java.text.MessageFormat; import org.jfree.chart.HashUtilities; import org.jfree.chart.util.PublicCloneable; import org.jfree.data.category.CategoryDataset; /** * A standard series label generator for plots that use data from * a {@link org.jfree.data.category.CategoryDataset}. */ public class StandardCategorySeriesLabelGenerator implements CategorySeriesLabelGenerator, Cloneable, PublicCloneable, Serializable { /** For serialization. */ private static final long serialVersionUID = 4630760091523940820L; /** The default item label format. */ public static final String DEFAULT_LABEL_FORMAT = "{0}"; /** The format pattern. */ private String formatPattern; /** * Creates a default series label generator (uses * {@link #DEFAULT_LABEL_FORMAT}). */ public StandardCategorySeriesLabelGenerator() { this(DEFAULT_LABEL_FORMAT); } /** * Creates a new series label generator. * * @param format the format pattern (<code>null</code> not permitted). */ public StandardCategorySeriesLabelGenerator(String format) { if (format == null) { throw new IllegalArgumentException("Null 'format' argument."); } this.formatPattern = format; } /** * Generates a label for the specified series. * * @param dataset the dataset (<code>null</code> not permitted). * @param series the series. * * @return A series label. */ @Override public String generateLabel(CategoryDataset dataset, int series) { if (dataset == null) { throw new IllegalArgumentException("Null 'dataset' argument."); } String label = MessageFormat.format(this.formatPattern, createItemArray(dataset, series)); return label; } /** * Creates the array of items that can be passed to the * {@link MessageFormat} class for creating labels. * * @param dataset the dataset (<code>null</code> not permitted). * @param series the series (zero-based index). * * @return The items (never <code>null</code>). */ protected Object[] createItemArray(CategoryDataset dataset, int series) { Object[] result = new Object[1]; result[0] = dataset.getRowKey(series).toString(); return result; } /** * Returns an independent copy of the generator. * * @return A clone. * * @throws CloneNotSupportedException if cloning is not supported. */ @Override public Object clone() throws CloneNotSupportedException { return super.clone(); } /** * Tests this object for equality with an arbitrary object. * * @param obj the other object (<code>null</code> permitted). * * @return A boolean. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof StandardCategorySeriesLabelGenerator)) { return false; } StandardCategorySeriesLabelGenerator that = (StandardCategorySeriesLabelGenerator) obj; if (!this.formatPattern.equals(that.formatPattern)) { return false; } return true; } /** * Returns a hash code for this instance. * * @return A hash code. */ @Override public int hashCode() { int result = 127; result = HashUtilities.hashCode(result, this.formatPattern); return result; } }
5,463
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
XYItemLabelGenerator.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/labels/XYItemLabelGenerator.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ------------------------- * XYItemLabelGenerator.java * ------------------------- * (C) Copyright 2001-2008, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 13-Dec-2001 : Version 1 (DG); * 16-Jan-2002 : Completed Javadocs (DG); * 13-Jun-2002 : Correction to Javadoc comments (DG); * 26-Sep-2002 : Fixed errors reported by Checkstyle (DG); * 25-Feb-2004 : Renamed XYToolTipGenerator --> XYItemLabelGenerator (DG); * 15-Apr-2004 : Moved the generateToolTip() method to a separate * interface (DG); * 11-May-2004 : Renamed XYItemLabelGenerator --> XYLabelGenerator (DG); * 20-Apr-2005 : Reverted name change of 11-May-2004 (DG); * */ package org.jfree.chart.labels; import org.jfree.data.xy.XYDataset; /** * Interface for a label generator for plots that use data from an * {@link XYDataset}. */ public interface XYItemLabelGenerator { /** * Generates a label for the specified item. The label is typically a * formatted version of the data value, but any text can be used. * * @param dataset the dataset (<code>null</code> not permitted). * @param series the series index (zero-based). * @param item the item index (zero-based). * * @return The label (possibly <code>null</code>). */ public String generateLabel(XYDataset dataset, int series, int item); }
2,673
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
StandardPieSectionLabelGenerator.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/labels/StandardPieSectionLabelGenerator.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ------------------------------------- * StandardPieSectionLabelGenerator.java * ------------------------------------- * (C) Copyright 2004-2012, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 09-Nov-2004 : Version 1, derived from StandardPieItemLabelGenerator (DG); * 29-Jul-2005 : Removed unused generateToolTip() method (DG); * ------------- JFREECHART 1.0.x --------------------------------------------- * 03-May-2006 : Modified DEFAULT_SECTION_LABEL_FORMAT (DG); * 10-Jan-2007 : Include attributedLabels in equals() test (DG); * 10-Jul-2007 : Added constructors with locale parameter (DG); * 23-Apr-2008 : Implemented PublicCloneable (DG); * 16-Jun-2012 : Removed JCommon dependencies (DG); * */ package org.jfree.chart.labels; import java.awt.Font; import java.awt.Paint; import java.awt.font.TextAttribute; import java.io.Serializable; import java.text.AttributedString; import java.text.NumberFormat; import java.util.Locale; import org.jfree.chart.util.ObjectList; import org.jfree.chart.util.PublicCloneable; import org.jfree.data.general.PieDataset; /** * A standard item label generator for plots that use data from a * {@link PieDataset}. * <p> * For the label format, use {0} where the pie section key should be inserted, * {1} for the absolute section value and {2} for the percent amount of the pie * section, e.g. <code>"{0} = {1} ({2})"</code> will display as * <code>apple = 120 (5%)</code>. */ public class StandardPieSectionLabelGenerator extends AbstractPieItemLabelGenerator implements PieSectionLabelGenerator, Cloneable, PublicCloneable, Serializable { /** For serialization. */ private static final long serialVersionUID = 3064190563760203668L; /** The default section label format. */ public static final String DEFAULT_SECTION_LABEL_FORMAT = "{0}"; /** * An optional list of attributed labels (instances of AttributedString). */ private ObjectList<AttributedString> attributedLabels; /** * Creates a new section label generator using * {@link #DEFAULT_SECTION_LABEL_FORMAT} as the label format string, and * platform default number and percentage formatters. */ public StandardPieSectionLabelGenerator() { this(DEFAULT_SECTION_LABEL_FORMAT, NumberFormat.getNumberInstance(), NumberFormat.getPercentInstance()); } /** * Creates a new instance for the specified locale. * * @param locale the local (<code>null</code> not permitted). * * @since 1.0.7 */ public StandardPieSectionLabelGenerator(Locale locale) { this(DEFAULT_SECTION_LABEL_FORMAT, locale); } /** * Creates a new section label generator using the specified label format * string, and platform default number and percentage formatters. * * @param labelFormat the label format (<code>null</code> not permitted). */ public StandardPieSectionLabelGenerator(String labelFormat) { this(labelFormat, NumberFormat.getNumberInstance(), NumberFormat.getPercentInstance()); } /** * Creates a new instance for the specified locale. * * @param labelFormat the label format (<code>null</code> not permitted). * @param locale the local (<code>null</code> not permitted). * * @since 1.0.7 */ public StandardPieSectionLabelGenerator(String labelFormat, Locale locale) { this(labelFormat, NumberFormat.getNumberInstance(locale), NumberFormat.getPercentInstance(locale)); } /** * Creates an item label generator using the specified number formatters. * * @param labelFormat the label format string (<code>null</code> not * permitted). * @param numberFormat the format object for the values (<code>null</code> * not permitted). * @param percentFormat the format object for the percentages * (<code>null</code> not permitted). */ public StandardPieSectionLabelGenerator(String labelFormat, NumberFormat numberFormat, NumberFormat percentFormat) { super(labelFormat, numberFormat, percentFormat); this.attributedLabels = new ObjectList<AttributedString>(); } /** * Returns the attributed label for a section, or <code>null</code> if none * is defined. * * @param section the section index. * * @return The attributed label. */ public AttributedString getAttributedLabel(int section) { return this.attributedLabels.get(section); } /** * Sets the attributed label for a section. * * @param section the section index. * @param label the label (<code>null</code> permitted). */ public void setAttributedLabel(int section, AttributedString label) { this.attributedLabels.set(section, label); } /** * Generates a label for a pie section. * * @param dataset the dataset (<code>null</code> not permitted). * @param key the section key (<code>null</code> not permitted). * * @return The label (possibly <code>null</code>). */ @Override public String generateSectionLabel(PieDataset dataset, Comparable key) { return super.generateSectionLabel(dataset, key); } /** * Generates an attributed label for the specified series, or * <code>null</code> if no attributed label is available (in which case, * the string returned by * {@link #generateSectionLabel(PieDataset, Comparable)} will * provide the fallback). Only certain attributes are recognised by the * code that ultimately displays the labels: * <ul> * <li>{@link TextAttribute#FONT}: will set the font;</li> * <li>{@link TextAttribute#POSTURE}: a value of * {@link TextAttribute#POSTURE_OBLIQUE} will add {@link Font#ITALIC} to * the current font;</li> * <li>{@link TextAttribute#WEIGHT}: a value of * {@link TextAttribute#WEIGHT_BOLD} will add {@link Font#BOLD} to the * current font;</li> * <li>{@link TextAttribute#FOREGROUND}: this will set the {@link Paint} * for the current</li> * <li>{@link TextAttribute#SUPERSCRIPT}: the values * {@link TextAttribute#SUPERSCRIPT_SUB} and * {@link TextAttribute#SUPERSCRIPT_SUPER} are recognised.</li> * </ul> * * @param dataset the dataset (<code>null</code> not permitted). * @param key the key. * * @return An attributed label (possibly <code>null</code>). */ @Override public AttributedString generateAttributedSectionLabel(PieDataset dataset, Comparable key) { return getAttributedLabel(dataset.getIndex(key)); } /** * Tests the generator for equality with an arbitrary object. * * @param obj the object to test against (<code>null</code> permitted). * * @return A boolean. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof StandardPieSectionLabelGenerator)) { return false; } StandardPieSectionLabelGenerator that = (StandardPieSectionLabelGenerator) obj; if (!this.attributedLabels.equals(that.attributedLabels)) { return false; } if (!super.equals(obj)) { return false; } return true; } /** * Returns an independent copy of the generator. * * @return A clone. * * @throws CloneNotSupportedException should not happen. */ @Override public Object clone() throws CloneNotSupportedException { return super.clone(); } }
9,215
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
ItemLabelAnchor.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/labels/ItemLabelAnchor.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * -------------------- * ItemLabelAnchor.java * -------------------- * (C) Copyright 2003-2008, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 29-Apr-2003 : Version 1 (DG); * 19-Feb-2004 : Moved to org.jfree.chart.labels package, added readResolve() * method (DG); * 11-Jan-2005 : Removed deprecated code in preparation for the 1.0.0 * release (DG); * */ package org.jfree.chart.labels; /** * An enumeration of the positions that a value label can take, relative to an * item in a {@link org.jfree.chart.plot.CategoryPlot}. */ public enum ItemLabelAnchor { /** CENTER. */ CENTER("ItemLabelAnchor.CENTER"), /** INSIDE1. */ INSIDE1("ItemLabelAnchor.INSIDE1"), /** INSIDE2. */ INSIDE2("ItemLabelAnchor.INSIDE2"), /** INSIDE3. */ INSIDE3("ItemLabelAnchor.INSIDE3"), /** INSIDE4. */ INSIDE4("ItemLabelAnchor.INSIDE4"), /** INSIDE5. */ INSIDE5("ItemLabelAnchor.INSIDE5"), /** INSIDE6. */ INSIDE6("ItemLabelAnchor.INSIDE6"), /** INSIDE7. */ INSIDE7("ItemLabelAnchor.INSIDE7"), /** INSIDE8. */ INSIDE8("ItemLabelAnchor.INSIDE8"), /** INSIDE9. */ INSIDE9("ItemLabelAnchor.INSIDE9"), /** INSIDE10. */ INSIDE10("ItemLabelAnchor.INSIDE10"), /** INSIDE11. */ INSIDE11("ItemLabelAnchor.INSIDE11"), /** INSIDE12. */ INSIDE12("ItemLabelAnchor.INSIDE12"), /** OUTSIDE1. */ OUTSIDE1("ItemLabelAnchor.OUTSIDE1"), /** OUTSIDE2. */ OUTSIDE2("ItemLabelAnchor.OUTSIDE2"), /** OUTSIDE3. */ OUTSIDE3("ItemLabelAnchor.OUTSIDE3"), /** OUTSIDE4. */ OUTSIDE4("ItemLabelAnchor.OUTSIDE4"), /** OUTSIDE5. */ OUTSIDE5("ItemLabelAnchor.OUTSIDE5"), /** OUTSIDE6. */ OUTSIDE6("ItemLabelAnchor.OUTSIDE6"), /** OUTSIDE7. */ OUTSIDE7("ItemLabelAnchor.OUTSIDE7"), /** OUTSIDE8. */ OUTSIDE8("ItemLabelAnchor.OUTSIDE8"), /** OUTSIDE9. */ OUTSIDE9("ItemLabelAnchor.OUTSIDE9"), /** OUTSIDE10. */ OUTSIDE10("ItemLabelAnchor.OUTSIDE10"), /** OUTSIDE11. */ OUTSIDE11("ItemLabelAnchor.OUTSIDE11"), /** OUTSIDE12. */ OUTSIDE12("ItemLabelAnchor.OUTSIDE12"); /** The name. */ private String name; /** * Private constructor. * * @param name the name. */ private ItemLabelAnchor(String name) { this.name = name; } /** * Returns a string representing the object. * * @return The string. */ @Override public String toString() { return this.name; } }
3,886
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
XYZToolTipGenerator.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/labels/XYZToolTipGenerator.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ------------------------ * XYZToolTipGenerator.java * ------------------------ * (C) Copyright 2003-2008, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 03-Feb-2003 : Version 1 (DG); * 25-Feb-2004 : Renamed XYZToolTipGenerator --> XYZItemLabelGenerator (DG); * 11-May-2004 : Reverted to XYZToolTipGenerator (DG); * */ package org.jfree.chart.labels; import org.jfree.data.xy.XYZDataset; /** * Interface for a tooltip generator for plots that use data from an * {@link XYZDataset}. */ public interface XYZToolTipGenerator extends XYToolTipGenerator { /** * Generates a tool tip text item for a particular item within a series. * * @param dataset the dataset (<code>null</code> not permitted). * @param series the series index (zero-based). * @param item the item index (zero-based). * * @return The tooltip text (possibly <code>null</code>). */ public String generateToolTip(XYZDataset dataset, int series, int item); }
2,314
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
SymbolicXYItemLabelGenerator.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/labels/SymbolicXYItemLabelGenerator.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * --------------------------------- * SymbolicXYItemLabelGenerator.java * --------------------------------- * (C) Copyright 2001-2012, by Anthony Boulestreau and Contributors. * * Original Author: Anthony Boulestreau; * Contributor(s): David Gilbert (for Object Refinery Limited); * * Changes * ------- * 29-Mar-2002 : Version 1, contributed by Anthony Boulestreau (DG); * 26-Sep-2002 : Fixed errors reported by Checkstyle (DG); * 23-Mar-2003 : Implemented Serializable (DG); * 13-Aug-2003 : Implemented Cloneable (DG); * 17-Nov-2003 : Implemented PublicCloneable (DG); * 25-Feb-2004 : Renamed XYToolTipGenerator --> XYItemLabelGenerator (DG); * 19-Jan-2005 : Now accesses primitives only from dataset (DG); * 20-Apr-2005 : Renamed XYLabelGenerator --> XYItemLabelGenerator (DG); * 02-Feb-2007 : Removed author tags all over JFreeChart sources (DG); * 31-Mar-2008 : Added hashCode() method to appease FindBugs (DG); * 17-Jun-2012 : Removed JCommon dependencies (DG); * */ package org.jfree.chart.labels; import java.io.Serializable; import org.jfree.chart.util.PublicCloneable; import org.jfree.data.time.RegularTimePeriod; import org.jfree.data.time.TimeSeriesCollection; import org.jfree.data.xy.XYDataset; import org.jfree.data.xy.XisSymbolic; import org.jfree.data.xy.YisSymbolic; /** * A standard item label generator for plots that use data from an * {@link XYDataset}. */ public class SymbolicXYItemLabelGenerator implements XYItemLabelGenerator, XYToolTipGenerator, Cloneable, PublicCloneable, Serializable { /** For serialization. */ private static final long serialVersionUID = 3963400354475494395L; /** * Generates a tool tip text item for a particular item within a series. * * @param data the dataset. * @param series the series number (zero-based index). * @param item the item number (zero-based index). * * @return The tool tip text (possibly <code>null</code>). */ @Override public String generateToolTip(XYDataset data, int series, int item) { String xStr, yStr; if (data instanceof YisSymbolic) { yStr = ((YisSymbolic) data).getYSymbolicValue(series, item); } else { double y = data.getYValue(series, item); yStr = Double.toString(round(y, 2)); } if (data instanceof XisSymbolic) { xStr = ((XisSymbolic) data).getXSymbolicValue(series, item); } else if (data instanceof TimeSeriesCollection) { RegularTimePeriod p = ((TimeSeriesCollection) data).getSeries(series) .getTimePeriod(item); xStr = p.toString(); } else { double x = data.getXValue(series, item); xStr = Double.toString(round(x, 2)); } return "X: " + xStr + ", Y: " + yStr; } /** * Generates a label for the specified item. The label is typically a * formatted version of the data value, but any text can be used. * * @param dataset the dataset (<code>null</code> not permitted). * @param series the series index (zero-based). * @param category the category index (zero-based). * * @return The label (possibly <code>null</code>). */ @Override public String generateLabel(XYDataset dataset, int series, int category) { return null; //TODO: implement this method properly } /** * Round a double value. * * @param value the value. * @param nb the exponent. * * @return The rounded value. */ private static double round(double value, int nb) { if (nb <= 0) { return Math.floor(value + 0.5d); } double p = Math.pow(10, nb); double tempval = Math.floor(value * p + 0.5d); return tempval / p; } /** * Returns an independent copy of the generator. * * @return A clone. * * @throws CloneNotSupportedException if cloning is not supported. */ @Override public Object clone() throws CloneNotSupportedException { return super.clone(); } /** * Tests if this object is equal to another. * * @param obj the other object. * * @return A boolean. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (obj instanceof SymbolicXYItemLabelGenerator) { return true; } return false; } /** * Returns a hash code for this instance. * * @return A hash code. */ @Override public int hashCode() { int result = 127; return result; } }
5,968
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
BoxAndWhiskerXYToolTipGenerator.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/labels/BoxAndWhiskerXYToolTipGenerator.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ------------------------------------ * BoxAndWhiskerXYToolTipGenerator.java * ------------------------------------ * (C) Copyright 2003-2008, by David Browning and Contributors. * * Original Author: David Browning; * Contributor(s): David Gilbert (for Object Refinery Limited); * * Changes * ------- * 05-Aug-2003 : Version 1, contributed by David Browning (DG); * 13-Aug-2003 : Implemented Cloneable (DG); * 28-Aug-2003 : Updated for changes in dataset API (DG); * 25-Feb-2004 : Renamed XYToolTipGenerator --> XYItemLabelGenerator (DG); * 27-Feb-2004 : Renamed BoxAndWhiskerItemLabelGenerator --> * BoxAndWhiskerXYItemLabelGenerator, and modified to use * MessageFormat (DG); * 15-Jul-2004 : Switched getX() with getXValue() and getY() with * getYValue() (DG); * 02-Feb-2007 : Removed author tags all over JFreeChart sources (DG); * */ package org.jfree.chart.labels; import java.io.Serializable; import java.text.DateFormat; import java.text.MessageFormat; import java.text.NumberFormat; import java.util.Date; import org.jfree.data.statistics.BoxAndWhiskerXYDataset; import org.jfree.data.xy.XYDataset; /** * An item label generator for plots that use data from a * {@link BoxAndWhiskerXYDataset}. * <P> * The tooltip text and item label text are composed using a * {@link java.text.MessageFormat} object, that can aggregate some or all of * the following string values into a message. * <table> * <tr><td>0</td><td>Series Name</td></tr> * <tr><td>1</td><td>X (value or date)</td></tr> * <tr><td>2</td><td>Mean</td></tr> * <tr><td>3</td><td>Median</td></tr> * <tr><td>4</td><td>Minimum</td></tr> * <tr><td>5</td><td>Maximum</td></tr> * <tr><td>6</td><td>Quartile 1</td></tr> * <tr><td>7</td><td>Quartile 3</td></tr> * </table> */ public class BoxAndWhiskerXYToolTipGenerator extends StandardXYToolTipGenerator implements XYToolTipGenerator, Cloneable, Serializable { /** For serialization. */ private static final long serialVersionUID = -2648775791161459710L; /** The default tooltip format string. */ public static final String DEFAULT_TOOL_TIP_FORMAT = "X: {1} Mean: {2} Median: {3} Min: {4} Max: {5} Q1: {6} Q3: {7} "; /** * Creates a default item label generator. */ public BoxAndWhiskerXYToolTipGenerator() { super(DEFAULT_TOOL_TIP_FORMAT, NumberFormat.getInstance(), NumberFormat.getInstance()); } /** * Creates a new item label generator. If the date formatter is not * <code>null</code>, the x-values will be formatted as dates. * * @param toolTipFormat the tool tip format string (<code>null</code> not * permitted). * @param numberFormat the number formatter (<code>null</code> not * permitted). * @param dateFormat the date formatter (<code>null</code> permitted). */ public BoxAndWhiskerXYToolTipGenerator(String toolTipFormat, DateFormat dateFormat, NumberFormat numberFormat) { super(toolTipFormat, dateFormat, numberFormat); } /** * Creates the array of items that can be passed to the * {@link MessageFormat} class for creating labels. * * @param dataset the dataset (<code>null</code> not permitted). * @param series the series (zero-based index). * @param item the item (zero-based index). * * @return The items (never <code>null</code>). */ @Override protected Object[] createItemArray(XYDataset dataset, int series, int item) { Object[] result = new Object[8]; result[0] = dataset.getSeriesKey(series).toString(); Number x = dataset.getX(series, item); if (getXDateFormat() != null) { result[1] = getXDateFormat().format(new Date(x.longValue())); } else { result[1] = getXFormat().format(x); } NumberFormat formatter = getYFormat(); if (dataset instanceof BoxAndWhiskerXYDataset) { BoxAndWhiskerXYDataset d = (BoxAndWhiskerXYDataset) dataset; result[2] = formatter.format(d.getMeanValue(series, item)); result[3] = formatter.format(d.getMedianValue(series, item)); result[4] = formatter.format(d.getMinRegularValue(series, item)); result[5] = formatter.format(d.getMaxRegularValue(series, item)); result[6] = formatter.format(d.getQ1Value(series, item)); result[7] = formatter.format(d.getQ3Value(series, item)); } return result; } /** * Tests if this object is equal to another. * * @param obj the other object. * * @return A boolean. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof BoxAndWhiskerXYToolTipGenerator)) { return false; } return super.equals(obj); } }
6,359
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
AbstractPieItemLabelGenerator.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/labels/AbstractPieItemLabelGenerator.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ---------------------------------- * AbstractPieItemLabelGenerator.java * ---------------------------------- * (C) Copyright 2004-2008, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 09-Nov-2004 : Version 1, draws out code from StandardPieItemLabelGenerator * and StandardPieToolTipGenerator (DG); * ------------- JFREECHART 1.0.x --------------------------------------------- * 03-May-2006 : Fixed bug 1480978, a problem in the clone() method (DG); * 23-Nov-2007 : Implemented hashCode() (DG); * */ package org.jfree.chart.labels; import java.io.Serializable; import java.text.MessageFormat; import java.text.NumberFormat; import org.jfree.chart.HashUtilities; import org.jfree.data.general.DatasetUtilities; import org.jfree.data.general.PieDataset; /** * A base class used for generating pie chart item labels. */ public class AbstractPieItemLabelGenerator implements Serializable { /** For serialization. */ private static final long serialVersionUID = 7347703325267846275L; /** The label format string. */ private String labelFormat; /** A number formatter for the value. */ private NumberFormat numberFormat; /** A number formatter for the percentage. */ private NumberFormat percentFormat; /** * Creates an item label generator using the specified number formatters. * * @param labelFormat the label format string (<code>null</code> not * permitted). * @param numberFormat the format object for the values (<code>null</code> * not permitted). * @param percentFormat the format object for the percentages * (<code>null</code> not permitted). */ protected AbstractPieItemLabelGenerator(String labelFormat, NumberFormat numberFormat, NumberFormat percentFormat) { if (labelFormat == null) { throw new IllegalArgumentException("Null 'labelFormat' argument."); } if (numberFormat == null) { throw new IllegalArgumentException("Null 'numberFormat' argument."); } if (percentFormat == null) { throw new IllegalArgumentException( "Null 'percentFormat' argument."); } this.labelFormat = labelFormat; this.numberFormat = numberFormat; this.percentFormat = percentFormat; } /** * Returns the label format string. * * @return The label format string (never <code>null</code>). */ public String getLabelFormat() { return this.labelFormat; } /** * Returns the number formatter. * * @return The formatter (never <code>null</code>). */ public NumberFormat getNumberFormat() { return this.numberFormat; } /** * Returns the percent formatter. * * @return The formatter (never <code>null</code>). */ public NumberFormat getPercentFormat() { return this.percentFormat; } /** * Creates the array of items that can be passed to the * {@link MessageFormat} class for creating labels. The returned array * contains four values: * <ul> * <li>result[0] = the section key converted to a <code>String</code>;</li> * <li>result[1] = the formatted data value;</li> * <li>result[2] = the formatted percentage (of the total);</li> * <li>result[3] = the formatted total value.</li> * </ul> * * @param dataset the dataset (<code>null</code> not permitted). * @param key the key (<code>null</code> not permitted). * * @return The items (never <code>null</code>). */ protected Object[] createItemArray(PieDataset dataset, Comparable key) { Object[] result = new Object[4]; double total = DatasetUtilities.calculatePieDatasetTotal(dataset); result[0] = key.toString(); Number value = dataset.getValue(key); if (value != null) { result[1] = this.numberFormat.format(value); } else { result[1] = "null"; } double percent = 0.0; if (value != null) { double v = value.doubleValue(); if (v > 0.0) { percent = v / total; } } result[2] = this.percentFormat.format(percent); result[3] = this.numberFormat.format(total); return result; } /** * Generates a label for a pie section. * * @param dataset the dataset (<code>null</code> not permitted). * @param key the section key (<code>null</code> not permitted). * * @return The label (possibly <code>null</code>). */ protected String generateSectionLabel(PieDataset dataset, Comparable key) { String result = null; if (dataset != null) { Object[] items = createItemArray(dataset, key); result = MessageFormat.format(this.labelFormat, items); } return result; } /** * Tests the generator for equality with an arbitrary object. * * @param obj the object to test against (<code>null</code> permitted). * * @return A boolean. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof AbstractPieItemLabelGenerator)) { return false; } AbstractPieItemLabelGenerator that = (AbstractPieItemLabelGenerator) obj; if (!this.labelFormat.equals(that.labelFormat)) { return false; } if (!this.numberFormat.equals(that.numberFormat)) { return false; } if (!this.percentFormat.equals(that.percentFormat)) { return false; } return true; } /** * Returns a hash code for this instance. * * @return A hash code. */ @Override public int hashCode() { int result = 127; result = HashUtilities.hashCode(result, this.labelFormat); result = HashUtilities.hashCode(result, this.numberFormat); result = HashUtilities.hashCode(result, this.percentFormat); return result; } /** * Returns an independent copy of the generator. * * @return A clone. * * @throws CloneNotSupportedException should not happen. */ @Override public Object clone() throws CloneNotSupportedException { AbstractPieItemLabelGenerator clone = (AbstractPieItemLabelGenerator) super.clone(); if (this.numberFormat != null) { clone.numberFormat = (NumberFormat) this.numberFormat.clone(); } if (this.percentFormat != null) { clone.percentFormat = (NumberFormat) this.percentFormat.clone(); } return clone; } }
8,284
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
AbstractXYItemLabelGenerator.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/labels/AbstractXYItemLabelGenerator.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * --------------------------------- * AbstractXYItemLabelGenerator.java * --------------------------------- * (C) Copyright 2004-2012, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 27-Feb-2004 : Version 1 (DG); * 12-May-2004 : Moved default tool tip format to * StandardXYToolTipGenerator (DG); * 15-Jul-2004 : Switched getX() with getXValue() and getY() with * getYValue() (DG); * 08-Oct-2004 : Modified createItemArray() method to handle null values (DG); * 10-Jan-2005 : Updated createItemArray() to use x, y primitives if * possible (DG); * ------------- JFREECHART 1.0.x -------------------------------------------- * 26-Jan-2006 : Minor API doc update (DG); * 25-Jan-2007 : Added new constructor and fixed bug in clone() method (DG); * 16-Oct-2007 : Removed redundant code (DG); * 23-Nov-2007 : Implemented hashCode() (DG); * 26-May-2008 : Added accessor methods for nullYString and updated equals() * method (DG); * 16-Jun-2012 : Removed JCommon dependencies (DG); * */ package org.jfree.chart.labels; import java.io.Serializable; import java.text.DateFormat; import java.text.MessageFormat; import java.text.NumberFormat; import java.util.Date; import org.jfree.chart.HashUtilities; import org.jfree.chart.util.ObjectUtilities; import org.jfree.data.xy.XYDataset; /** * A base class for creating item label generators. */ public class AbstractXYItemLabelGenerator implements Cloneable, Serializable { /** For serialization. */ private static final long serialVersionUID = 5869744396278660636L; /** The item label format string. */ private String formatString; /** A number formatter for the x value. */ private NumberFormat xFormat; /** A date formatter for the x value. */ private DateFormat xDateFormat; /** A formatter for the y value. */ private NumberFormat yFormat; /** A date formatter for the y value. */ private DateFormat yDateFormat; /** The string used to represent 'null' for the y-value. */ private String nullYString = "null"; /** * Creates an item label generator using default number formatters. */ protected AbstractXYItemLabelGenerator() { this("{2}", NumberFormat.getNumberInstance(), NumberFormat.getNumberInstance()); } /** * Creates an item label generator using the specified number formatters. * * @param formatString the item label format string (<code>null</code> * not permitted). * @param xFormat the format object for the x values (<code>null</code> * not permitted). * @param yFormat the format object for the y values (<code>null</code> * not permitted). */ protected AbstractXYItemLabelGenerator(String formatString, NumberFormat xFormat, NumberFormat yFormat) { if (formatString == null) { throw new IllegalArgumentException("Null 'formatString' argument."); } if (xFormat == null) { throw new IllegalArgumentException("Null 'xFormat' argument."); } if (yFormat == null) { throw new IllegalArgumentException("Null 'yFormat' argument."); } this.formatString = formatString; this.xFormat = xFormat; this.yFormat = yFormat; } /** * Creates an item label generator using the specified number formatters. * * @param formatString the item label format string (<code>null</code> * not permitted). * @param xFormat the format object for the x values (<code>null</code> * permitted). * @param yFormat the format object for the y values (<code>null</code> * not permitted). */ protected AbstractXYItemLabelGenerator(String formatString, DateFormat xFormat, NumberFormat yFormat) { this(formatString, NumberFormat.getInstance(), yFormat); this.xDateFormat = xFormat; } /** * Creates an item label generator using the specified formatters (a * number formatter for the x-values and a date formatter for the * y-values). * * @param formatString the item label format string (<code>null</code> * not permitted). * @param xFormat the format object for the x values (<code>null</code> * permitted). * @param yFormat the format object for the y values (<code>null</code> * not permitted). * * @since 1.0.4 */ protected AbstractXYItemLabelGenerator(String formatString, NumberFormat xFormat, DateFormat yFormat) { this(formatString, xFormat, NumberFormat.getInstance()); this.yDateFormat = yFormat; } /** * Creates an item label generator using the specified number formatters. * * @param formatString the item label format string (<code>null</code> * not permitted). * @param xFormat the format object for the x values (<code>null</code> * permitted). * @param yFormat the format object for the y values (<code>null</code> * not permitted). */ protected AbstractXYItemLabelGenerator(String formatString, DateFormat xFormat, DateFormat yFormat) { this(formatString, NumberFormat.getInstance(), NumberFormat.getInstance()); this.xDateFormat = xFormat; this.yDateFormat = yFormat; } /** * Returns the format string (this controls the overall structure of the * label). * * @return The format string (never <code>null</code>). */ public String getFormatString() { return this.formatString; } /** * Returns the number formatter for the x-values. * * @return The number formatter (possibly <code>null</code>). */ public NumberFormat getXFormat() { return this.xFormat; } /** * Returns the date formatter for the x-values. * * @return The date formatter (possibly <code>null</code>). */ public DateFormat getXDateFormat() { return this.xDateFormat; } /** * Returns the number formatter for the y-values. * * @return The number formatter (possibly <code>null</code>). */ public NumberFormat getYFormat() { return this.yFormat; } /** * Returns the date formatter for the y-values. * * @return The date formatter (possibly <code>null</code>). */ public DateFormat getYDateFormat() { return this.yDateFormat; } /** * Generates a label string for an item in the dataset. * * @param dataset the dataset (<code>null</code> not permitted). * @param series the series (zero-based index). * @param item the item (zero-based index). * * @return The label (possibly <code>null</code>). */ public String generateLabelString(XYDataset dataset, int series, int item) { Object[] items = createItemArray(dataset, series, item); return MessageFormat.format(this.formatString, items); } /** * Returns the string representing a null value. * * @return The string representing a null value. * * @since 1.0.10 */ public String getNullYString() { return this.nullYString; } /** * Creates the array of items that can be passed to the * {@link MessageFormat} class for creating labels. * * @param dataset the dataset (<code>null</code> not permitted). * @param series the series (zero-based index). * @param item the item (zero-based index). * * @return An array of three items from the dataset formatted as * <code>String</code> objects (never <code>null</code>). */ protected Object[] createItemArray(XYDataset dataset, int series, int item) { Object[] result = new Object[3]; result[0] = dataset.getSeriesKey(series).toString(); double x = dataset.getXValue(series, item); if (this.xDateFormat != null) { result[1] = this.xDateFormat.format(new Date((long) x)); } else { result[1] = this.xFormat.format(x); } double y = dataset.getYValue(series, item); if (Double.isNaN(y) && dataset.getY(series, item) == null) { result[2] = this.nullYString; } else { if (this.yDateFormat != null) { result[2] = this.yDateFormat.format(new Date((long) y)); } else { result[2] = this.yFormat.format(y); } } return result; } /** * Tests this object for equality with an arbitrary object. * * @param obj the other object (<code>null</code> permitted). * * @return A boolean. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof AbstractXYItemLabelGenerator)) { return false; } AbstractXYItemLabelGenerator that = (AbstractXYItemLabelGenerator) obj; if (!this.formatString.equals(that.formatString)) { return false; } if (!ObjectUtilities.equal(this.xFormat, that.xFormat)) { return false; } if (!ObjectUtilities.equal(this.xDateFormat, that.xDateFormat)) { return false; } if (!ObjectUtilities.equal(this.yFormat, that.yFormat)) { return false; } if (!ObjectUtilities.equal(this.yDateFormat, that.yDateFormat)) { return false; } if (!this.nullYString.equals(that.nullYString)) { return false; } return true; } /** * Returns a hash code for this instance. * * @return A hash code. */ @Override public int hashCode() { int result = 127; result = HashUtilities.hashCode(result, this.formatString); result = HashUtilities.hashCode(result, this.xFormat); result = HashUtilities.hashCode(result, this.xDateFormat); result = HashUtilities.hashCode(result, this.yFormat); result = HashUtilities.hashCode(result, this.yDateFormat); return result; } /** * Returns an independent copy of the generator. * * @return A clone. * * @throws CloneNotSupportedException if cloning is not supported. */ @Override public Object clone() throws CloneNotSupportedException { AbstractXYItemLabelGenerator clone = (AbstractXYItemLabelGenerator) super.clone(); if (this.xFormat != null) { clone.xFormat = (NumberFormat) this.xFormat.clone(); } if (this.yFormat != null) { clone.yFormat = (NumberFormat) this.yFormat.clone(); } if (this.xDateFormat != null) { clone.xDateFormat = (DateFormat) this.xDateFormat.clone(); } if (this.yDateFormat != null) { clone.yDateFormat = (DateFormat) this.yDateFormat.clone(); } return clone; } }
12,927
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
CategoryItemLabelGenerator.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/labels/CategoryItemLabelGenerator.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ------------------------------- * CategoryItemLabelGenerator.java * ------------------------------- * (C) Copyright 2001-2008, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 13-Dec-2001 : Version 1 (DG); * 16-Jan-2002 : Completed Javadocs (DG); * 26-Sep-2002 : Fixed errors reported by Checkstyle (DG); * 24-Oct-2002 : Method now specifies category index (DG); * 05-Nov-2002 : Replaced reference to CategoryDataset with TableDataset (DG); * 21-Jan-2003 : TableDataset merged with CategoryDataset (DG); * 10-Apr-2003 : Changed CategoryDataset --> KeyedValues2DDataset (DG); * 01-May-2003 : Added generateValueLabel() method (with a plan to renaming * this interface to reflect its more general use) (DG); * 09-Jun-2003 : Renamed CategoryToolTipGenerator * --> CategoryItemLabelGenerator (DG); * 13-Aug-2003 : Added clone() method (DG); * 12-Feb-2004 : Removed clone() method (DG); * 15-Apr-2004 : Moved generateToolTip() method into CategoryToolTipGenerator * interface (DG); * 11-May-2004 : Renamed CategoryItemLabelGenerator * --> CategoryLabelGenerator (DG); * 31-Jan-2005 : Added generateRowLabel() and generateColumnLabel() * methods (DG); * 20-Apr-2005 : Reverted name change of 11-May-2004 (DG); * */ package org.jfree.chart.labels; import org.jfree.data.category.CategoryDataset; /** * A <i>category item label generator</i> is an object that can be assigned to a * {@link org.jfree.chart.renderer.category.CategoryItemRenderer} and that * assumes responsibility for creating text items to be used as labels for the * items in a {@link org.jfree.chart.plot.CategoryPlot}. * <p> * To assist with cloning charts, classes that implement this interface should * also implement the {@link org.jfree.util.PublicCloneable} interface. */ public interface CategoryItemLabelGenerator { /** * Generates a label for the specified row. * * @param dataset the dataset (<code>null</code> not permitted). * @param row the row index (zero-based). * * @return The label. */ public String generateRowLabel(CategoryDataset dataset, int row); /** * Generates a label for the specified row. * * @param dataset the dataset (<code>null</code> not permitted). * @param column the column index (zero-based). * * @return The label. */ public String generateColumnLabel(CategoryDataset dataset, int column); /** * Generates a label for the specified item. The label is typically a * formatted version of the data value, but any text can be used. * * @param dataset the dataset (<code>null</code> not permitted). * @param row the row index (zero-based). * @param column the column index (zero-based). * * @return The label (possibly <code>null</code>). */ public String generateLabel(CategoryDataset dataset, int row, int column); }
4,295
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
PieToolTipGenerator.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/labels/PieToolTipGenerator.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ------------------------ * PieToolTipGenerator.java * ------------------------ * (C) Copyright 2001-2008, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 15-Apr-2004 : Version 1, split from PieItemLabelGenerator (DG); * */ package org.jfree.chart.labels; import org.jfree.data.general.PieDataset; /** * A tool tip generator that is used by the * {@link org.jfree.chart.plot.PiePlot} class. */ public interface PieToolTipGenerator { /** * Generates a tool tip text item for the specified item in the dataset. * This method can return <code>null</code> to indicate that no tool tip * should be displayed for an item. * * @param dataset the dataset (<code>null</code> not permitted). * @param key the section key (<code>null</code> not permitted). * * @return The tool tip text (possibly <code>null</code>). */ public String generateToolTip(PieDataset dataset, Comparable key); }
2,273
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
BoxAndWhiskerToolTipGenerator.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/labels/BoxAndWhiskerToolTipGenerator.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ------------------------------------ * BoxAndWhiskerToolTipGenerator.java * ------------------------------------ * (C) Copyright 2004-2012, by David Browning and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 02-Jun-2004 : Version 1 (DG); * 23-Mar-2005 : Implemented PublicCloneable (DG); * 17-Jun-2012 : Removed JCommon dependencies (DG); * */ package org.jfree.chart.labels; import java.io.Serializable; import java.text.MessageFormat; import java.text.NumberFormat; import org.jfree.chart.util.PublicCloneable; import org.jfree.data.category.CategoryDataset; import org.jfree.data.statistics.BoxAndWhiskerCategoryDataset; /** * An item label generator for plots that use data from a * {@link BoxAndWhiskerCategoryDataset}. * <P> * The tooltip text and item label text are composed using a * {@link java.text.MessageFormat} object, that can aggregate some or all of * the following string values into a message. * <table> * <tr><td>0</td><td>Series Name</td></tr> * <tr><td>1</td><td>X (value or date)</td></tr> * <tr><td>2</td><td>Mean</td></tr> * <tr><td>3</td><td>Median</td></tr> * <tr><td>4</td><td>Minimum</td></tr> * <tr><td>5</td><td>Maximum</td></tr> * <tr><td>6</td><td>Quartile 1</td></tr> * <tr><td>7</td><td>Quartile 3</td></tr> * </table> */ public class BoxAndWhiskerToolTipGenerator extends StandardCategoryToolTipGenerator implements CategoryToolTipGenerator, Cloneable, PublicCloneable, Serializable { /** For serialization. */ private static final long serialVersionUID = -6076837753823076334L; /** The default tooltip format string. */ public static final String DEFAULT_TOOL_TIP_FORMAT = "X: {1} Mean: {2} Median: {3} Min: {4} Max: {5} Q1: {6} Q3: {7} "; /** * Creates a default tool tip generator. */ public BoxAndWhiskerToolTipGenerator() { super(DEFAULT_TOOL_TIP_FORMAT, NumberFormat.getInstance()); } /** * Creates a tool tip formatter. * * @param format the tool tip format string. * @param formatter the formatter. */ public BoxAndWhiskerToolTipGenerator(String format, NumberFormat formatter) { super(format, formatter); } /** * Creates the array of items that can be passed to the * {@link MessageFormat} class for creating labels. * * @param dataset the dataset (<code>null</code> not permitted). * @param series the series (zero-based index). * @param item the item (zero-based index). * * @return The items (never <code>null</code>). */ @Override protected Object[] createItemArray(CategoryDataset dataset, int series, int item) { Object[] result = new Object[8]; result[0] = dataset.getRowKey(series); Number y = dataset.getValue(series, item); NumberFormat formatter = getNumberFormat(); result[1] = formatter.format(y); if (dataset instanceof BoxAndWhiskerCategoryDataset) { BoxAndWhiskerCategoryDataset d = (BoxAndWhiskerCategoryDataset) dataset; result[2] = formatter.format(d.getMeanValue(series, item)); result[3] = formatter.format(d.getMedianValue(series, item)); result[4] = formatter.format(d.getMinRegularValue(series, item)); result[5] = formatter.format(d.getMaxRegularValue(series, item)); result[6] = formatter.format(d.getQ1Value(series, item)); result[7] = formatter.format(d.getQ3Value(series, item)); } return result; } /** * Tests if this object is equal to another. * * @param obj the other object. * * @return A boolean. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (obj instanceof BoxAndWhiskerToolTipGenerator) { return super.equals(obj); } return false; } }
5,367
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z
IntervalXYItemLabelGenerator.java
/FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/labels/IntervalXYItemLabelGenerator.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * --------------------------------- * IntervalXYItemLabelGenerator.java * --------------------------------- * (C) Copyright 2008-2012, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 26-May-2008 : Version 1 (DG); * 17-Jun-2012 : Removed JCommon dependencies (DG); * */ package org.jfree.chart.labels; import java.io.Serializable; import java.text.DateFormat; import java.text.MessageFormat; import java.text.NumberFormat; import java.util.Date; import org.jfree.chart.util.PublicCloneable; import org.jfree.data.xy.IntervalXYDataset; import org.jfree.data.xy.XYDataset; /** * An item label generator for datasets that implement the * {@link IntervalXYDataset} interface. * * @since 1.0.10 */ public class IntervalXYItemLabelGenerator extends AbstractXYItemLabelGenerator implements XYItemLabelGenerator, Cloneable, PublicCloneable, Serializable { /** The default item label format. */ public static final String DEFAULT_ITEM_LABEL_FORMAT = "{5} - {6}"; /** * Creates an item label generator using default number formatters. */ public IntervalXYItemLabelGenerator() { this(DEFAULT_ITEM_LABEL_FORMAT, NumberFormat.getNumberInstance(), NumberFormat.getNumberInstance()); } /** * Creates an item label generator using the specified number formatters. * * @param formatString the item label format string (<code>null</code> not * permitted). * @param xFormat the format object for the x values (<code>null</code> * not permitted). * @param yFormat the format object for the y values (<code>null</code> * not permitted). */ public IntervalXYItemLabelGenerator(String formatString, NumberFormat xFormat, NumberFormat yFormat) { super(formatString, xFormat, yFormat); } /** * Creates an item label generator using the specified formatters. * * @param formatString the item label format string (<code>null</code> * not permitted). * @param xFormat the format object for the x values (<code>null</code> * not permitted). * @param yFormat the format object for the y values (<code>null</code> * not permitted). */ public IntervalXYItemLabelGenerator(String formatString, DateFormat xFormat, NumberFormat yFormat) { super(formatString, xFormat, yFormat); } /** * Creates an item label generator using the specified formatters (a * number formatter for the x-values and a date formatter for the * y-values). * * @param formatString the item label format string (<code>null</code> * not permitted). * @param xFormat the format object for the x values (<code>null</code> * permitted). * @param yFormat the format object for the y values (<code>null</code> * not permitted). */ public IntervalXYItemLabelGenerator(String formatString, NumberFormat xFormat, DateFormat yFormat) { super(formatString, xFormat, yFormat); } /** * Creates a label generator using the specified date formatters. * * @param formatString the label format string (<code>null</code> not * permitted). * @param xFormat the format object for the x values (<code>null</code> * not permitted). * @param yFormat the format object for the y values (<code>null</code> * not permitted). */ public IntervalXYItemLabelGenerator(String formatString, DateFormat xFormat, DateFormat yFormat) { super(formatString, xFormat, yFormat); } /** * Creates the array of items that can be passed to the * {@link MessageFormat} class for creating labels. * * @param dataset the dataset (<code>null</code> not permitted). * @param series the series (zero-based index). * @param item the item (zero-based index). * * @return An array of seven items from the dataset formatted as * <code>String</code> objects (never <code>null</code>). */ @Override protected Object[] createItemArray(XYDataset dataset, int series, int item) { IntervalXYDataset intervalDataset = null; if (dataset instanceof IntervalXYDataset) { intervalDataset = (IntervalXYDataset) dataset; } Object[] result = new Object[7]; result[0] = dataset.getSeriesKey(series).toString(); double x = dataset.getXValue(series, item); double xs = x; double xe = x; double y = dataset.getYValue(series, item); double ys = y; double ye = y; if (intervalDataset != null) { xs = intervalDataset.getStartXValue(series, item); xe = intervalDataset.getEndXValue(series, item); ys = intervalDataset.getStartYValue(series, item); ye = intervalDataset.getEndYValue(series, item); } DateFormat xdf = getXDateFormat(); if (xdf != null) { result[1] = xdf.format(new Date((long) x)); result[2] = xdf.format(new Date((long) xs)); result[3] = xdf.format(new Date((long) xe)); } else { NumberFormat xnf = getXFormat(); result[1] = xnf.format(x); result[2] = xnf.format(xs); result[3] = xnf.format(xe); } NumberFormat ynf = getYFormat(); DateFormat ydf = getYDateFormat(); if (Double.isNaN(y) && dataset.getY(series, item) == null) { result[4] = getNullYString(); } else { if (ydf != null) { result[4] = ydf.format(new Date((long) y)); } else { result[4] = ynf.format(y); } } if (Double.isNaN(ys) && intervalDataset.getStartY(series, item) == null) { result[5] = getNullYString(); } else { if (ydf != null) { result[5] = ydf.format(new Date((long) ys)); } else { result[5] = ynf.format(ys); } } if (Double.isNaN(ye) && intervalDataset.getEndY(series, item) == null) { result[6] = getNullYString(); } else { if (ydf != null) { result[6] = ydf.format(new Date((long) ye)); } else { result[6] = ynf.format(ye); } } return result; } /** * Generates the item label text for an item in a dataset. * * @param dataset the dataset (<code>null</code> not permitted). * @param series the series index (zero-based). * @param item the item index (zero-based). * * @return The label text (possibly <code>null</code>). */ @Override public String generateLabel(XYDataset dataset, int series, int item) { return generateLabelString(dataset, series, item); } /** * Returns an independent copy of the generator. * * @return A clone. * * @throws CloneNotSupportedException if cloning is not supported. */ @Override public Object clone() throws CloneNotSupportedException { return super.clone(); } /** * Tests this object for equality with an arbitrary object. * * @param obj the other object (<code>null</code> permitted). * * @return A boolean. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof IntervalXYItemLabelGenerator)) { return false; } return super.equals(obj); } }
9,314
Java
.java
akardapolov/ASH-Viewer
156
72
35
2011-05-25T05:22:11Z
2023-12-04T11:03:40Z