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 |
---|---|---|---|---|---|---|---|---|---|---|---|
OHLCItem.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/data/time/ohlc/OHLCItem.java | /* ===========================================================
* JFreeChart : a free chart library for the Java(tm) platform
* ===========================================================
*
* (C) Copyright 2000-2011, 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.]
*
* -------------
* OHLCItem.java
* -------------
* (C) Copyright 2006, 2007, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 04-Dec-2006 : Version 1 (DG);
*
*/
package org.jfree.data.time.ohlc;
import org.jfree.data.ComparableObjectItem;
import org.jfree.data.time.RegularTimePeriod;
/**
* An item representing data in the form (period, open, high, low, close).
*
* @since 1.0.4
*/
public class OHLCItem extends ComparableObjectItem {
/**
* Creates a new instance of <code>OHLCItem</code>.
*
* @param period the time period.
* @param open the open-value.
* @param high the high-value.
* @param low the low-value.
* @param close the close-value.
*/
public OHLCItem(RegularTimePeriod period, double open, double high,
double low, double close) {
super(period, new OHLC(open, high, low, close));
}
/**
* Returns the period.
*
* @return The period (never <code>null</code>).
*/
public RegularTimePeriod getPeriod() {
return (RegularTimePeriod) getComparable();
}
/**
* Returns the y-value.
*
* @return The y-value.
*/
public double getYValue() {
return getCloseValue();
}
/**
* Returns the open value.
*
* @return The open value.
*/
public double getOpenValue() {
OHLC ohlc = (OHLC) getObject();
if (ohlc != null) {
return ohlc.getOpen();
}
else {
return Double.NaN;
}
}
/**
* Returns the high value.
*
* @return The high value.
*/
public double getHighValue() {
OHLC ohlc = (OHLC) getObject();
if (ohlc != null) {
return ohlc.getHigh();
}
else {
return Double.NaN;
}
}
/**
* Returns the low value.
*
* @return The low value.
*/
public double getLowValue() {
OHLC ohlc = (OHLC) getObject();
if (ohlc != null) {
return ohlc.getLow();
}
else {
return Double.NaN;
}
}
/**
* Returns the close value.
*
* @return The close value.
*/
public double getCloseValue() {
OHLC ohlc = (OHLC) getObject();
if (ohlc != null) {
return ohlc.getClose();
}
else {
return Double.NaN;
}
}
}
| 3,752 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
PieDatasetHandler.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/data/xml/PieDatasetHandler.java | /* ===========================================================
* JFreeChart : a free chart library for the Java(tm) platform
* ===========================================================
*
* (C) Copyright 2000-2011, 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.]
*
* ----------------------
* PieDatasetHandler.java
* ----------------------
* (C) Copyright 2003-2008, by Object Refinery Limited and Contributors.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 23-Jan-2003 : Version 1 (DG);
*
*/
package org.jfree.data.xml;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.data.general.PieDataset;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
/**
* A SAX handler for reading a {@link PieDataset} from an XML file.
*/
public class PieDatasetHandler extends RootHandler implements DatasetTags {
/** The pie dataset under construction. */
private DefaultPieDataset dataset;
/**
* Default constructor.
*/
public PieDatasetHandler() {
this.dataset = null;
}
/**
* Returns the dataset.
*
* @return The dataset.
*/
public PieDataset getDataset() {
return this.dataset;
}
/**
* Adds an item to the dataset under construction.
*
* @param key the key.
* @param value the value.
*/
public void addItem(Comparable key, Number value) {
this.dataset.setValue(key, value);
}
/**
* Starts an element.
*
* @param namespaceURI the namespace.
* @param localName the element name.
* @param qName the element name.
* @param atts the element attributes.
*
* @throws SAXException for errors.
*/
@Override
public void startElement(String namespaceURI,
String localName,
String qName,
Attributes atts) throws SAXException {
DefaultHandler current = getCurrentHandler();
if (current != this) {
current.startElement(namespaceURI, localName, qName, atts);
}
else if (qName.equals(PIEDATASET_TAG)) {
this.dataset = new DefaultPieDataset();
}
else if (qName.equals(ITEM_TAG)) {
ItemHandler subhandler = new ItemHandler(this, this);
getSubHandlers().push(subhandler);
subhandler.startElement(namespaceURI, localName, qName, atts);
}
}
/**
* The end of an element.
*
* @param namespaceURI the namespace.
* @param localName the element name.
* @param qName the element name.
*
* @throws SAXException for errors.
*/
@Override
public void endElement(String namespaceURI,
String localName,
String qName) throws SAXException {
DefaultHandler current = getCurrentHandler();
if (current != this) {
current.endElement(namespaceURI, localName, qName);
}
}
}
| 4,090 | 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/data/xml/package-info.java | /**
* Support for reading datasets from XML files.
*/
package org.jfree.data.xml;
| 84 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
CategoryDatasetHandler.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/data/xml/CategoryDatasetHandler.java | /* ===========================================================
* JFreeChart : a free chart library for the Java(tm) platform
* ===========================================================
*
* (C) Copyright 2000-2011, 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.]
*
* ---------------------------
* CategoryDatasetHandler.java
* ---------------------------
* (C) Copyright 2003-2008, by Object Refinery Limited and Contributors.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 23-Jan-2003 : Version 1 (DG);
*
*/
package org.jfree.data.xml;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.category.DefaultCategoryDataset;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
/**
* A SAX handler for reading a {@link CategoryDataset} from an XML file.
*/
public class CategoryDatasetHandler extends RootHandler implements DatasetTags {
/** The dataset under construction. */
private DefaultCategoryDataset dataset;
/**
* Creates a new handler.
*/
public CategoryDatasetHandler() {
this.dataset = null;
}
/**
* Returns the dataset.
*
* @return The dataset.
*/
public CategoryDataset getDataset() {
return this.dataset;
}
/**
* Adds an item to the dataset.
*
* @param rowKey the row key.
* @param columnKey the column key.
* @param value the value.
*/
public void addItem(Comparable rowKey, Comparable columnKey, Number value) {
this.dataset.addValue(value, rowKey, columnKey);
}
/**
* The start of an element.
*
* @param namespaceURI the namespace.
* @param localName the element name.
* @param qName the element name.
* @param atts the element attributes.
*
* @throws SAXException for errors.
*/
@Override
public void startElement(String namespaceURI,
String localName,
String qName,
Attributes atts) throws SAXException {
DefaultHandler current = getCurrentHandler();
if (current != this) {
current.startElement(namespaceURI, localName, qName, atts);
}
else if (qName.equals(CATEGORYDATASET_TAG)) {
this.dataset = new DefaultCategoryDataset();
}
else if (qName.equals(SERIES_TAG)) {
CategorySeriesHandler subhandler = new CategorySeriesHandler(this);
getSubHandlers().push(subhandler);
subhandler.startElement(namespaceURI, localName, qName, atts);
}
else {
throw new SAXException("Element not recognised: " + qName);
}
}
/**
* The end of an element.
*
* @param namespaceURI the namespace.
* @param localName the element name.
* @param qName the element name.
*
* @throws SAXException for errors.
*/
@Override
public void endElement(String namespaceURI,
String localName,
String qName) throws SAXException {
DefaultHandler current = getCurrentHandler();
if (current != this) {
current.endElement(namespaceURI, localName, qName);
}
}
}
| 4,337 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
KeyHandler.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/data/xml/KeyHandler.java | /* ===========================================================
* JFreeChart : a free chart library for the Java(tm) platform
* ===========================================================
*
* (C) Copyright 2000-2011, 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.]
*
* ---------------
* KeyHandler.java
* ---------------
* (C) Copyright 2003-2008, by Object Refinery Limited and Contributors.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 23-Jan-2003 : Version 1 (DG);
*
*/
package org.jfree.data.xml;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
/**
* A SAX handler for reading a key.
*/
public class KeyHandler extends DefaultHandler implements DatasetTags {
/** The root handler. */
private RootHandler rootHandler;
/** The item handler. */
private ItemHandler itemHandler;
/** Storage for the current CDATA */
private StringBuffer currentText;
/** The key. */
//private Comparable key;
/**
* Creates a new handler.
*
* @param rootHandler the root handler.
* @param itemHandler the item handler.
*/
public KeyHandler(RootHandler rootHandler, ItemHandler itemHandler) {
this.rootHandler = rootHandler;
this.itemHandler = itemHandler;
this.currentText = new StringBuffer();
//this.key = null;
}
/**
* The start of an element.
*
* @param namespaceURI the namespace.
* @param localName the element name.
* @param qName the element name.
* @param atts the attributes.
*
* @throws SAXException for errors.
*/
@Override
public void startElement(String namespaceURI,
String localName,
String qName,
Attributes atts) throws SAXException {
if (qName.equals(KEY_TAG)) {
clearCurrentText();
}
else {
throw new SAXException("Expecting <Key> but found " + qName);
}
}
/**
* The end of an element.
*
* @param namespaceURI the namespace.
* @param localName the element name.
* @param qName the element name.
*
* @throws SAXException for errors.
*/
@Override
public void endElement(String namespaceURI,
String localName,
String qName) throws SAXException {
if (qName.equals(KEY_TAG)) {
this.itemHandler.setKey(getCurrentText());
this.rootHandler.popSubHandler();
this.rootHandler.pushSubHandler(
new ValueHandler(this.rootHandler, this.itemHandler)
);
}
else {
throw new SAXException("Expecting </Key> but found " + qName);
}
}
/**
* Receives some (or all) of the text in the current element.
*
* @param ch character buffer.
* @param start the start index.
* @param length the length of the valid character data.
*/
@Override
public void characters(char[] ch, int start, int length) {
if (this.currentText != null) {
this.currentText.append(String.copyValueOf(ch, start, length));
}
}
/**
* Returns the current text of the textbuffer.
*
* @return The current text.
*/
protected String getCurrentText() {
return this.currentText.toString();
}
/**
* Removes all text from the textbuffer at the end of a CDATA section.
*/
protected void clearCurrentText() {
this.currentText.delete(0, this.currentText.length());
}
}
| 4,698 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
ItemHandler.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/data/xml/ItemHandler.java | /* ===========================================================
* JFreeChart : a free chart library for the Java(tm) platform
* ===========================================================
*
* (C) Copyright 2000-2011, 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.]
*
* ----------------
* ItemHandler.java
* ----------------
* (C) Copyright 2003-2008, by Object Refinery Limited and Contributors.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 23-Jan-2003 : Version 1 (DG);
*
*/
package org.jfree.data.xml;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
/**
* A handler for reading key-value items.
*/
public class ItemHandler extends DefaultHandler implements DatasetTags {
/** The root handler. */
private RootHandler root;
/** The parent handler (can be the same as root, but not always). */
private DefaultHandler parent;
/** The key. */
private Comparable key;
/** The value. */
private Number value;
/**
* Creates a new item handler.
*
* @param root the root handler.
* @param parent the parent handler.
*/
public ItemHandler(RootHandler root, DefaultHandler parent) {
this.root = root;
this.parent = parent;
this.key = null;
this.value = null;
}
/**
* Returns the key that has been read by the handler, or <code>null</code>.
*
* @return The key.
*/
public Comparable getKey() {
return this.key;
}
/**
* Sets the key.
*
* @param key the key.
*/
public void setKey(Comparable key) {
this.key = key;
}
/**
* Returns the key that has been read by the handler, or <code>null</code>.
*
* @return The value.
*/
public Number getValue() {
return this.value;
}
/**
* Sets the value.
*
* @param value the value.
*/
public void setValue(Number value) {
this.value = value;
}
/**
* The start of an element.
*
* @param namespaceURI the namespace.
* @param localName the element name.
* @param qName the element name.
* @param atts the attributes.
*
* @throws SAXException for errors.
*/
@Override
public void startElement(String namespaceURI,
String localName,
String qName,
Attributes atts) throws SAXException {
if (qName.equals(ITEM_TAG)) {
KeyHandler subhandler = new KeyHandler(this.root, this);
this.root.pushSubHandler(subhandler);
}
else if (qName.equals(VALUE_TAG)) {
ValueHandler subhandler = new ValueHandler(this.root, this);
this.root.pushSubHandler(subhandler);
}
else {
throw new SAXException(
"Expected <Item> or <Value>...found " + qName
);
}
}
/**
* The end of an element.
*
* @param namespaceURI the namespace.
* @param localName the element name.
* @param qName the element name.
*/
@Override
public void endElement(String namespaceURI,
String localName,
String qName) {
if (this.parent instanceof PieDatasetHandler) {
PieDatasetHandler handler = (PieDatasetHandler) this.parent;
handler.addItem(this.key, this.value);
this.root.popSubHandler();
}
else if (this.parent instanceof CategorySeriesHandler) {
CategorySeriesHandler handler = (CategorySeriesHandler) this.parent;
handler.addItem(this.key, this.value);
this.root.popSubHandler();
}
}
}
| 4,836 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
RootHandler.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/data/xml/RootHandler.java | /* ===========================================================
* JFreeChart : a free chart library for the Java(tm) platform
* ===========================================================
*
* (C) Copyright 2000-2011, 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.]
*
* ----------------
* RootHandler.java
* ----------------
* (C) Copyright 2003-2008, by Object Refinery Limited and Contributors.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 23-Jan-2003 : Version 1 (DG);
*
*/
package org.jfree.data.xml;
import java.util.Stack;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
/**
* A SAX handler that delegates work to sub-handlers.
*/
public class RootHandler extends DefaultHandler implements DatasetTags {
/** The sub-handlers. */
private Stack subHandlers;
/**
* Creates a new handler.
*/
public RootHandler() {
this.subHandlers = new Stack();
}
/**
* Returns the stack of sub handlers.
*
* @return The sub-handler stack.
*/
public Stack getSubHandlers() {
return this.subHandlers;
}
/**
* Receives some (or all) of the text in the current element.
*
* @param ch character buffer.
* @param start the start index.
* @param length the length of the valid character data.
*
* @throws SAXException for errors.
*/
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
DefaultHandler handler = getCurrentHandler();
if (handler != this) {
handler.characters(ch, start, length);
}
}
/**
* Returns the handler at the top of the stack.
*
* @return The handler.
*/
public DefaultHandler getCurrentHandler() {
DefaultHandler result = this;
if (this.subHandlers != null) {
if (this.subHandlers.size() > 0) {
Object top = this.subHandlers.peek();
if (top != null) {
result = (DefaultHandler) top;
}
}
}
return result;
}
/**
* Pushes a sub-handler onto the stack.
*
* @param subhandler the sub-handler.
*/
public void pushSubHandler(DefaultHandler subhandler) {
this.subHandlers.push(subhandler);
}
/**
* Pops a sub-handler from the stack.
*
* @return The sub-handler.
*/
public DefaultHandler popSubHandler() {
return (DefaultHandler) this.subHandlers.pop();
}
}
| 3,586 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
CategorySeriesHandler.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/data/xml/CategorySeriesHandler.java | /* ===========================================================
* JFreeChart : a free chart library for the Java(tm) platform
* ===========================================================
*
* (C) Copyright 2000-2011, 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.]
*
* --------------------------
* CategorySeriesHandler.java
* --------------------------
* (C) Copyright 2003-2008, by Object Refinery Limited and Contributors.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 23-Jan-2003 : Version 1 (DG);
*
*/
package org.jfree.data.xml;
import org.jfree.data.DefaultKeyedValues;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
/**
* A handler for reading a series for a category dataset.
*/
public class CategorySeriesHandler extends DefaultHandler
implements DatasetTags {
/** The root handler. */
private RootHandler root;
/** The series key. */
private Comparable seriesKey;
/** The values. */
private DefaultKeyedValues values;
/**
* Creates a new item handler.
*
* @param root the root handler.
*/
public CategorySeriesHandler(RootHandler root) {
this.root = root;
this.values = new DefaultKeyedValues();
}
/**
* Sets the series key.
*
* @param key the key.
*/
public void setSeriesKey(Comparable key) {
this.seriesKey = key;
}
/**
* Adds an item to the temporary storage for the series.
*
* @param key the key.
* @param value the value.
*/
public void addItem(Comparable key, final Number value) {
this.values.addValue(key, value);
}
/**
* The start of an element.
*
* @param namespaceURI the namespace.
* @param localName the element name.
* @param qName the element name.
* @param atts the attributes.
*
* @throws SAXException for errors.
*/
@Override
public void startElement(String namespaceURI,
String localName,
String qName,
Attributes atts) throws SAXException {
if (qName.equals(SERIES_TAG)) {
setSeriesKey(atts.getValue("name"));
ItemHandler subhandler = new ItemHandler(this.root, this);
this.root.pushSubHandler(subhandler);
}
else if (qName.equals(ITEM_TAG)) {
ItemHandler subhandler = new ItemHandler(this.root, this);
this.root.pushSubHandler(subhandler);
subhandler.startElement(namespaceURI, localName, qName, atts);
}
else {
throw new SAXException(
"Expecting <Series> or <Item> tag...found " + qName
);
}
}
/**
* The end of an element.
*
* @param namespaceURI the namespace.
* @param localName the element name.
* @param qName the element name.
*/
@Override
public void endElement(String namespaceURI,
String localName,
String qName) {
if (this.root instanceof CategoryDatasetHandler) {
CategoryDatasetHandler handler = (CategoryDatasetHandler) this.root;
for (Comparable key : this.values.getKeys()) {
Number value = this.values.getValue(key);
handler.addItem(this.seriesKey, key, value);
}
this.root.popSubHandler();
}
}
}
| 4,544 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
ValueHandler.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/data/xml/ValueHandler.java | /* ===========================================================
* JFreeChart : a free chart library for the Java(tm) platform
* ===========================================================
*
* (C) Copyright 2000-2011, 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.]
*
* -----------------
* ValueHandler.java
* -----------------
* (C) Copyright 2003-2008, by Object Refinery Limited and Contributors.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): Luke Quinane;
*
* Changes
* -------
* 23-Jan-2003 : Version 1 (DG);
* 25-Nov-2003 : Patch to handle 'NaN' values (DG);
*
*/
package org.jfree.data.xml;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
/**
* A handler for reading a 'Value' element.
*/
public class ValueHandler extends DefaultHandler implements DatasetTags {
/** The root handler. */
private RootHandler rootHandler;
/** The item handler. */
private ItemHandler itemHandler;
/** Storage for the current CDATA */
private StringBuffer currentText;
/**
* Creates a new value handler.
*
* @param rootHandler the root handler.
* @param itemHandler the item handler.
*/
public ValueHandler(RootHandler rootHandler, ItemHandler itemHandler) {
this.rootHandler = rootHandler;
this.itemHandler = itemHandler;
this.currentText = new StringBuffer();
}
/**
* The start of an element.
*
* @param namespaceURI the namespace.
* @param localName the element name.
* @param qName the element name.
* @param atts the attributes.
*
* @throws SAXException for errors.
*/
@Override
public void startElement(String namespaceURI,
String localName,
String qName,
Attributes atts) throws SAXException {
if (qName.equals(VALUE_TAG)) {
// no attributes to read
clearCurrentText();
}
else {
throw new SAXException("Expecting <Value> but found " + qName);
}
}
/**
* The end of an element.
*
* @param namespaceURI the namespace.
* @param localName the element name.
* @param qName the element name.
*
* @throws SAXException for errors.
*/
@Override
public void endElement(String namespaceURI,
String localName,
String qName) throws SAXException {
if (qName.equals(VALUE_TAG)) {
Number value;
try {
value = Double.valueOf(this.currentText.toString());
if (((Double) value).isNaN()) {
value = null;
}
}
catch (NumberFormatException e1) {
value = null;
}
this.itemHandler.setValue(value);
this.rootHandler.popSubHandler();
}
else {
throw new SAXException("Expecting </Value> but found " + qName);
}
}
/**
* Receives some (or all) of the text in the current element.
*
* @param ch character buffer.
* @param start the start index.
* @param length the length of the valid character data.
*/
@Override
public void characters(char[] ch, int start, int length) {
if (this.currentText != null) {
this.currentText.append(String.copyValueOf(ch, start, length));
}
}
/**
* Returns the current text of the textbuffer.
*
* @return The current text.
*/
protected String getCurrentText() {
return this.currentText.toString();
}
/**
* Removes all text from the textbuffer at the end of a CDATA section.
*/
protected void clearCurrentText() {
this.currentText.delete(0, this.currentText.length());
}
}
| 4,932 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
DatasetTags.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/data/xml/DatasetTags.java | /* ===========================================================
* JFreeChart : a free chart library for the Java(tm) platform
* ===========================================================
*
* (C) Copyright 2000-2011, 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.]
*
* ----------------
* DatasetTags.java
* ----------------
* (C) Copyright 2003-2008, by Object Refinery Limited and Contributors.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 23-Jan-2003 : Version 1 (DG);
*
*/
package org.jfree.data.xml;
/**
* Constants for the tags that identify the elements in the XML files.
*/
public interface DatasetTags {
/** The 'PieDataset' element name. */
public static final String PIEDATASET_TAG = "PieDataset";
/** The 'CategoryDataset' element name. */
public static final String CATEGORYDATASET_TAG = "CategoryDataset";
/** The 'Series' element name. */
public static final String SERIES_TAG = "Series";
/** The 'Item' element name. */
public static final String ITEM_TAG = "Item";
/** The 'Key' element name. */
public static final String KEY_TAG = "Key";
/** The 'Value' element name. */
public static final String VALUE_TAG = "Value";
}
| 2,237 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
DatasetReader.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/data/xml/DatasetReader.java | /* ===========================================================
* JFreeChart : a free chart library for the Java(tm) platform
* ===========================================================
*
* (C) Copyright 2000-2011, 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.]
*
* ------------------
* DatasetReader.java
* ------------------
* (C) Copyright 2002-2008, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 20-Nov-2002 : Version 1 (DG);
*
*/
package org.jfree.data.xml;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.general.PieDataset;
import org.xml.sax.SAXException;
/**
* A utility class for reading datasets from XML.
*/
public class DatasetReader {
/**
* Reads a {@link PieDataset} from an XML file.
*
* @param file the file.
*
* @return A dataset.
*
* @throws IOException if there is a problem reading the file.
*/
public static PieDataset readPieDatasetFromXML(File file)
throws IOException {
InputStream in = new FileInputStream(file);
return readPieDatasetFromXML(in);
}
/**
* Reads a {@link PieDataset} from a stream.
*
* @param in the input stream.
*
* @return A dataset.
*
* @throws IOException if there is an I/O error.
*/
public static PieDataset readPieDatasetFromXML(InputStream in)
throws IOException {
PieDataset result = null;
SAXParserFactory factory = SAXParserFactory.newInstance();
try {
SAXParser parser = factory.newSAXParser();
PieDatasetHandler handler = new PieDatasetHandler();
parser.parse(in, handler);
result = handler.getDataset();
}
catch (SAXException e) {
System.out.println(e.getMessage());
}
catch (ParserConfigurationException e2) {
System.out.println(e2.getMessage());
}
return result;
}
/**
* Reads a {@link CategoryDataset} from a file.
*
* @param file the file.
*
* @return A dataset.
*
* @throws IOException if there is a problem reading the file.
*/
public static CategoryDataset readCategoryDatasetFromXML(File file)
throws IOException {
InputStream in = new FileInputStream(file);
return readCategoryDatasetFromXML(in);
}
/**
* Reads a {@link CategoryDataset} from a stream.
*
* @param in the stream.
*
* @return A dataset.
*
* @throws IOException if there is a problem reading the file.
*/
public static CategoryDataset readCategoryDatasetFromXML(InputStream in)
throws IOException {
CategoryDataset result = null;
SAXParserFactory factory = SAXParserFactory.newInstance();
try {
SAXParser parser = factory.newSAXParser();
CategoryDatasetHandler handler = new CategoryDatasetHandler();
parser.parse(in, handler);
result = handler.getDataset();
}
catch (SAXException e) {
System.out.println(e.getMessage());
}
catch (ParserConfigurationException e2) {
System.out.println(e2.getMessage());
}
return result;
}
}
| 4,567 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
DefaultMultiValueCategoryDataset.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/data/statistics/DefaultMultiValueCategoryDataset.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.]
*
* -------------------------------------
* DefaultMultiValueCategoryDataset.java
* -------------------------------------
* (C) Copyright 2007, 2008, by David Forslund and Contributors.
*
* Original Author: David Forslund;
* Contributor(s): David Gilbert (for Object Refinery Limited);
*
* Changes
* -------
* 08-Oct-2007 : Version 1, see patch 1780779 (DG);
* 06-Nov-2007 : Return EMPTY_LIST not null from getValues() (DG);
* 17-Jun-2012 : Removed JCommon dependencies (DG);
*
*/
package org.jfree.data.statistics;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.jfree.chart.axis.NumberComparator;
import org.jfree.chart.util.PublicCloneable;
import org.jfree.data.KeyedObjects2D;
import org.jfree.data.Range;
import org.jfree.data.RangeInfo;
import org.jfree.data.general.AbstractDataset;
import org.jfree.data.general.DatasetChangeEvent;
/**
* A category dataset that defines multiple values for each item.
*
* @since 1.0.7
*/
public class DefaultMultiValueCategoryDataset extends AbstractDataset
implements MultiValueCategoryDataset, RangeInfo, PublicCloneable {
/**
* Storage for the data.
*/
protected KeyedObjects2D data;
/**
* The minimum range value.
*/
private Number minimumRangeValue;
/**
* The maximum range value.
*/
private Number maximumRangeValue;
/**
* The range of values.
*/
private Range rangeBounds;
/**
* Creates a new dataset.
*/
public DefaultMultiValueCategoryDataset() {
this.data = new KeyedObjects2D();
this.minimumRangeValue = null;
this.maximumRangeValue = null;
this.rangeBounds = new Range(0.0, 0.0);
}
/**
* Adds a list of values to the dataset (<code>null</code> and Double.NaN
* items are automatically removed) and sends a {@link DatasetChangeEvent}
* to all registered listeners.
*
* @param values a list of values (<code>null</code> not permitted).
* @param rowKey the row key (<code>null</code> not permitted).
* @param columnKey the column key (<code>null</code> not permitted).
*/
public void add(List<Number> values, Comparable rowKey, Comparable columnKey) {
if (values == null) {
throw new IllegalArgumentException("Null 'values' argument.");
}
if (rowKey == null) {
throw new IllegalArgumentException("Null 'rowKey' argument.");
}
if (columnKey == null) {
throw new IllegalArgumentException("Null 'columnKey' argument.");
}
List<Number> vlist = new ArrayList<Number>(values.size());
for (Number n : values) {
double v = n.doubleValue();
if (!Double.isNaN(v)) {
vlist.add(n);
}
}
Collections.sort(vlist, new NumberComparator());
this.data.addObject(vlist, rowKey, columnKey);
if (vlist.size() > 0) {
double maxval = Double.NEGATIVE_INFINITY;
double minval = Double.POSITIVE_INFINITY;
for (Number n : vlist) {
double v = n.doubleValue();
minval = Math.min(minval, v);
maxval = Math.max(maxval, v);
}
// update the cached range values...
if (this.maximumRangeValue == null) {
this.maximumRangeValue = maxval;
}
else if (maxval > this.maximumRangeValue.doubleValue()) {
this.maximumRangeValue = maxval;
}
if (this.minimumRangeValue == null) {
this.minimumRangeValue = minval;
}
else if (minval < this.minimumRangeValue.doubleValue()) {
this.minimumRangeValue = minval;
}
this.rangeBounds = new Range(this.minimumRangeValue.doubleValue(),
this.maximumRangeValue.doubleValue());
}
fireDatasetChanged();
}
/**
* Returns a list (possibly empty) of the values for the specified item.
* The returned list should be unmodifiable.
*
* @param row the row index (zero-based).
* @param column the column index (zero-based).
*
* @return The list of values.
*/
@Override
public List<Number> getValues(int row, int column) {
List<Number> values = (List<Number>) this.data.getObject(row, column);
if (values != null) {
return Collections.unmodifiableList(values);
}
else {
return Collections.EMPTY_LIST;
}
}
/**
* Returns a list (possibly empty) of the values for the specified item.
* The returned list should be unmodifiable.
*
* @param rowKey the row key (<code>null</code> not permitted).
* @param columnKey the column key (<code>null</code> not permitted).
*
* @return The list of values.
*/
@Override
public List<Number> getValues(Comparable rowKey, Comparable columnKey) {
return Collections.unmodifiableList((List<Number>) this.data.getObject(rowKey,
columnKey));
}
/**
* Returns the average value for the specified item.
*
* @param row the row key.
* @param column the column key.
*
* @return The average value.
*/
@Override
public Number getValue(Comparable row, Comparable column) {
List<Number> l = (List<Number>) this.data.getObject(row, column);
double average = 0.0d;
int count = 0;
if (l != null && l.size() > 0) {
for (Number n : l) {
average += n.doubleValue();
count += 1;
}
if (count > 0) {
average = average / count;
}
}
if (count == 0) {
return null;
}
return average;
}
/**
* Returns the average value for the specified item.
*
* @param row the row index.
* @param column the column index.
*
* @return The average value.
*/
@Override
public Number getValue(int row, int column) {
List<Number> l = (List<Number>) this.data.getObject(row, column);
double average = 0.0d;
int count = 0;
if (l != null && l.size() > 0) {
for (Number n : l) {
average += n.doubleValue();
count += 1;
}
if (count > 0) {
average = average / count;
}
}
if (count == 0) {
return null;
}
return average;
}
/**
* Returns the column index for a given key.
*
* @param key the column key.
*
* @return The column index.
*/
@Override
public int getColumnIndex(Comparable key) {
return this.data.getColumnIndex(key);
}
/**
* Returns a column key.
*
* @param column the column index (zero-based).
*
* @return The column key.
*/
@Override
public Comparable getColumnKey(int column) {
return this.data.getColumnKey(column);
}
/**
* Returns the column keys.
*
* @return The keys.
*/
@Override
public List<Comparable> getColumnKeys() {
return this.data.getColumnKeys();
}
/**
* Returns the row index for a given key.
*
* @param key the row key.
*
* @return The row index.
*/
@Override
public int getRowIndex(Comparable key) {
return this.data.getRowIndex(key);
}
/**
* Returns a row key.
*
* @param row the row index (zero-based).
*
* @return The row key.
*/
@Override
public Comparable getRowKey(int row) {
return this.data.getRowKey(row);
}
/**
* Returns the row keys.
*
* @return The keys.
*/
@Override
public List<Comparable> getRowKeys() {
return this.data.getRowKeys();
}
/**
* Returns the number of rows in the table.
*
* @return The row count.
*/
@Override
public int getRowCount() {
return this.data.getRowCount();
}
/**
* Returns the number of columns in the table.
*
* @return The column count.
*/
@Override
public int getColumnCount() {
return this.data.getColumnCount();
}
/**
* Returns the minimum y-value in the dataset.
*
* @param includeInterval a flag that determines whether or not the
* y-interval is taken into account.
*
* @return The minimum value.
*/
@Override
public double getRangeLowerBound(boolean includeInterval) {
double result = Double.NaN;
if (this.minimumRangeValue != null) {
result = this.minimumRangeValue.doubleValue();
}
return result;
}
/**
* Returns the maximum y-value in the dataset.
*
* @param includeInterval a flag that determines whether or not the
* y-interval is taken into account.
*
* @return The maximum value.
*/
@Override
public double getRangeUpperBound(boolean includeInterval) {
double result = Double.NaN;
if (this.maximumRangeValue != null) {
result = this.maximumRangeValue.doubleValue();
}
return result;
}
/**
* Returns the range of the values in this dataset's range.
*
* @param includeInterval a flag that determines whether or not the
* y-interval is taken into account.
* @return The range.
*/
@Override
public Range getRangeBounds(boolean includeInterval) {
return this.rangeBounds;
}
/**
* Tests this dataset 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 DefaultMultiValueCategoryDataset)) {
return false;
}
DefaultMultiValueCategoryDataset that
= (DefaultMultiValueCategoryDataset) obj;
return this.data.equals(that.data);
}
/**
* Returns a clone of this instance.
*
* @return A clone.
*
* @throws CloneNotSupportedException if the dataset cannot be cloned.
*/
@Override
public Object clone() throws CloneNotSupportedException {
DefaultMultiValueCategoryDataset clone
= (DefaultMultiValueCategoryDataset) super.clone();
clone.data = (KeyedObjects2D) this.data.clone();
return clone;
}
}
| 12,034 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
BoxAndWhiskerXYDataset.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/data/statistics/BoxAndWhiskerXYDataset.java | /* ===========================================================
* JFreeChart : a free chart library for the Java(tm) platform
* ===========================================================
*
* (C) Copyright 2000-2011, 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.]
*
* ---------------------------
* BoxAndWhiskerXYDataset.java
* ---------------------------
* (C) Copyright 2003-2008, 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 (DG);
* 12-Aug-2003 : Added new methods: getMaxNonOutlierValue
* getMaxNonFaroutValue
* getOutlierCoefficient
* setOutlierCoefficient
* getFaroutCoefficient
* setFaroutCoefficient
* getInterquartileRange (DB)
* 27-Aug-2003 : Renamed BoxAndWhiskerDataset --> BoxAndWhiskerXYDataset, and
* cut down methods (DG);
* ------------- JFREECHART 1.0.x ---------------------------------------------
* 02-Feb-2007 : Removed author tags from all over JFreeChart sources (DG);
*
*/
package org.jfree.data.statistics;
import java.util.List;
import org.jfree.data.xy.XYDataset;
/**
* An interface that defines data in the form of (x, max, min, average, median)
* tuples.
* <P>
* Example: JFreeChart uses this interface to obtain data for AIMS
* max-min-average-median plots.
*/
public interface BoxAndWhiskerXYDataset extends XYDataset {
/**
* Returns the mean for the specified series and item.
*
* @param series the series (zero-based index).
* @param item the item (zero-based index).
*
* @return The mean for the specified series and item.
*/
public Number getMeanValue(int series, int item);
/**
* Returns the median-value for the specified series and item.
*
* @param series the series (zero-based index).
* @param item the item (zero-based index).
*
* @return The median-value for the specified series and item.
*/
public Number getMedianValue(int series, int item);
/**
* Returns the Q1 median-value for the specified series and item.
*
* @param series the series (zero-based index).
* @param item the item (zero-based index).
*
* @return The Q1 median-value for the specified series and item.
*/
public Number getQ1Value(int series, int item);
/**
* Returns the Q3 median-value for the specified series and item.
*
* @param series the series (zero-based index).
* @param item the item (zero-based index).
*
* @return The Q3 median-value for the specified series and item.
*/
public Number getQ3Value(int series, int item);
/**
* Returns the min-value for the specified series and item.
*
* @param series the series (zero-based index).
* @param item the item (zero-based index).
*
* @return The min-value for the specified series and item.
*/
public Number getMinRegularValue(int series, int item);
/**
* Returns the max-value for the specified series and item.
*
* @param series the series (zero-based index).
* @param item the item (zero-based index).
*
* @return The max-value for the specified series and item.
*/
public Number getMaxRegularValue(int series, int item);
/**
* Returns the minimum value which is not a farout.
* @param series the series (zero-based index).
* @param item the item (zero-based index).
*
* @return A <code>Number</code> representing the maximum non-farout value.
*/
public Number getMinOutlier(int series, int item);
/**
* Returns the maximum value which is not a farout, ie Q3 + (interquartile
* range * farout coefficient).
*
* @param series the series (zero-based index).
* @param item the item (zero-based index).
*
* @return A <code>Number</code> representing the maximum non-farout value.
*/
public Number getMaxOutlier(int series, int item);
/**
* Returns a list of outliers for the specified series and item.
*
* @param series the series (zero-based index).
* @param item the item (zero-based index).
*
* @return The list of outliers for the specified series and item
* (possibly <code>null</code>).
*/
public List<Number> getOutliers(int series, int item);
/**
* Returns the value used as the outlier coefficient. The outlier
* coefficient gives an indication of the degree of certainty in an
* unskewed distribution. Increasing the coefficient increases the number
* of values included. Currently only used to ensure farout coefficient
* is greater than the outlier coefficient
*
* @return A <code>double</code> representing the value used to calculate
* outliers
*/
public double getOutlierCoefficient();
/**
* Returns the value used as the farout coefficient. The farout coefficient
* allows the calculation of which values will be off the graph.
*
* @return A <code>double</code> representing the value used to calculate
* farouts
*/
public double getFaroutCoefficient();
}
| 6,524 | 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/data/statistics/package-info.java | /**
* Classes for representing statistical data.
*/
package org.jfree.data.statistics;
| 89 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
HistogramType.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/data/statistics/HistogramType.java | /* ===========================================================
* JFreeChart : a free chart library for the Java(tm) platform
* ===========================================================
*
* (C) Copyright 2000-2011, 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.]
*
* ------------------
* HistogramType.java
* ------------------
* (C) Copyright 2004-2008, by Object Refinery Limited and Contributors.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 05-Mar-2004 : Version 1 (DG);
*
*/
package org.jfree.data.statistics;
/**
* A class for creating constants to represent the histogram type. See Bloch's
* enum tip in 'Effective Java'.
*/
public enum HistogramType {
/** Frequency histogram. */
FREQUENCY("FREQUENCY"),
/** Relative frequency. */
RELATIVE_FREQUENCY("RELATIVE_FREQUENCY"),
/** Scale area to one. */
SCALE_AREA_TO_1("SCALE_AREA_TO_1");
/** The type name. */
private String name;
/**
* Creates a new type.
*
* @param name the name.
*/
private HistogramType(String name) {
this.name = name;
}
/**
* Returns a string representing the object.
*
* @return The string.
*/
@Override
public String toString() {
return this.name;
}
}
| 2,303 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
HistogramBin.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/data/statistics/HistogramBin.java | /* ===========================================================
* JFreeChart : a free chart library for the Java(tm) platform
* ===========================================================
*
* (C) Copyright 2000-2011, 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.]
*
* -----------------
* HistogramBin.java
* -----------------
* (C) Copyright 2003-2008, by Jelai Wang and Contributors.
*
* Original Author: Jelai Wang (jelaiw AT mindspring.com);
* Contributor(s): David Gilbert (for Object Refinery Limited);
*
* Changes
* -------
* 06-Jul-2003 : Version 1, contributed by Jelai Wang (DG);
* 07-Jul-2003 : Changed package and added Javadocs (DG);
* 01-Mar-2004 : Moved from org.jfree.data --> org.jfree.data.statistics (DG);
* ------------- JFREECHART 1.0.x ---------------------------------------------
* 02-Feb-2007 : Removed author tags from all over JFreeChart sources (DG);
*
*/
package org.jfree.data.statistics;
import java.io.Serializable;
/**
* A bin for the {@link HistogramDataset} class.
*/
public class HistogramBin implements Cloneable, Serializable {
/** For serialization. */
private static final long serialVersionUID = 7614685080015589931L;
/** The number of items in the bin. */
private int count;
/** The start boundary. */
private double startBoundary;
/** The end boundary. */
private double endBoundary;
/**
* Creates a new bin.
*
* @param startBoundary the start boundary.
* @param endBoundary the end boundary.
*/
public HistogramBin(double startBoundary, double endBoundary) {
if (startBoundary > endBoundary) {
throw new IllegalArgumentException(
"HistogramBin(): startBoundary > endBoundary.");
}
this.count = 0;
this.startBoundary = startBoundary;
this.endBoundary = endBoundary;
}
/**
* Returns the number of items in the bin.
*
* @return The item count.
*/
public int getCount() {
return this.count;
}
/**
* Increments the item count.
*/
public void incrementCount() {
this.count++;
}
/**
* Returns the start boundary.
*
* @return The start boundary.
*/
public double getStartBoundary() {
return this.startBoundary;
}
/**
* Returns the end boundary.
*
* @return The end boundary.
*/
public double getEndBoundary() {
return this.endBoundary;
}
/**
* Returns the bin width.
*
* @return The bin width.
*/
public double getBinWidth() {
return this.endBoundary - this.startBoundary;
}
/**
* Tests this object for equality with an arbitrary object.
*
* @param obj the object to test against.
*
* @return A boolean.
*/
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (obj == this) {
return true;
}
if (obj instanceof HistogramBin) {
HistogramBin bin = (HistogramBin) obj;
boolean b0 = bin.startBoundary == this.startBoundary;
boolean b1 = bin.endBoundary == this.endBoundary;
boolean b2 = bin.count == this.count;
return b0 && b1 && b2;
}
return false;
}
/**
* Returns a clone of the bin.
*
* @return A clone.
*
* @throws CloneNotSupportedException not thrown by this class.
*/
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
| 4,601 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
BoxAndWhiskerCalculator.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/data/statistics/BoxAndWhiskerCalculator.java | /* ===========================================================
* JFreeChart : a free chart library for the Java(tm) platform
* ===========================================================
*
* (C) Copyright 2000-2011, 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.]
*
* ----------------------------
* BoxAndWhiskerCalculator.java
* ----------------------------
* (C) Copyright 2003-2008, by Object Refinery Limited and Contributors.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 28-Aug-2003 : Version 1 (DG);
* 17-Nov-2003 : Fixed bug in calculations of outliers and median (DG);
* 10-Jan-2005 : Removed deprecated methods in preparation for 1.0.0
* release (DG);
* ------------- JFREECHART 1.0.x ---------------------------------------------
* 15-Nov-2006 : Cleaned up handling of null arguments, and null or NaN items
* in the list (DG);
*
*/
package org.jfree.data.statistics;
import org.jfree.chart.axis.NumberComparator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* A utility class that calculates the mean, median, quartiles Q1 and Q3, plus
* a list of outlier values...all from an arbitrary list of
* <code>Number</code> objects.
*/
public abstract class BoxAndWhiskerCalculator {
/**
* Calculates the statistics required for a {@link BoxAndWhiskerItem}
* from a list of <code>Number</code> objects. Any items in the list
* that are <code>null</code>, not an instance of <code>Number</code>, or
* equivalent to <code>Double.NaN</code>, will be ignored.
*
* @param values a list of numbers (a <code>null</code> list is not
* permitted).
*
* @return A box-and-whisker item.
*/
public static BoxAndWhiskerItem calculateBoxAndWhiskerStatistics(
List<Number> values) {
return calculateBoxAndWhiskerStatistics(values, true);
}
/**
* Calculates the statistics required for a {@link BoxAndWhiskerItem}
* from a list of <code>Number</code> objects. Any items in the list
* that are <code>null</code>, not an instance of <code>Number</code>, or
* equivalent to <code>Double.NaN</code>, will be ignored.
*
* @param values a list of numbers (a <code>null</code> list is not
* permitted).
* @param stripNullAndNaNItems a flag that controls the handling of null
* and NaN items.
*
* @return A box-and-whisker item.
*
* @since 1.0.3
*/
public static BoxAndWhiskerItem calculateBoxAndWhiskerStatistics(
List<Number> values, boolean stripNullAndNaNItems) {
if (values == null) {
throw new IllegalArgumentException("Null 'values' argument.");
}
List<Number> vlist;
if (stripNullAndNaNItems) {
vlist = new ArrayList<Number>(values.size());
for (Number n : values) {
double v = n.doubleValue();
if (!Double.isNaN(v)) {
vlist.add(n);
}
}
}
else {
vlist = values;
}
Collections.sort(vlist, new NumberComparator());
double mean = Statistics.calculateMean(vlist, false);
double median = Statistics.calculateMedian(vlist, false);
double q1 = calculateQ1(vlist);
double q3 = calculateQ3(vlist);
double interQuartileRange = q3 - q1;
double upperOutlierThreshold = q3 + (interQuartileRange * 1.5);
double lowerOutlierThreshold = q1 - (interQuartileRange * 1.5);
double upperFaroutThreshold = q3 + (interQuartileRange * 2.0);
double lowerFaroutThreshold = q1 - (interQuartileRange * 2.0);
double minRegularValue = Double.POSITIVE_INFINITY;
double maxRegularValue = Double.NEGATIVE_INFINITY;
double minOutlier = Double.POSITIVE_INFINITY;
double maxOutlier = Double.NEGATIVE_INFINITY;
List<Number> outliers = new ArrayList<Number>();
for (Number number : vlist) {
double value = number.doubleValue();
if (value > upperOutlierThreshold) {
outliers.add(number);
if (value > maxOutlier && value <= upperFaroutThreshold) {
maxOutlier = value;
}
} else if (value < lowerOutlierThreshold) {
outliers.add(number);
if (value < minOutlier && value >= lowerFaroutThreshold) {
minOutlier = value;
}
} else {
minRegularValue = Math.min(minRegularValue, value);
maxRegularValue = Math.max(maxRegularValue, value);
}
minOutlier = Math.min(minOutlier, minRegularValue);
maxOutlier = Math.max(maxOutlier, maxRegularValue);
}
return new BoxAndWhiskerItem(mean, median,
q1, q3, minRegularValue,
maxRegularValue, minOutlier,
maxOutlier, outliers);
}
/**
* Calculates the first quartile for a list of numbers in ascending order.
* If the items in the list are not in ascending order, the result is
* unspecified. If the list contains items that are <code>null</code>, not
* an instance of <code>Number</code>, or equivalent to
* <code>Double.NaN</code>, the result is unspecified.
*
* @param values the numbers in ascending order (<code>null</code> not
* permitted).
*
* @return The first quartile.
*/
public static double calculateQ1(List<Number> values) {
if (values == null) {
throw new IllegalArgumentException("Null 'values' argument.");
}
double result = Double.NaN;
int count = values.size();
if (count > 0) {
if (count % 2 == 1) {
if (count > 1) {
result = Statistics.calculateMedian(values, 0, count / 2);
}
else {
result = Statistics.calculateMedian(values, 0, 0);
}
}
else {
result = Statistics.calculateMedian(values, 0, count / 2 - 1);
}
}
return result;
}
/**
* Calculates the third quartile for a list of numbers in ascending order.
* If the items in the list are not in ascending order, the result is
* unspecified. If the list contains items that are <code>null</code>, not
* an instance of <code>Number</code>, or equivalent to
* <code>Double.NaN</code>, the result is unspecified.
*
* @param values the list of values (<code>null</code> not permitted).
*
* @return The third quartile.
*/
public static double calculateQ3(List<Number> values) {
if (values == null) {
throw new IllegalArgumentException("Null 'values' argument.");
}
double result = Double.NaN;
int count = values.size();
if (count > 0) {
if (count % 2 == 1) {
if (count > 1) {
result = Statistics.calculateMedian(values, count / 2,
count - 1);
}
else {
result = Statistics.calculateMedian(values, 0, 0);
}
}
else {
result = Statistics.calculateMedian(values, count / 2,
count - 1);
}
}
return result;
}
}
| 8,615 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
SimpleHistogramBin.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/data/statistics/SimpleHistogramBin.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.]
*
* -----------------------
* SimpleHistogramBin.java
* -----------------------
* (C) Copyright 2005-2012, by Object Refinery Limited and Contributors.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 10-Jan-2005 : Version 1 (DG);
* 17-Jun-2012 : Removed JCommon dependencies (DG);
*
*/
package org.jfree.data.statistics;
import java.io.Serializable;
import org.jfree.chart.util.PublicCloneable;
/**
* A bin for the {@link SimpleHistogramDataset}.
*/
public class SimpleHistogramBin implements Comparable,
Cloneable, PublicCloneable, Serializable {
/** For serialization. */
private static final long serialVersionUID = 3480862537505941742L;
/** The lower bound for the bin. */
private double lowerBound;
/** The upper bound for the bin. */
private double upperBound;
/**
* A flag that controls whether the lower bound is included in the bin
* range.
*/
private boolean includeLowerBound;
/**
* A flag that controls whether the upper bound is included in the bin
* range.
*/
private boolean includeUpperBound;
/** The item count. */
private int itemCount;
/**
* Creates a new bin.
*
* @param lowerBound the lower bound (inclusive).
* @param upperBound the upper bound (inclusive);
*/
public SimpleHistogramBin(double lowerBound, double upperBound) {
this(lowerBound, upperBound, true, true);
}
/**
* Creates a new bin.
*
* @param lowerBound the lower bound.
* @param upperBound the upper bound.
* @param includeLowerBound include the lower bound?
* @param includeUpperBound include the upper bound?
*/
public SimpleHistogramBin(double lowerBound, double upperBound,
boolean includeLowerBound,
boolean includeUpperBound) {
if (lowerBound >= upperBound) {
throw new IllegalArgumentException("Invalid bounds");
}
this.lowerBound = lowerBound;
this.upperBound = upperBound;
this.includeLowerBound = includeLowerBound;
this.includeUpperBound = includeUpperBound;
this.itemCount = 0;
}
/**
* Returns the lower bound.
*
* @return The lower bound.
*/
public double getLowerBound() {
return this.lowerBound;
}
/**
* Return the upper bound.
*
* @return The upper bound.
*/
public double getUpperBound() {
return this.upperBound;
}
/**
* Returns the item count.
*
* @return The item count.
*/
public int getItemCount() {
return this.itemCount;
}
/**
* Sets the item count.
*
* @param count the item count.
*/
public void setItemCount(int count) {
this.itemCount = count;
}
/**
* Returns <code>true</code> if the specified value belongs in the bin,
* and <code>false</code> otherwise.
*
* @param value the value.
*
* @return A boolean.
*/
public boolean accepts(double value) {
if (Double.isNaN(value)) {
return false;
}
if (value < this.lowerBound) {
return false;
}
if (value > this.upperBound) {
return false;
}
if (value == this.lowerBound) {
return this.includeLowerBound;
}
if (value == this.upperBound) {
return this.includeUpperBound;
}
return true;
}
/**
* Returns <code>true</code> if this bin overlaps with the specified bin,
* and <code>false</code> otherwise.
*
* @param bin the other bin (<code>null</code> not permitted).
*
* @return A boolean.
*/
public boolean overlapsWith(SimpleHistogramBin bin) {
if (this.upperBound < bin.lowerBound) {
return false;
}
if (this.lowerBound > bin.upperBound) {
return false;
}
if (this.upperBound == bin.lowerBound) {
return this.includeUpperBound && bin.includeLowerBound;
}
if (this.lowerBound == bin.upperBound) {
return this.includeLowerBound && bin.includeUpperBound;
}
return true;
}
/**
* Compares the bin to an arbitrary object and returns the relative
* ordering.
*
* @param obj the object.
*
* @return An integer indicating the relative ordering of the this bin and
* the given object.
*/
@Override
public int compareTo(Object obj) {
if (!(obj instanceof SimpleHistogramBin)) {
return 0;
}
SimpleHistogramBin bin = (SimpleHistogramBin) obj;
if (this.lowerBound < bin.lowerBound) {
return -1;
}
if (this.lowerBound > bin.lowerBound) {
return 1;
}
// lower bounds are the same
if (this.upperBound < bin.upperBound) {
return -1;
}
if (this.upperBound > bin.upperBound) {
return 1;
}
return 0;
}
/**
* Tests this bin 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 SimpleHistogramBin)) {
return false;
}
SimpleHistogramBin that = (SimpleHistogramBin) obj;
if (this.lowerBound != that.lowerBound) {
return false;
}
if (this.upperBound != that.upperBound) {
return false;
}
if (this.includeLowerBound != that.includeLowerBound) {
return false;
}
if (this.includeUpperBound != that.includeUpperBound) {
return false;
}
if (this.itemCount != that.itemCount) {
return false;
}
return true;
}
/**
* Returns a clone of the bin.
*
* @return A clone.
*
* @throws CloneNotSupportedException not thrown by this class.
*/
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
| 7,566 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
MeanAndStandardDeviation.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/data/statistics/MeanAndStandardDeviation.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.]
*
* -----------------------------
* MeanAndStandardDeviation.java
* -----------------------------
* (C) Copyright 2003-2012, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes:
* --------
* 05-Feb-2002 : Version 1 (DG);
* 05-Feb-2005 : Added equals() method and implemented Serializable (DG);
* 02-Oct-2007 : Added getMeanValue() and getStandardDeviationValue() methods
* for convenience, and toString() method for debugging (DG);
* 17-Jun-2012 : Removed JCommon dependencies (DG);
*
*/
package org.jfree.data.statistics;
import java.io.Serializable;
import org.jfree.chart.util.ObjectUtilities;
/**
* A simple data structure that holds a mean value and a standard deviation
* value. This is used in the
* {@link org.jfree.data.statistics.DefaultStatisticalCategoryDataset} class.
*/
public class MeanAndStandardDeviation implements Serializable {
/** For serialization. */
private static final long serialVersionUID = 7413468697315721515L;
/** The mean. */
private Number mean;
/** The standard deviation. */
private Number standardDeviation;
/**
* Creates a new mean and standard deviation record.
*
* @param mean the mean.
* @param standardDeviation the standard deviation.
*/
public MeanAndStandardDeviation(double mean, double standardDeviation) {
this(new Double(mean), new Double(standardDeviation));
}
/**
* Creates a new mean and standard deviation record.
*
* @param mean the mean (<code>null</code> permitted).
* @param standardDeviation the standard deviation (<code>null</code>
* permitted.
*/
public MeanAndStandardDeviation(Number mean, Number standardDeviation) {
this.mean = mean;
this.standardDeviation = standardDeviation;
}
/**
* Returns the mean.
*
* @return The mean.
*/
public Number getMean() {
return this.mean;
}
/**
* Returns the mean as a double primitive. If the underlying mean is
* <code>null</code>, this method will return <code>Double.NaN</code>.
*
* @return The mean.
*
* @see #getMean()
*
* @since 1.0.7
*/
public double getMeanValue() {
double result = Double.NaN;
if (this.mean != null) {
result = this.mean.doubleValue();
}
return result;
}
/**
* Returns the standard deviation.
*
* @return The standard deviation.
*/
public Number getStandardDeviation() {
return this.standardDeviation;
}
/**
* Returns the standard deviation as a double primitive. If the underlying
* standard deviation is <code>null</code>, this method will return
* <code>Double.NaN</code>.
*
* @return The standard deviation.
*
* @since 1.0.7
*/
public double getStandardDeviationValue() {
double result = Double.NaN;
if (this.standardDeviation != null) {
result = this.standardDeviation.doubleValue();
}
return result;
}
/**
* 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 MeanAndStandardDeviation)) {
return false;
}
MeanAndStandardDeviation that = (MeanAndStandardDeviation) obj;
if (!ObjectUtilities.equal(this.mean, that.mean)) {
return false;
}
if (!ObjectUtilities.equal(
this.standardDeviation, that.standardDeviation)
) {
return false;
}
return true;
}
/**
* Returns a string representing this instance.
*
* @return A string.
*
* @since 1.0.7
*/
@Override
public String toString() {
return "[" + this.mean + ", " + this.standardDeviation + "]";
}
} | 5,402 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
DefaultBoxAndWhiskerCategoryDataset.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/data/statistics/DefaultBoxAndWhiskerCategoryDataset.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.]
*
* ----------------------------------------
* DefaultBoxAndWhiskerCategoryDataset.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 (DG);
* 27-Aug-2003 : Moved from org.jfree.data --> org.jfree.data.statistics (DG);
* 12-Nov-2003 : Changed 'data' from private to protected and added a new 'add'
* method as proposed by Tim Bardzil. Also removed old code (DG);
* 01-Mar-2004 : Added equals() method (DG);
* 18-Nov-2004 : Updates for changes in RangeInfo interface (DG);
* 11-Jan-2005 : Removed deprecated code in preparation for the 1.0.0
* release (DG);
* ------------- JFREECHART 1.0.x ---------------------------------------------
* 02-Feb-2007 : Removed author tags from all over JFreeChart sources (DG);
* 17-Apr-2007 : Fixed bug 1701822 (DG);
* 13-Jun-2007 : Fixed error in previous patch (DG);
* 28-Sep-2007 : Fixed cloning bug (DG);
* 02-Oct-2007 : Fixed bug in updating cached bounds (DG);
* 03-Oct-2007 : Fixed another bug in updating cached bounds, added removal
* methods (DG);
* 17-Jun-2012 : Removed JCommon dependencies (DG);
*
*/
package org.jfree.data.statistics;
import java.util.List;
import org.jfree.chart.util.ObjectUtilities;
import org.jfree.chart.util.PublicCloneable;
import org.jfree.data.KeyedObjects2D;
import org.jfree.data.Range;
import org.jfree.data.RangeInfo;
import org.jfree.data.general.AbstractDataset;
import org.jfree.data.general.DatasetChangeEvent;
/**
* A convenience class that provides a default implementation of the
* {@link BoxAndWhiskerCategoryDataset} interface.
*/
public class DefaultBoxAndWhiskerCategoryDataset extends AbstractDataset
implements BoxAndWhiskerCategoryDataset, RangeInfo, PublicCloneable {
/** Storage for the data. */
protected KeyedObjects2D data;
/** The minimum range value. */
private double minimumRangeValue;
/** The row index for the cell that the minimum range value comes from. */
private int minimumRangeValueRow;
/**
* The column index for the cell that the minimum range value comes from.
*/
private int minimumRangeValueColumn;
/** The maximum range value. */
private double maximumRangeValue;
/** The row index for the cell that the maximum range value comes from. */
private int maximumRangeValueRow;
/**
* The column index for the cell that the maximum range value comes from.
*/
private int maximumRangeValueColumn;
/**
* Creates a new dataset.
*/
public DefaultBoxAndWhiskerCategoryDataset() {
this.data = new KeyedObjects2D();
this.minimumRangeValue = Double.NaN;
this.minimumRangeValueRow = -1;
this.minimumRangeValueColumn = -1;
this.maximumRangeValue = Double.NaN;
this.maximumRangeValueRow = -1;
this.maximumRangeValueColumn = -1;
}
/**
* Adds a list of values relating to one box-and-whisker entity to the
* table. The various median values are calculated.
*
* @param list a collection of values from which the various medians will
* be calculated.
* @param rowKey the row key (<code>null</code> not permitted).
* @param columnKey the column key (<code>null</code> not permitted).
*
* @see #add(BoxAndWhiskerItem, Comparable, Comparable)
*/
public void add(List<Number> list, Comparable rowKey, Comparable columnKey) {
BoxAndWhiskerItem item = BoxAndWhiskerCalculator
.calculateBoxAndWhiskerStatistics(list);
add(item, rowKey, columnKey);
}
/**
* Adds a list of values relating to one Box and Whisker entity to the
* table. The various median values are calculated.
*
* @param item a box and whisker item (<code>null</code> not permitted).
* @param rowKey the row key (<code>null</code> not permitted).
* @param columnKey the column key (<code>null</code> not permitted).
*
* @see #add(List, Comparable, Comparable)
*/
public void add(BoxAndWhiskerItem item, Comparable rowKey,
Comparable columnKey) {
this.data.addObject(item, rowKey, columnKey);
// update cached min and max values
int r = this.data.getRowIndex(rowKey);
int c = this.data.getColumnIndex(columnKey);
if ((this.maximumRangeValueRow == r && this.maximumRangeValueColumn
== c) || (this.minimumRangeValueRow == r
&& this.minimumRangeValueColumn == c)) {
updateBounds();
}
else {
double minval = Double.NaN;
if (item.getMinOutlier() != null) {
minval = item.getMinOutlier().doubleValue();
}
double maxval = Double.NaN;
if (item.getMaxOutlier() != null) {
maxval = item.getMaxOutlier().doubleValue();
}
if (Double.isNaN(this.maximumRangeValue)) {
this.maximumRangeValue = maxval;
this.maximumRangeValueRow = r;
this.maximumRangeValueColumn = c;
}
else if (maxval > this.maximumRangeValue) {
this.maximumRangeValue = maxval;
this.maximumRangeValueRow = r;
this.maximumRangeValueColumn = c;
}
if (Double.isNaN(this.minimumRangeValue)) {
this.minimumRangeValue = minval;
this.minimumRangeValueRow = r;
this.minimumRangeValueColumn = c;
}
else if (minval < this.minimumRangeValue) {
this.minimumRangeValue = minval;
this.minimumRangeValueRow = r;
this.minimumRangeValueColumn = c;
}
}
fireDatasetChanged();
}
/**
* Removes an item from the dataset and sends a {@link DatasetChangeEvent}
* to all registered listeners.
*
* @param rowKey the row key (<code>null</code> not permitted).
* @param columnKey the column key (<code>null</code> not permitted).
*
* @see #add(BoxAndWhiskerItem, Comparable, Comparable)
*
* @since 1.0.7
*/
public void remove(Comparable rowKey, Comparable columnKey) {
// defer null argument checks
int r = getRowIndex(rowKey);
int c = getColumnIndex(columnKey);
this.data.removeObject(rowKey, columnKey);
// if this cell held a maximum and/or minimum value, we'll need to
// update the cached bounds...
if ((this.maximumRangeValueRow == r && this.maximumRangeValueColumn
== c) || (this.minimumRangeValueRow == r
&& this.minimumRangeValueColumn == c)) {
updateBounds();
}
fireDatasetChanged();
}
/**
* Removes a row from the dataset and sends a {@link DatasetChangeEvent}
* to all registered listeners.
*
* @param rowIndex the row index.
*
* @see #removeColumn(int)
*
* @since 1.0.7
*/
public void removeRow(int rowIndex) {
this.data.removeRow(rowIndex);
updateBounds();
fireDatasetChanged();
}
/**
* Removes a row from the dataset and sends a {@link DatasetChangeEvent}
* to all registered listeners.
*
* @param rowKey the row key.
*
* @see #removeColumn(Comparable)
*
* @since 1.0.7
*/
public void removeRow(Comparable rowKey) {
this.data.removeRow(rowKey);
updateBounds();
fireDatasetChanged();
}
/**
* Removes a column from the dataset and sends a {@link DatasetChangeEvent}
* to all registered listeners.
*
* @param columnIndex the column index.
*
* @see #removeRow(int)
*
* @since 1.0.7
*/
public void removeColumn(int columnIndex) {
this.data.removeColumn(columnIndex);
updateBounds();
fireDatasetChanged();
}
/**
* Removes a column from the dataset and sends a {@link DatasetChangeEvent}
* to all registered listeners.
*
* @param columnKey the column key.
*
* @see #removeRow(Comparable)
*
* @since 1.0.7
*/
public void removeColumn(Comparable columnKey) {
this.data.removeColumn(columnKey);
updateBounds();
fireDatasetChanged();
}
/**
* Clears all data from the dataset and sends a {@link DatasetChangeEvent}
* to all registered listeners.
*
* @since 1.0.7
*/
public void clear() {
this.data.clear();
updateBounds();
fireDatasetChanged();
}
/**
* Return an item from within the dataset.
*
* @param row the row index.
* @param column the column index.
*
* @return The item.
*/
public BoxAndWhiskerItem getItem(int row, int column) {
return (BoxAndWhiskerItem) this.data.getObject(row, column);
}
/**
* Returns the value for an item.
*
* @param row the row index.
* @param column the column index.
*
* @return The value.
*
* @see #getMedianValue(int, int)
* @see #getValue(Comparable, Comparable)
*/
@Override
public Number getValue(int row, int column) {
return getMedianValue(row, column);
}
/**
* Returns the value for an item.
*
* @param rowKey the row key.
* @param columnKey the columnKey.
*
* @return The value.
*
* @see #getMedianValue(Comparable, Comparable)
* @see #getValue(int, int)
*/
@Override
public Number getValue(Comparable rowKey, Comparable columnKey) {
return getMedianValue(rowKey, columnKey);
}
/**
* Returns the mean value for an item.
*
* @param row the row index (zero-based).
* @param column the column index (zero-based).
*
* @return The mean value.
*
* @see #getItem(int, int)
*/
@Override
public Number getMeanValue(int row, int column) {
Number result = null;
BoxAndWhiskerItem item = (BoxAndWhiskerItem) this.data.getObject(row,
column);
if (item != null) {
result = item.getMean();
}
return result;
}
/**
* Returns the mean value for an item.
*
* @param rowKey the row key.
* @param columnKey the column key.
*
* @return The mean value.
*
* @see #getItem(int, int)
*/
@Override
public Number getMeanValue(Comparable rowKey, Comparable columnKey) {
Number result = null;
BoxAndWhiskerItem item = (BoxAndWhiskerItem) this.data.getObject(
rowKey, columnKey);
if (item != null) {
result = item.getMean();
}
return result;
}
/**
* Returns the median value for an item.
*
* @param row the row index (zero-based).
* @param column the column index (zero-based).
*
* @return The median value.
*
* @see #getItem(int, int)
*/
@Override
public Number getMedianValue(int row, int column) {
Number result = null;
BoxAndWhiskerItem item = (BoxAndWhiskerItem) this.data.getObject(row,
column);
if (item != null) {
result = item.getMedian();
}
return result;
}
/**
* Returns the median value for an item.
*
* @param rowKey the row key.
* @param columnKey the columnKey.
*
* @return The median value.
*
* @see #getItem(int, int)
*/
@Override
public Number getMedianValue(Comparable rowKey, Comparable columnKey) {
Number result = null;
BoxAndWhiskerItem item = (BoxAndWhiskerItem) this.data.getObject(
rowKey, columnKey);
if (item != null) {
result = item.getMedian();
}
return result;
}
/**
* Returns the first quartile value.
*
* @param row the row index (zero-based).
* @param column the column index (zero-based).
*
* @return The first quartile value.
*
* @see #getItem(int, int)
*/
@Override
public Number getQ1Value(int row, int column) {
Number result = null;
BoxAndWhiskerItem item = (BoxAndWhiskerItem) this.data.getObject(
row, column);
if (item != null) {
result = item.getQ1();
}
return result;
}
/**
* Returns the first quartile value.
*
* @param rowKey the row key.
* @param columnKey the column key.
*
* @return The first quartile value.
*
* @see #getItem(int, int)
*/
@Override
public Number getQ1Value(Comparable rowKey, Comparable columnKey) {
Number result = null;
BoxAndWhiskerItem item = (BoxAndWhiskerItem) this.data.getObject(
rowKey, columnKey);
if (item != null) {
result = item.getQ1();
}
return result;
}
/**
* Returns the third quartile value.
*
* @param row the row index (zero-based).
* @param column the column index (zero-based).
*
* @return The third quartile value.
*
* @see #getItem(int, int)
*/
@Override
public Number getQ3Value(int row, int column) {
Number result = null;
BoxAndWhiskerItem item = (BoxAndWhiskerItem) this.data.getObject(
row, column);
if (item != null) {
result = item.getQ3();
}
return result;
}
/**
* Returns the third quartile value.
*
* @param rowKey the row key.
* @param columnKey the column key.
*
* @return The third quartile value.
*
* @see #getItem(int, int)
*/
@Override
public Number getQ3Value(Comparable rowKey, Comparable columnKey) {
Number result = null;
BoxAndWhiskerItem item = (BoxAndWhiskerItem) this.data.getObject(
rowKey, columnKey);
if (item != null) {
result = item.getQ3();
}
return result;
}
/**
* Returns the column index for a given key.
*
* @param key the column key (<code>null</code> not permitted).
*
* @return The column index.
*
* @see #getColumnKey(int)
*/
@Override
public int getColumnIndex(Comparable key) {
return this.data.getColumnIndex(key);
}
/**
* Returns a column key.
*
* @param column the column index (zero-based).
*
* @return The column key.
*
* @see #getColumnIndex(Comparable)
*/
@Override
public Comparable getColumnKey(int column) {
return this.data.getColumnKey(column);
}
/**
* Returns the column keys.
*
* @return The keys.
*
* @see #getRowKeys()
*/
@Override
public List<Comparable> getColumnKeys() {
return this.data.getColumnKeys();
}
/**
* Returns the row index for a given key.
*
* @param key the row key (<code>null</code> not permitted).
*
* @return The row index.
*
* @see #getRowKey(int)
*/
@Override
public int getRowIndex(Comparable key) {
// defer null argument check
return this.data.getRowIndex(key);
}
/**
* Returns a row key.
*
* @param row the row index (zero-based).
*
* @return The row key.
*
* @see #getRowIndex(Comparable)
*/
@Override
public Comparable getRowKey(int row) {
return this.data.getRowKey(row);
}
/**
* Returns the row keys.
*
* @return The keys.
*
* @see #getColumnKeys()
*/
@Override
public List<Comparable> getRowKeys() {
return this.data.getRowKeys();
}
/**
* Returns the number of rows in the table.
*
* @return The row count.
*
* @see #getColumnCount()
*/
@Override
public int getRowCount() {
return this.data.getRowCount();
}
/**
* Returns the number of columns in the table.
*
* @return The column count.
*
* @see #getRowCount()
*/
@Override
public int getColumnCount() {
return this.data.getColumnCount();
}
/**
* Returns the minimum y-value in the dataset.
*
* @param includeInterval a flag that determines whether or not the
* y-interval is taken into account.
*
* @return The minimum value.
*
* @see #getRangeUpperBound(boolean)
*/
@Override
public double getRangeLowerBound(boolean includeInterval) {
return this.minimumRangeValue;
}
/**
* Returns the maximum y-value in the dataset.
*
* @param includeInterval a flag that determines whether or not the
* y-interval is taken into account.
*
* @return The maximum value.
*
* @see #getRangeLowerBound(boolean)
*/
@Override
public double getRangeUpperBound(boolean includeInterval) {
return this.maximumRangeValue;
}
/**
* Returns the range of the values in this dataset's range.
*
* @param includeInterval a flag that determines whether or not the
* y-interval is taken into account.
*
* @return The range.
*/
@Override
public Range getRangeBounds(boolean includeInterval) {
return new Range(this.minimumRangeValue, this.maximumRangeValue);
}
/**
* Returns the minimum regular (non outlier) value for an item.
*
* @param row the row index (zero-based).
* @param column the column index (zero-based).
*
* @return The minimum regular value.
*
* @see #getItem(int, int)
*/
@Override
public Number getMinRegularValue(int row, int column) {
Number result = null;
BoxAndWhiskerItem item = (BoxAndWhiskerItem) this.data.getObject(
row, column);
if (item != null) {
result = item.getMinRegularValue();
}
return result;
}
/**
* Returns the minimum regular (non outlier) value for an item.
*
* @param rowKey the row key.
* @param columnKey the column key.
*
* @return The minimum regular value.
*
* @see #getItem(int, int)
*/
@Override
public Number getMinRegularValue(Comparable rowKey, Comparable columnKey) {
Number result = null;
BoxAndWhiskerItem item = (BoxAndWhiskerItem) this.data.getObject(
rowKey, columnKey);
if (item != null) {
result = item.getMinRegularValue();
}
return result;
}
/**
* Returns the maximum regular (non outlier) value for an item.
*
* @param row the row index (zero-based).
* @param column the column index (zero-based).
*
* @return The maximum regular value.
*
* @see #getItem(int, int)
*/
@Override
public Number getMaxRegularValue(int row, int column) {
Number result = null;
BoxAndWhiskerItem item = (BoxAndWhiskerItem) this.data.getObject(
row, column);
if (item != null) {
result = item.getMaxRegularValue();
}
return result;
}
/**
* Returns the maximum regular (non outlier) value for an item.
*
* @param rowKey the row key.
* @param columnKey the column key.
*
* @return The maximum regular value.
*
* @see #getItem(int, int)
*/
@Override
public Number getMaxRegularValue(Comparable rowKey, Comparable columnKey) {
Number result = null;
BoxAndWhiskerItem item = (BoxAndWhiskerItem) this.data.getObject(
rowKey, columnKey);
if (item != null) {
result = item.getMaxRegularValue();
}
return result;
}
/**
* Returns the minimum outlier (non farout) value for an item.
*
* @param row the row index (zero-based).
* @param column the column index (zero-based).
*
* @return The minimum outlier.
*
* @see #getItem(int, int)
*/
@Override
public Number getMinOutlier(int row, int column) {
Number result = null;
BoxAndWhiskerItem item = (BoxAndWhiskerItem) this.data.getObject(
row, column);
if (item != null) {
result = item.getMinOutlier();
}
return result;
}
/**
* Returns the minimum outlier (non farout) value for an item.
*
* @param rowKey the row key.
* @param columnKey the column key.
*
* @return The minimum outlier.
*
* @see #getItem(int, int)
*/
@Override
public Number getMinOutlier(Comparable rowKey, Comparable columnKey) {
Number result = null;
BoxAndWhiskerItem item = (BoxAndWhiskerItem) this.data.getObject(
rowKey, columnKey);
if (item != null) {
result = item.getMinOutlier();
}
return result;
}
/**
* Returns the maximum outlier (non farout) value for an item.
*
* @param row the row index (zero-based).
* @param column the column index (zero-based).
*
* @return The maximum outlier.
*
* @see #getItem(int, int)
*/
@Override
public Number getMaxOutlier(int row, int column) {
Number result = null;
BoxAndWhiskerItem item = (BoxAndWhiskerItem) this.data.getObject(
row, column);
if (item != null) {
result = item.getMaxOutlier();
}
return result;
}
/**
* Returns the maximum outlier (non farout) value for an item.
*
* @param rowKey the row key.
* @param columnKey the column key.
*
* @return The maximum outlier.
*
* @see #getItem(int, int)
*/
@Override
public Number getMaxOutlier(Comparable rowKey, Comparable columnKey) {
Number result = null;
BoxAndWhiskerItem item = (BoxAndWhiskerItem) this.data.getObject(
rowKey, columnKey);
if (item != null) {
result = item.getMaxOutlier();
}
return result;
}
/**
* Returns a list of outlier values for an item.
*
* @param row the row index (zero-based).
* @param column the column index (zero-based).
*
* @return A list of outlier values.
*
* @see #getItem(int, int)
*/
@Override
public List<Number> getOutliers(int row, int column) {
List<Number> result = null;
BoxAndWhiskerItem item = (BoxAndWhiskerItem) this.data.getObject(
row, column);
if (item != null) {
result = item.getOutliers();
}
return result;
}
/**
* Returns a list of outlier values for an item.
*
* @param rowKey the row key.
* @param columnKey the column key.
*
* @return A list of outlier values.
*
* @see #getItem(int, int)
*/
@Override
public List<Number> getOutliers(Comparable rowKey, Comparable columnKey) {
List<Number> result = null;
BoxAndWhiskerItem item = (BoxAndWhiskerItem) this.data.getObject(
rowKey, columnKey);
if (item != null) {
result = item.getOutliers();
}
return result;
}
/**
* Resets the cached bounds, by iterating over the entire dataset to find
* the current bounds.
*/
private void updateBounds() {
this.minimumRangeValue = Double.NaN;
this.minimumRangeValueRow = -1;
this.minimumRangeValueColumn = -1;
this.maximumRangeValue = Double.NaN;
this.maximumRangeValueRow = -1;
this.maximumRangeValueColumn = -1;
int rowCount = getRowCount();
int columnCount = getColumnCount();
for (int r = 0; r < rowCount; r++) {
for (int c = 0; c < columnCount; c++) {
BoxAndWhiskerItem item = getItem(r, c);
if (item != null) {
Number min = item.getMinOutlier();
if (min != null) {
double minv = min.doubleValue();
if (!Double.isNaN(minv)) {
if (minv < this.minimumRangeValue || Double.isNaN(
this.minimumRangeValue)) {
this.minimumRangeValue = minv;
this.minimumRangeValueRow = r;
this.minimumRangeValueColumn = c;
}
}
}
Number max = item.getMaxOutlier();
if (max != null) {
double maxv = max.doubleValue();
if (!Double.isNaN(maxv)) {
if (maxv > this.maximumRangeValue || Double.isNaN(
this.maximumRangeValue)) {
this.maximumRangeValue = maxv;
this.maximumRangeValueRow = r;
this.maximumRangeValueColumn = c;
}
}
}
}
}
}
}
/**
* Tests this dataset 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 DefaultBoxAndWhiskerCategoryDataset) {
DefaultBoxAndWhiskerCategoryDataset dataset
= (DefaultBoxAndWhiskerCategoryDataset) obj;
return ObjectUtilities.equal(this.data, dataset.data);
}
return false;
}
/**
* Returns a clone of this dataset.
*
* @return A clone.
*
* @throws CloneNotSupportedException if cloning is not possible.
*/
@Override
public Object clone() throws CloneNotSupportedException {
DefaultBoxAndWhiskerCategoryDataset clone
= (DefaultBoxAndWhiskerCategoryDataset) super.clone();
clone.data = (KeyedObjects2D) this.data.clone();
return clone;
}
}
| 28,086 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
MultiValueCategoryDataset.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/data/statistics/MultiValueCategoryDataset.java | /* ===========================================================
* JFreeChart : a free chart library for the Java(tm) platform
* ===========================================================
*
* (C) Copyright 2000-2011, 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.]
*
* ------------------------------
* MultiValueCategoryDataset.java
* ------------------------------
* (C) Copyright 2007, 2008, by David Forslund and Contributors.
*
* Original Author: David Forslund;
* Contributor(s): David Gilbert (for Object Refinery Limited);
*
* Changes
* -------
* 08-Oct-2007 : Version 1, see patch 1780779 (DG);
*
*/
package org.jfree.data.statistics;
import java.util.List;
import org.jfree.data.category.CategoryDataset;
/**
* A category dataset that defines multiple values for each item.
*
* @since 1.0.7
*/
public interface MultiValueCategoryDataset extends CategoryDataset {
/**
* Returns a list (possibly empty) of the values for the specified item.
* The returned list should be unmodifiable.
*
* @param row the row index (zero-based).
* @param column the column index (zero-based).
*
* @return The list of values.
*/
public List<Number> getValues(int row, int column);
/**
* Returns a list (possibly empty) of the values for the specified item.
* The returned list should be unmodifiable.
*
* @param rowKey the row key (<code>null</code> not permitted).
* @param columnKey the column key (<code>null</code> not permitted).
*
* @return The list of values.
*/
public List<Number> getValues(Comparable rowKey, Comparable columnKey);
} | 2,616 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
DefaultBoxAndWhiskerXYDataset.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/data/statistics/DefaultBoxAndWhiskerXYDataset.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.]
*
* ----------------------------------
* DefaultBoxAndWhiskerXYDataset.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 (DG);
* 08-Aug-2003 : Minor changes to comments (DB)
* Allow average to be null - average is a perculiar AIMS
* requirement which probably should be stripped out and overlaid
* if required...
* Added a number of methods to allow the max and min non-outlier
* and non-farout values to be calculated
* 12-Aug-2003 Changed the getYValue to return the highest outlier value
* Added getters and setters for outlier and farout coefficients
* 27-Aug-2003 : Renamed DefaultBoxAndWhiskerDataset
* --> DefaultBoxAndWhiskerXYDataset (DG);
* 06-May-2004 : Now extends AbstractXYDataset (DG);
* 15-Jul-2004 : Switched getX() with getXValue() and getY() with
* getYValue() (DG);
* 18-Nov-2004 : Updated for changes in RangeInfo interface (DG);
* 11-Jan-2005 : Removed deprecated code in preparation for the 1.0.0
* release (DG);
* ------------- JFREECHART 1.0.x ---------------------------------------------
* 02-Feb-2007 : Removed author tags from all over JFreeChart sources (DG);
* 12-Nov-2007 : Implemented equals() and clone() (DG);
* 17-Jun-2012 : Removed JCommon dependencies (DG);
*
*/
package org.jfree.data.statistics;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.jfree.chart.util.ObjectUtilities;
import org.jfree.data.Range;
import org.jfree.data.RangeInfo;
import org.jfree.data.general.DatasetChangeEvent;
import org.jfree.data.xy.AbstractXYDataset;
/**
* A simple implementation of the {@link BoxAndWhiskerXYDataset} interface.
* This dataset implementation can hold only one series.
*/
public class DefaultBoxAndWhiskerXYDataset extends AbstractXYDataset
implements BoxAndWhiskerXYDataset, RangeInfo {
/** The series key. */
private Comparable seriesKey;
/** Storage for the dates. */
private List<Date> dates;
/** Storage for the box and whisker statistics. */
private List<BoxAndWhiskerItem> items;
/** The minimum range value. */
private Number minimumRangeValue;
/** The maximum range value. */
private Number maximumRangeValue;
/** The range of values. */
private Range rangeBounds;
/**
* The coefficient used to calculate outliers. Tukey's default value is
* 1.5 (see EDA) Any value which is greater than Q3 + (interquartile range
* * outlier coefficient) is considered to be an outlier. Can be altered
* if the data is particularly skewed.
*/
private double outlierCoefficient = 1.5;
/**
* The coefficient used to calculate farouts. Tukey's default value is 2
* (see EDA) Any value which is greater than Q3 + (interquartile range *
* farout coefficient) is considered to be a farout. Can be altered if the
* data is particularly skewed.
*/
private double faroutCoefficient = 2.0;
/**
* Constructs a new box and whisker dataset.
* <p>
* The current implementation allows only one series in the dataset.
* This may be extended in a future version.
*
* @param seriesKey the key for the series.
*/
public DefaultBoxAndWhiskerXYDataset(Comparable seriesKey) {
this.seriesKey = seriesKey;
this.dates = new ArrayList<Date>();
this.items = new ArrayList<BoxAndWhiskerItem>();
this.minimumRangeValue = null;
this.maximumRangeValue = null;
this.rangeBounds = null;
}
/**
* Returns the value used as the outlier coefficient. The outlier
* coefficient gives an indication of the degree of certainty in an
* unskewed distribution. Increasing the coefficient increases the number
* of values included. Currently only used to ensure farout coefficient is
* greater than the outlier coefficient
*
* @return A <code>double</code> representing the value used to calculate
* outliers.
*
* @see #setOutlierCoefficient(double)
*/
@Override
public double getOutlierCoefficient() {
return this.outlierCoefficient;
}
/**
* Sets the value used as the outlier coefficient
*
* @param outlierCoefficient being a <code>double</code> representing the
* value used to calculate outliers.
*
* @see #getOutlierCoefficient()
*/
public void setOutlierCoefficient(double outlierCoefficient) {
this.outlierCoefficient = outlierCoefficient;
}
/**
* Returns the value used as the farout coefficient. The farout coefficient
* allows the calculation of which values will be off the graph.
*
* @return A <code>double</code> representing the value used to calculate
* farouts.
*
* @see #setFaroutCoefficient(double)
*/
@Override
public double getFaroutCoefficient() {
return this.faroutCoefficient;
}
/**
* Sets the value used as the farouts coefficient. The farout coefficient
* must b greater than the outlier coefficient.
*
* @param faroutCoefficient being a <code>double</code> representing the
* value used to calculate farouts.
*
* @see #getFaroutCoefficient()
*/
public void setFaroutCoefficient(double faroutCoefficient) {
if (faroutCoefficient > getOutlierCoefficient()) {
this.faroutCoefficient = faroutCoefficient;
}
else {
throw new IllegalArgumentException("Farout value must be greater "
+ "than the outlier value, which is currently set at: ("
+ getOutlierCoefficient() + ")");
}
}
/**
* Returns the number of series in the dataset.
* <p>
* This implementation only allows one series.
*
* @return The number of series.
*/
@Override
public int getSeriesCount() {
return 1;
}
/**
* Returns the number of items in the specified series.
*
* @param series the index (zero-based) of the series.
*
* @return The number of items in the specified series.
*/
@Override
public int getItemCount(int series) {
return this.dates.size();
}
/**
* Adds an item to the dataset and sends a {@link DatasetChangeEvent} to
* all registered listeners.
*
* @param date the date (<code>null</code> not permitted).
* @param item the item (<code>null</code> not permitted).
*/
public void add(Date date, BoxAndWhiskerItem item) {
this.dates.add(date);
this.items.add(item);
if (this.minimumRangeValue == null) {
this.minimumRangeValue = item.getMinRegularValue();
}
else {
if (item.getMinRegularValue().doubleValue()
< this.minimumRangeValue.doubleValue()) {
this.minimumRangeValue = item.getMinRegularValue();
}
}
if (this.maximumRangeValue == null) {
this.maximumRangeValue = item.getMaxRegularValue();
}
else {
if (item.getMaxRegularValue().doubleValue()
> this.maximumRangeValue.doubleValue()) {
this.maximumRangeValue = item.getMaxRegularValue();
}
}
this.rangeBounds = new Range(this.minimumRangeValue.doubleValue(),
this.maximumRangeValue.doubleValue());
fireDatasetChanged();
}
/**
* Returns the name of the series stored in this dataset.
*
* @param i the index of the series. Currently ignored.
*
* @return The name of this series.
*/
@Override
public Comparable getSeriesKey(int i) {
return this.seriesKey;
}
/**
* Return an item from within the dataset.
*
* @param series the series index (ignored, since this dataset contains
* only one series).
* @param item the item within the series (zero-based index)
*
* @return The item.
*/
public BoxAndWhiskerItem getItem(int series, int item) {
return this.items.get(item);
}
/**
* Returns the x-value for one item in a series.
* <p>
* The value returned is a Long object generated from the underlying Date
* object.
*
* @param series the series (zero-based index).
* @param item the item (zero-based index).
*
* @return The x-value.
*/
@Override
public Number getX(int series, int item) {
return this.dates.get(item).getTime();
}
/**
* Returns the x-value for one item in a series, as a Date.
* <p>
* This method is provided for convenience only.
*
* @param series the series (zero-based index).
* @param item the item (zero-based index).
*
* @return The x-value as a Date.
*/
public Date getXDate(int series, int item) {
return this.dates.get(item);
}
/**
* Returns the y-value for one item in a series.
* <p>
* This method (from the XYDataset interface) is mapped to the
* getMeanValue() method.
*
* @param series the series (zero-based index).
* @param item the item (zero-based index).
*
* @return The y-value.
*/
@Override
public Number getY(int series, int item) {
return getMeanValue(series, item);
}
/**
* Returns the mean for the specified series and item.
*
* @param series the series (zero-based index).
* @param item the item (zero-based index).
*
* @return The mean for the specified series and item.
*/
@Override
public Number getMeanValue(int series, int item) {
Number result = null;
BoxAndWhiskerItem stats = this.items.get(item);
if (stats != null) {
result = stats.getMean();
}
return result;
}
/**
* Returns the median-value for the specified series and item.
*
* @param series the series (zero-based index).
* @param item the item (zero-based index).
*
* @return The median-value for the specified series and item.
*/
@Override
public Number getMedianValue(int series, int item) {
Number result = null;
BoxAndWhiskerItem stats = this.items.get(item);
if (stats != null) {
result = stats.getMedian();
}
return result;
}
/**
* Returns the Q1 median-value for the specified series and item.
*
* @param series the series (zero-based index).
* @param item the item (zero-based index).
*
* @return The Q1 median-value for the specified series and item.
*/
@Override
public Number getQ1Value(int series, int item) {
Number result = null;
BoxAndWhiskerItem stats = this.items.get(item);
if (stats != null) {
result = stats.getQ1();
}
return result;
}
/**
* Returns the Q3 median-value for the specified series and item.
*
* @param series the series (zero-based index).
* @param item the item (zero-based index).
*
* @return The Q3 median-value for the specified series and item.
*/
@Override
public Number getQ3Value(int series, int item) {
Number result = null;
BoxAndWhiskerItem stats = this.items.get(item);
if (stats != null) {
result = stats.getQ3();
}
return result;
}
/**
* Returns the min-value for the specified series and item.
*
* @param series the series (zero-based index).
* @param item the item (zero-based index).
*
* @return The min-value for the specified series and item.
*/
@Override
public Number getMinRegularValue(int series, int item) {
Number result = null;
BoxAndWhiskerItem stats = this.items.get(item);
if (stats != null) {
result = stats.getMinRegularValue();
}
return result;
}
/**
* Returns the max-value for the specified series and item.
*
* @param series the series (zero-based index).
* @param item the item (zero-based index).
*
* @return The max-value for the specified series and item.
*/
@Override
public Number getMaxRegularValue(int series, int item) {
Number result = null;
BoxAndWhiskerItem stats = this.items.get(item);
if (stats != null) {
result = stats.getMaxRegularValue();
}
return result;
}
/**
* Returns the minimum value which is not a farout.
* @param series the series (zero-based index).
* @param item the item (zero-based index).
*
* @return A <code>Number</code> representing the maximum non-farout value.
*/
@Override
public Number getMinOutlier(int series, int item) {
Number result = null;
BoxAndWhiskerItem stats = this.items.get(item);
if (stats != null) {
result = stats.getMinOutlier();
}
return result;
}
/**
* Returns the maximum value which is not a farout, ie Q3 + (interquartile
* range * farout coefficient).
*
* @param series the series (zero-based index).
* @param item the item (zero-based index).
*
* @return A <code>Number</code> representing the maximum non-farout value.
*/
@Override
public Number getMaxOutlier(int series, int item) {
Number result = null;
BoxAndWhiskerItem stats = this.items.get(item);
if (stats != null) {
result = stats.getMaxOutlier();
}
return result;
}
/**
* Returns a list of outliers for the specified series and item.
*
* @param series the series (zero-based index).
* @param item the item (zero-based index).
*
* @return The list of outliers for the specified series and item
* (possibly <code>null</code>).
*/
@Override
public List<Number> getOutliers(int series, int item) {
List<Number> result = null;
BoxAndWhiskerItem stats = this.items.get(item);
if (stats != null) {
result = stats.getOutliers();
}
return result;
}
/**
* Returns the minimum y-value in the dataset.
*
* @param includeInterval a flag that determines whether or not the
* y-interval is taken into account.
*
* @return The minimum value.
*/
@Override
public double getRangeLowerBound(boolean includeInterval) {
double result = Double.NaN;
if (this.minimumRangeValue != null) {
result = this.minimumRangeValue.doubleValue();
}
return result;
}
/**
* Returns the maximum y-value in the dataset.
*
* @param includeInterval a flag that determines whether or not the
* y-interval is taken into account.
*
* @return The maximum value.
*/
@Override
public double getRangeUpperBound(boolean includeInterval) {
double result = Double.NaN;
if (this.maximumRangeValue != null) {
result = this.maximumRangeValue.doubleValue();
}
return result;
}
/**
* Returns the range of the values in this dataset's range.
*
* @param includeInterval a flag that determines whether or not the
* y-interval is taken into account.
*
* @return The range.
*/
@Override
public Range getRangeBounds(boolean includeInterval) {
return this.rangeBounds;
}
/**
* Tests this dataset 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 DefaultBoxAndWhiskerXYDataset)) {
return false;
}
DefaultBoxAndWhiskerXYDataset that
= (DefaultBoxAndWhiskerXYDataset) obj;
if (!ObjectUtilities.equal(this.seriesKey, that.seriesKey)) {
return false;
}
if (!this.dates.equals(that.dates)) {
return false;
}
if (!this.items.equals(that.items)) {
return false;
}
return true;
}
/**
* Returns a clone of the plot.
*
* @return A clone.
*
* @throws CloneNotSupportedException if the cloning is not supported.
*/
@Override
public Object clone() throws CloneNotSupportedException {
DefaultBoxAndWhiskerXYDataset clone
= (DefaultBoxAndWhiskerXYDataset) super.clone();
clone.dates = new java.util.ArrayList<Date>(this.dates);
clone.items = new java.util.ArrayList<BoxAndWhiskerItem>(this.items);
return clone;
}
}
| 18,701 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
Regression.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/data/statistics/Regression.java | /* ===========================================================
* JFreeChart : a free chart library for the Java(tm) platform
* ===========================================================
*
* (C) Copyright 2000-2011, 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.]
*
* ---------------
* Regression.java
* ---------------
* (C) Copyright 2002-2009, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): Peter Kolb (patch 2795746);
*
* Changes
* -------
* 30-Sep-2002 : Version 1 (DG);
* 18-Aug-2003 : Added 'abstract' (DG);
* 15-Jul-2004 : Switched getX() with getXValue() and getY() with
* getYValue() (DG);
* 29-May-2009 : Added support for polynomial regression, see patch 2795746
* by Peter Kolb (DG);
*
*/
package org.jfree.data.statistics;
import org.jfree.data.xy.XYDataset;
/**
* A utility class for fitting regression curves to data.
*/
public abstract class Regression {
/**
* Returns the parameters 'a' and 'b' for an equation y = a + bx, fitted to
* the data using ordinary least squares regression. The result is
* returned as a double[], where result[0] --> a, and result[1] --> b.
*
* @param data the data.
*
* @return The parameters.
*/
public static double[] getOLSRegression(double[][] data) {
int n = data.length;
if (n < 2) {
throw new IllegalArgumentException("Not enough data.");
}
double sumX = 0;
double sumY = 0;
double sumXX = 0;
double sumXY = 0;
for (double[] aData : data) {
double x = aData[0];
double y = aData[1];
sumX += x;
sumY += y;
double xx = x * x;
sumXX += xx;
double xy = x * y;
sumXY += xy;
}
double sxx = sumXX - (sumX * sumX) / n;
double sxy = sumXY - (sumX * sumY) / n;
double xbar = sumX / n;
double ybar = sumY / n;
double[] result = new double[2];
result[1] = sxy / sxx;
result[0] = ybar - result[1] * xbar;
return result;
}
/**
* Returns the parameters 'a' and 'b' for an equation y = a + bx, fitted to
* the data using ordinary least squares regression. The result is returned
* as a double[], where result[0] --> a, and result[1] --> b.
*
* @param data the data.
* @param series the series (zero-based index).
*
* @return The parameters.
*/
public static double[] getOLSRegression(XYDataset data, int series) {
int n = data.getItemCount(series);
if (n < 2) {
throw new IllegalArgumentException("Not enough data.");
}
double sumX = 0;
double sumY = 0;
double sumXX = 0;
double sumXY = 0;
for (int i = 0; i < n; i++) {
double x = data.getXValue(series, i);
double y = data.getYValue(series, i);
sumX += x;
sumY += y;
double xx = x * x;
sumXX += xx;
double xy = x * y;
sumXY += xy;
}
double sxx = sumXX - (sumX * sumX) / n;
double sxy = sumXY - (sumX * sumY) / n;
double xbar = sumX / n;
double ybar = sumY / n;
double[] result = new double[2];
result[1] = sxy / sxx;
result[0] = ybar - result[1] * xbar;
return result;
}
/**
* Returns the parameters 'a' and 'b' for an equation y = ax^b, fitted to
* the data using a power regression equation. The result is returned as
* an array, where double[0] --> a, and double[1] --> b.
*
* @param data the data.
*
* @return The parameters.
*/
public static double[] getPowerRegression(double[][] data) {
int n = data.length;
if (n < 2) {
throw new IllegalArgumentException("Not enough data.");
}
double sumX = 0;
double sumY = 0;
double sumXX = 0;
double sumXY = 0;
for (double[] aData : data) {
double x = Math.log(aData[0]);
double y = Math.log(aData[1]);
sumX += x;
sumY += y;
double xx = x * x;
sumXX += xx;
double xy = x * y;
sumXY += xy;
}
double sxx = sumXX - (sumX * sumX) / n;
double sxy = sumXY - (sumX * sumY) / n;
double xbar = sumX / n;
double ybar = sumY / n;
double[] result = new double[2];
result[1] = sxy / sxx;
result[0] = Math.pow(Math.exp(1.0), ybar - result[1] * xbar);
return result;
}
/**
* Returns the parameters 'a' and 'b' for an equation y = ax^b, fitted to
* the data using a power regression equation. The result is returned as
* an array, where double[0] --> a, and double[1] --> b.
*
* @param data the data.
* @param series the series to fit the regression line against.
*
* @return The parameters.
*/
public static double[] getPowerRegression(XYDataset data, int series) {
int n = data.getItemCount(series);
if (n < 2) {
throw new IllegalArgumentException("Not enough data.");
}
double sumX = 0;
double sumY = 0;
double sumXX = 0;
double sumXY = 0;
for (int i = 0; i < n; i++) {
double x = Math.log(data.getXValue(series, i));
double y = Math.log(data.getYValue(series, i));
sumX += x;
sumY += y;
double xx = x * x;
sumXX += xx;
double xy = x * y;
sumXY += xy;
}
double sxx = sumXX - (sumX * sumX) / n;
double sxy = sumXY - (sumX * sumY) / n;
double xbar = sumX / n;
double ybar = sumY / n;
double[] result = new double[2];
result[1] = sxy / sxx;
result[0] = Math.pow(Math.exp(1.0), ybar - result[1] * xbar);
return result;
}
/**
* Returns the parameters 'a0', 'a1', 'a2', ..., 'an' for a polynomial
* function of order n, y = a0 + a1 * x + a2 * x^2 + ... + an * x^n,
* fitted to the data using a polynomial regression equation.
* The result is returned as an array with a length of n + 2,
* where double[0] --> a0, double[1] --> a1, .., double[n] --> an.
* and double[n + 1] is the correlation coefficient R2
* Reference: J. D. Faires, R. L. Burden, Numerische Methoden (german
* edition), pp. 243ff and 327ff.
*
* @param dataset the dataset (<code>null</code> not permitted).
* @param series the series to fit the regression line against (the series
* must have at least order + 1 non-NaN items).
* @param order the order of the function (> 0).
*
* @return The parameters.
*
* @since 1.0.14
*/
public static double[] getPolynomialRegression(XYDataset dataset, int series, int order) {
if (dataset == null) {
throw new IllegalArgumentException("Null 'dataset' argument.");
}
int itemCount = dataset.getItemCount(series);
if (itemCount < order + 1) {
throw new IllegalArgumentException("Not enough data.");
}
int validItems = 0;
double[][] data = new double[2][itemCount];
for(int item = 0; item < itemCount; item++){
double x = dataset.getXValue(series, item);
double y = dataset.getYValue(series, item);
if (!Double.isNaN(x) && !Double.isNaN(y)){
data[0][validItems] = x;
data[1][validItems] = y;
validItems++;
}
}
if (validItems < order + 1) {
throw new IllegalArgumentException("Not enough data.");
}
int equations = order + 1;
int coefficients = order + 2;
double[] result = new double[equations + 1];
double[][] matrix = new double[equations][coefficients];
double sumX = 0.0;
double sumY = 0.0;
for(int item = 0; item < validItems; item++){
sumX += data[0][item];
sumY += data[1][item];
for(int eq = 0; eq < equations; eq++){
for(int coe = 0; coe < coefficients - 1; coe++){
matrix[eq][coe] += Math.pow(data[0][item],eq + coe);
}
matrix[eq][coefficients - 1] += data[1][item]
* Math.pow(data[0][item],eq);
}
}
double[][] subMatrix = calculateSubMatrix(matrix);
for (int eq = 1; eq < equations; eq++) {
matrix[eq][0] = 0;
for (int coe = 1; coe < coefficients; coe++) {
matrix[eq][coe] = subMatrix[eq - 1][coe - 1];
}
}
for (int eq = equations - 1; eq > -1; eq--) {
double value = matrix[eq][coefficients - 1];
for (int coe = eq; coe < coefficients -1; coe++) {
value -= matrix[eq][coe] * result[coe];
}
result[eq] = value / matrix[eq][eq];
}
double meanY = sumY / validItems;
double yObsSquare = 0.0;
double yRegSquare = 0.0;
for (int item = 0; item < validItems; item++) {
double yCalc = 0;
for (int eq = 0; eq < equations; eq++) {
yCalc += result[eq] * Math.pow(data[0][item],eq);
}
yRegSquare += Math.pow(yCalc - meanY, 2);
yObsSquare += Math.pow(data[1][item] - meanY, 2);
}
double rSquare = yRegSquare / yObsSquare;
result[equations] = rSquare;
return result;
}
/**
* Returns a matrix with the following features: (1) the number of rows
* and columns is 1 less than that of the original matrix; (2)the matrix
* is triangular, i.e. all elements a (row, column) with column > row are
* zero. This method is used for calculating a polynomial regression.
*
* @param matrix the start matrix.
*
* @return The new matrix.
*/
private static double[][] calculateSubMatrix(double[][] matrix){
int equations = matrix.length;
int coefficients = matrix[0].length;
double[][] result = new double[equations - 1][coefficients - 1];
for (int eq = 1; eq < equations; eq++) {
double factor = matrix[0][0] / matrix[eq][0];
for (int coe = 1; coe < coefficients; coe++) {
result[eq - 1][coe -1] = matrix[0][coe] - matrix[eq][coe]
* factor;
}
}
if (equations == 1) {
return result;
}
// check for zero pivot element
if (result[0][0] == 0) {
boolean found = false;
for (int i = 0; i < result.length; i ++) {
if (result[i][0] != 0) {
found = true;
double[] temp = result[0];
System.arraycopy(result[i], 0, result[0], 0, result[i].length);
System.arraycopy(temp, 0, result[i], 0, temp.length);
break;
}
}
if (!found) {
return new double[equations - 1][coefficients - 1];
}
}
double[][] subMatrix = calculateSubMatrix(result);
for (int eq = 1; eq < equations - 1; eq++) {
result[eq][0] = 0;
for (int coe = 1; coe < coefficients - 1; coe++) {
result[eq][coe] = subMatrix[eq - 1][coe - 1];
}
}
return result;
}
}
| 12,670 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
DefaultStatisticalCategoryDataset.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/data/statistics/DefaultStatisticalCategoryDataset.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.]
*
* --------------------------------------
* DefaultStatisticalCategoryDataset.java
* --------------------------------------
* (C) Copyright 2002-2012, by Pascal Collet and Contributors.
*
* Original Author: Pascal Collet;
* Contributor(s): David Gilbert (for Object Refinery Limited);
*
* Changes
* -------
* 21-Aug-2002 : Version 1, contributed by Pascal Collet (DG);
* 07-Oct-2002 : Fixed errors reported by Checkstyle (DG);
* 05-Feb-2003 : Revised implementation to use KeyedObjects2D (DG);
* 28-Aug-2003 : Moved from org.jfree.data --> org.jfree.data.statistics (DG);
* 06-Oct-2003 : Removed incorrect Javadoc text (DG);
* 18-Nov-2004 : Updated for changes in RangeInfo interface (DG);
* 11-Jan-2005 : Removed deprecated code in preparation for the 1.0.0
* release (DG);
* 01-Feb-2005 : Changed minimumRangeValue and maximumRangeValue from Double
* to double (DG);
* 05-Feb-2005 : Implemented equals() method (DG);
* ------------- JFREECHART 1.0.x ---------------------------------------------
* 08-Aug-2006 : Reworked implementation of RangeInfo methods (DG);
* 02-Feb-2007 : Removed author tags from all over JFreeChart sources (DG);
* 28-Sep-2007 : Fixed cloning bug (DG);
* 02-Oct-2007 : Fixed bug updating cached range values (DG);
* 19-May-2009 : Fixed FindBugs warnings, patch by Michal Wozniak (DG);
* 20-Oct-2011 : Fixed getRangeBounds() bug 3072674 (DG);
* 17-Jun-2012 : Removed JCommon dependencies (DG);
*
*/
package org.jfree.data.statistics;
import java.util.List;
import org.jfree.chart.util.PublicCloneable;
import org.jfree.data.KeyedObjects2D;
import org.jfree.data.Range;
import org.jfree.data.RangeInfo;
import org.jfree.data.general.AbstractDataset;
import org.jfree.data.general.DatasetChangeEvent;
/**
* A convenience class that provides a default implementation of the
* {@link StatisticalCategoryDataset} interface.
*/
public class DefaultStatisticalCategoryDataset extends AbstractDataset
implements StatisticalCategoryDataset, RangeInfo, PublicCloneable {
/** Storage for the data. */
private KeyedObjects2D data;
/** The minimum range value. */
private double minimumRangeValue;
/** The row index for the minimum range value. */
private int minimumRangeValueRow;
/** The column index for the minimum range value. */
private int minimumRangeValueColumn;
/** The minimum range value including the standard deviation. */
private double minimumRangeValueIncStdDev;
/**
* The row index for the minimum range value (including the standard
* deviation).
*/
private int minimumRangeValueIncStdDevRow;
/**
* The column index for the minimum range value (including the standard
* deviation).
*/
private int minimumRangeValueIncStdDevColumn;
/** The maximum range value. */
private double maximumRangeValue;
/** The row index for the maximum range value. */
private int maximumRangeValueRow;
/** The column index for the maximum range value. */
private int maximumRangeValueColumn;
/** The maximum range value including the standard deviation. */
private double maximumRangeValueIncStdDev;
/**
* The row index for the maximum range value (including the standard
* deviation).
*/
private int maximumRangeValueIncStdDevRow;
/**
* The column index for the maximum range value (including the standard
* deviation).
*/
private int maximumRangeValueIncStdDevColumn;
/**
* Creates a new dataset.
*/
public DefaultStatisticalCategoryDataset() {
this.data = new KeyedObjects2D();
this.minimumRangeValue = Double.NaN;
this.minimumRangeValueRow = -1;
this.minimumRangeValueColumn = -1;
this.maximumRangeValue = Double.NaN;
this.maximumRangeValueRow = -1;
this.maximumRangeValueColumn = -1;
this.minimumRangeValueIncStdDev = Double.NaN;
this.minimumRangeValueIncStdDevRow = -1;
this.minimumRangeValueIncStdDevColumn = -1;
this.maximumRangeValueIncStdDev = Double.NaN;
this.maximumRangeValueIncStdDevRow = -1;
this.maximumRangeValueIncStdDevColumn = -1;
}
/**
* Returns the mean value for an item.
*
* @param row the row index (zero-based).
* @param column the column index (zero-based).
*
* @return The mean value (possibly <code>null</code>).
*/
@Override
public Number getMeanValue(int row, int column) {
Number result = null;
MeanAndStandardDeviation masd = (MeanAndStandardDeviation)
this.data.getObject(row, column);
if (masd != null) {
result = masd.getMean();
}
return result;
}
/**
* Returns the value for an item (for this dataset, the mean value is
* returned).
*
* @param row the row index.
* @param column the column index.
*
* @return The value (possibly <code>null</code>).
*/
@Override
public Number getValue(int row, int column) {
return getMeanValue(row, column);
}
/**
* Returns the value for an item (for this dataset, the mean value is
* returned).
*
* @param rowKey the row key.
* @param columnKey the columnKey.
*
* @return The value (possibly <code>null</code>).
*/
@Override
public Number getValue(Comparable rowKey, Comparable columnKey) {
return getMeanValue(rowKey, columnKey);
}
/**
* Returns the mean value for an item.
*
* @param rowKey the row key.
* @param columnKey the columnKey.
*
* @return The mean value (possibly <code>null</code>).
*/
@Override
public Number getMeanValue(Comparable rowKey, Comparable columnKey) {
Number result = null;
MeanAndStandardDeviation masd = (MeanAndStandardDeviation)
this.data.getObject(rowKey, columnKey);
if (masd != null) {
result = masd.getMean();
}
return result;
}
/**
* Returns the standard deviation value for an item.
*
* @param row the row index (zero-based).
* @param column the column index (zero-based).
*
* @return The standard deviation (possibly <code>null</code>).
*/
@Override
public Number getStdDevValue(int row, int column) {
Number result = null;
MeanAndStandardDeviation masd = (MeanAndStandardDeviation)
this.data.getObject(row, column);
if (masd != null) {
result = masd.getStandardDeviation();
}
return result;
}
/**
* Returns the standard deviation value for an item.
*
* @param rowKey the row key.
* @param columnKey the columnKey.
*
* @return The standard deviation (possibly <code>null</code>).
*/
@Override
public Number getStdDevValue(Comparable rowKey, Comparable columnKey) {
Number result = null;
MeanAndStandardDeviation masd = (MeanAndStandardDeviation)
this.data.getObject(rowKey, columnKey);
if (masd != null) {
result = masd.getStandardDeviation();
}
return result;
}
/**
* Returns the column index for a given key.
*
* @param key the column key (<code>null</code> not permitted).
*
* @return The column index.
*/
@Override
public int getColumnIndex(Comparable key) {
// defer null argument check
return this.data.getColumnIndex(key);
}
/**
* Returns a column key.
*
* @param column the column index (zero-based).
*
* @return The column key.
*/
@Override
public Comparable getColumnKey(int column) {
return this.data.getColumnKey(column);
}
/**
* Returns the column keys.
*
* @return The keys.
*/
@Override
public List<Comparable> getColumnKeys() {
return this.data.getColumnKeys();
}
/**
* Returns the row index for a given key.
*
* @param key the row key (<code>null</code> not permitted).
*
* @return The row index.
*/
@Override
public int getRowIndex(Comparable key) {
// defer null argument check
return this.data.getRowIndex(key);
}
/**
* Returns a row key.
*
* @param row the row index (zero-based).
*
* @return The row key.
*/
@Override
public Comparable getRowKey(int row) {
return this.data.getRowKey(row);
}
/**
* Returns the row keys.
*
* @return The keys.
*/
@Override
public List<Comparable> getRowKeys() {
return this.data.getRowKeys();
}
/**
* Returns the number of rows in the table.
*
* @return The row count.
*
* @see #getColumnCount()
*/
@Override
public int getRowCount() {
return this.data.getRowCount();
}
/**
* Returns the number of columns in the table.
*
* @return The column count.
*
* @see #getRowCount()
*/
@Override
public int getColumnCount() {
return this.data.getColumnCount();
}
/**
* Adds a mean and standard deviation to the table.
*
* @param mean the mean.
* @param standardDeviation the standard deviation.
* @param rowKey the row key.
* @param columnKey the column key.
*/
public void add(double mean, double standardDeviation,
Comparable rowKey, Comparable columnKey) {
add(new Double(mean), new Double(standardDeviation), rowKey, columnKey);
}
/**
* Adds a mean and standard deviation to the table.
*
* @param mean the mean.
* @param standardDeviation the standard deviation.
* @param rowKey the row key.
* @param columnKey the column key.
*/
public void add(Number mean, Number standardDeviation,
Comparable rowKey, Comparable columnKey) {
MeanAndStandardDeviation item = new MeanAndStandardDeviation(
mean, standardDeviation);
this.data.addObject(item, rowKey, columnKey);
double m = Double.NaN;
double sd = Double.NaN;
if (mean != null) {
m = mean.doubleValue();
}
if (standardDeviation != null) {
sd = standardDeviation.doubleValue();
}
// update cached range values
int r = this.data.getColumnIndex(columnKey);
int c = this.data.getRowIndex(rowKey);
if ((r == this.maximumRangeValueRow && c
== this.maximumRangeValueColumn) || (r
== this.maximumRangeValueIncStdDevRow && c
== this.maximumRangeValueIncStdDevColumn) || (r
== this.minimumRangeValueRow && c
== this.minimumRangeValueColumn) || (r
== this.minimumRangeValueIncStdDevRow && c
== this.minimumRangeValueIncStdDevColumn)) {
// iterate over all data items and update mins and maxes
updateBounds();
}
else {
if (!Double.isNaN(m)) {
if (Double.isNaN(this.maximumRangeValue)
|| m > this.maximumRangeValue) {
this.maximumRangeValue = m;
this.maximumRangeValueRow = r;
this.maximumRangeValueColumn = c;
}
}
if (!Double.isNaN(m + sd)) {
if (Double.isNaN(this.maximumRangeValueIncStdDev)
|| (m + sd) > this.maximumRangeValueIncStdDev) {
this.maximumRangeValueIncStdDev = m + sd;
this.maximumRangeValueIncStdDevRow = r;
this.maximumRangeValueIncStdDevColumn = c;
}
}
if (!Double.isNaN(m)) {
if (Double.isNaN(this.minimumRangeValue)
|| m < this.minimumRangeValue) {
this.minimumRangeValue = m;
this.minimumRangeValueRow = r;
this.minimumRangeValueColumn = c;
}
}
if (!Double.isNaN(m - sd)) {
if (Double.isNaN(this.minimumRangeValueIncStdDev)
|| (m - sd) < this.minimumRangeValueIncStdDev) {
this.minimumRangeValueIncStdDev = m - sd;
this.minimumRangeValueIncStdDevRow = r;
this.minimumRangeValueIncStdDevColumn = c;
}
}
}
fireDatasetChanged();
}
/**
* Removes an item from the dataset and sends a {@link DatasetChangeEvent}
* to all registered listeners.
*
* @param rowKey the row key (<code>null</code> not permitted).
* @param columnKey the column key (<code>null</code> not permitted).
*
* @see #add(double, double, Comparable, Comparable)
*
* @since 1.0.7
*/
public void remove(Comparable rowKey, Comparable columnKey) {
// defer null argument checks
int r = getRowIndex(rowKey);
int c = getColumnIndex(columnKey);
this.data.removeObject(rowKey, columnKey);
// if this cell held a maximum and/or minimum value, we'll need to
// update the cached bounds...
if ((r == this.maximumRangeValueRow && c
== this.maximumRangeValueColumn) || (r
== this.maximumRangeValueIncStdDevRow && c
== this.maximumRangeValueIncStdDevColumn) || (r
== this.minimumRangeValueRow && c
== this.minimumRangeValueColumn) || (r
== this.minimumRangeValueIncStdDevRow && c
== this.minimumRangeValueIncStdDevColumn)) {
// iterate over all data items and update mins and maxes
updateBounds();
}
fireDatasetChanged();
}
/**
* Removes a row from the dataset and sends a {@link DatasetChangeEvent}
* to all registered listeners.
*
* @param rowIndex the row index.
*
* @see #removeColumn(int)
*
* @since 1.0.7
*/
public void removeRow(int rowIndex) {
this.data.removeRow(rowIndex);
updateBounds();
fireDatasetChanged();
}
/**
* Removes a row from the dataset and sends a {@link DatasetChangeEvent}
* to all registered listeners.
*
* @param rowKey the row key (<code>null</code> not permitted).
*
* @see #removeColumn(Comparable)
*
* @since 1.0.7
*/
public void removeRow(Comparable rowKey) {
this.data.removeRow(rowKey);
updateBounds();
fireDatasetChanged();
}
/**
* Removes a column from the dataset and sends a {@link DatasetChangeEvent}
* to all registered listeners.
*
* @param columnIndex the column index.
*
* @see #removeRow(int)
*
* @since 1.0.7
*/
public void removeColumn(int columnIndex) {
this.data.removeColumn(columnIndex);
updateBounds();
fireDatasetChanged();
}
/**
* Removes a column from the dataset and sends a {@link DatasetChangeEvent}
* to all registered listeners.
*
* @param columnKey the column key (<code>null</code> not permitted).
*
* @see #removeRow(Comparable)
*
* @since 1.0.7
*/
public void removeColumn(Comparable columnKey) {
this.data.removeColumn(columnKey);
updateBounds();
fireDatasetChanged();
}
/**
* Clears all data from the dataset and sends a {@link DatasetChangeEvent}
* to all registered listeners.
*
* @since 1.0.7
*/
public void clear() {
this.data.clear();
updateBounds();
fireDatasetChanged();
}
/**
* Iterate over all the data items and update the cached bound values.
*/
private void updateBounds() {
this.maximumRangeValue = Double.NaN;
this.maximumRangeValueRow = -1;
this.maximumRangeValueColumn = -1;
this.minimumRangeValue = Double.NaN;
this.minimumRangeValueRow = -1;
this.minimumRangeValueColumn = -1;
this.maximumRangeValueIncStdDev = Double.NaN;
this.maximumRangeValueIncStdDevRow = -1;
this.maximumRangeValueIncStdDevColumn = -1;
this.minimumRangeValueIncStdDev = Double.NaN;
this.minimumRangeValueIncStdDevRow = -1;
this.minimumRangeValueIncStdDevColumn = -1;
int rowCount = this.data.getRowCount();
int columnCount = this.data.getColumnCount();
for (int r = 0; r < rowCount; r++) {
for (int c = 0; c < columnCount; c++) {
MeanAndStandardDeviation masd = (MeanAndStandardDeviation)
this.data.getObject(r, c);
if (masd == null) {
continue;
}
double m = masd.getMeanValue();
double sd = masd.getStandardDeviationValue();
if (!Double.isNaN(m)) {
// update the max value
if (Double.isNaN(this.maximumRangeValue)) {
this.maximumRangeValue = m;
this.maximumRangeValueRow = r;
this.maximumRangeValueColumn = c;
}
else {
if (m > this.maximumRangeValue) {
this.maximumRangeValue = m;
this.maximumRangeValueRow = r;
this.maximumRangeValueColumn = c;
}
}
// update the min value
if (Double.isNaN(this.minimumRangeValue)) {
this.minimumRangeValue = m;
this.minimumRangeValueRow = r;
this.minimumRangeValueColumn = c;
}
else {
if (m < this.minimumRangeValue) {
this.minimumRangeValue = m;
this.minimumRangeValueRow = r;
this.minimumRangeValueColumn = c;
}
}
if (!Double.isNaN(sd)) {
// update the max value
if (Double.isNaN(this.maximumRangeValueIncStdDev)) {
this.maximumRangeValueIncStdDev = m + sd;
this.maximumRangeValueIncStdDevRow = r;
this.maximumRangeValueIncStdDevColumn = c;
}
else {
if (m + sd > this.maximumRangeValueIncStdDev) {
this.maximumRangeValueIncStdDev = m + sd;
this.maximumRangeValueIncStdDevRow = r;
this.maximumRangeValueIncStdDevColumn = c;
}
}
// update the min value
if (Double.isNaN(this.minimumRangeValueIncStdDev)) {
this.minimumRangeValueIncStdDev = m - sd;
this.minimumRangeValueIncStdDevRow = r;
this.minimumRangeValueIncStdDevColumn = c;
}
else {
if (m - sd < this.minimumRangeValueIncStdDev) {
this.minimumRangeValueIncStdDev = m - sd;
this.minimumRangeValueIncStdDevRow = r;
this.minimumRangeValueIncStdDevColumn = c;
}
}
}
}
}
}
}
/**
* Returns the minimum y-value in the dataset.
*
* @param includeInterval a flag that determines whether or not the
* y-interval is taken into account.
*
* @return The minimum value.
*
* @see #getRangeUpperBound(boolean)
*/
@Override
public double getRangeLowerBound(boolean includeInterval) {
if (includeInterval && !Double.isNaN(this.minimumRangeValueIncStdDev)) {
return this.minimumRangeValueIncStdDev;
}
else {
return this.minimumRangeValue;
}
}
/**
* Returns the maximum y-value in the dataset.
*
* @param includeInterval a flag that determines whether or not the
* y-interval is taken into account.
*
* @return The maximum value.
*
* @see #getRangeLowerBound(boolean)
*/
@Override
public double getRangeUpperBound(boolean includeInterval) {
if (includeInterval && !Double.isNaN(this.maximumRangeValueIncStdDev)) {
return this.maximumRangeValueIncStdDev;
}
else {
return this.maximumRangeValue;
}
}
/**
* Returns the bounds of the values in this dataset's y-values.
*
* @param includeInterval a flag that determines whether or not the
* y-interval is taken into account.
*
* @return The range.
*/
@Override
public Range getRangeBounds(boolean includeInterval) {
double lower = getRangeLowerBound(includeInterval);
double upper = getRangeUpperBound(includeInterval);
if (Double.isNaN(lower) && Double.isNaN(upper)) {
return null;
}
return new Range(lower, upper);
}
/**
* 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 DefaultStatisticalCategoryDataset)) {
return false;
}
DefaultStatisticalCategoryDataset that
= (DefaultStatisticalCategoryDataset) obj;
if (!this.data.equals(that.data)) {
return false;
}
return true;
}
/**
* Returns a clone of this dataset.
*
* @return A clone of this dataset.
*
* @throws CloneNotSupportedException if cloning cannot be completed.
*/
@Override
public Object clone() throws CloneNotSupportedException {
DefaultStatisticalCategoryDataset clone
= (DefaultStatisticalCategoryDataset) super.clone();
clone.data = (KeyedObjects2D) this.data.clone();
return clone;
}
}
| 24,122 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
StatisticalCategoryDataset.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/data/statistics/StatisticalCategoryDataset.java | /* ===========================================================
* JFreeChart : a free chart library for the Java(tm) platform
* ===========================================================
*
* (C) Copyright 2000-2011, 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.]
*
* -------------------------------
* StatisticalCategoryDataset.java
* -------------------------------
* (C) Copyright 2002-2009, by Pascal Collet and Contributors.
*
* Original Author: Pascal Collet;
* Contributor(s): David Gilbert (for Object Refinery Limited);
*
* Changes
* -------
* 21-Aug-2002 : Version 1, contributed by Pascal Collet (DG);
* 07-Oct-2002 : Fixed errors reported by Checkstyle (DG);
* 24-Oct-2002 : Amendments in line with changes to the CategoryDataset
* interface (DG);
* ------------- JFREECHART 1.0.x ---------------------------------------------
* 02-Feb-2007 : Removed author tags from all over JFreeChart sources (DG);
*
*/
package org.jfree.data.statistics;
import org.jfree.data.category.CategoryDataset;
/**
* A category dataset that defines a mean and standard deviation value for
* each item.
*/
public interface StatisticalCategoryDataset extends CategoryDataset {
/**
* Returns the mean value for an item.
*
* @param row the row index (zero-based).
* @param column the column index (zero-based).
*
* @return The mean value (possibly <code>null</code>).
*/
public Number getMeanValue(int row, int column);
/**
* Returns the mean value for an item.
*
* @param rowKey the row key.
* @param columnKey the columnKey.
*
* @return The mean value (possibly <code>null</code>).
*/
public Number getMeanValue(Comparable rowKey, Comparable columnKey);
/**
* Returns the standard deviation value for an item.
*
* @param row the row index (zero-based).
* @param column the column index (zero-based).
*
* @return The standard deviation (possibly <code>null</code>).
*/
public Number getStdDevValue(int row, int column);
/**
* Returns the standard deviation value for an item.
*
* @param rowKey the row key.
* @param columnKey the columnKey.
*
* @return The standard deviation (possibly <code>null</code>).
*/
public Number getStdDevValue(Comparable rowKey, Comparable columnKey);
}
| 3,355 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
SimpleHistogramDataset.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/data/statistics/SimpleHistogramDataset.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.]
*
* ---------------------------
* SimpleHistogramDataset.java
* ---------------------------
* (C) Copyright 2005-2012, by Object Refinery Limited and Contributors.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): Sergei Ivanov;
*
* Changes
* -------
* 10-Jan-2005 : Version 1 (DG);
* 21-May-2007 : Added clearObservations() and removeAllBins() (SI);
* 10-Jul-2007 : Added null argument check to constructor (DG);
* 17-Jun-2012 : Removed JCommon dependencies (DG);
*
*/
package org.jfree.data.statistics;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.jfree.chart.util.ObjectUtilities;
import org.jfree.chart.util.PublicCloneable;
import org.jfree.data.DomainOrder;
import org.jfree.data.general.DatasetChangeEvent;
import org.jfree.data.xy.AbstractIntervalXYDataset;
import org.jfree.data.xy.IntervalXYDataset;
/**
* A dataset used for creating simple histograms with custom defined bins.
*
* @see HistogramDataset
*/
public class SimpleHistogramDataset extends AbstractIntervalXYDataset
implements IntervalXYDataset, Cloneable, PublicCloneable,
Serializable {
/** For serialization. */
private static final long serialVersionUID = 7997996479768018443L;
/** The series key. */
private Comparable key;
/** The bins. */
private List<SimpleHistogramBin> bins;
/**
* A flag that controls whether or not the bin count is divided by the
* bin size.
*/
private boolean adjustForBinSize;
/**
* Creates a new histogram dataset. Note that the
* <code>adjustForBinSize</code> flag defaults to <code>true</code>.
*
* @param key the series key (<code>null</code> not permitted).
*/
public SimpleHistogramDataset(Comparable key) {
if (key == null) {
throw new IllegalArgumentException("Null 'key' argument.");
}
this.key = key;
this.bins = new ArrayList<SimpleHistogramBin>();
this.adjustForBinSize = true;
}
/**
* Returns a flag that controls whether or not the bin count is divided by
* the bin size in the {@link #getXValue(int, int)} method.
*
* @return A boolean.
*
* @see #setAdjustForBinSize(boolean)
*/
public boolean getAdjustForBinSize() {
return this.adjustForBinSize;
}
/**
* Sets the flag that controls whether or not the bin count is divided by
* the bin size in the {@link #getYValue(int, int)} method, and sends a
* {@link DatasetChangeEvent} to all registered listeners.
*
* @param adjust the flag.
*
* @see #getAdjustForBinSize()
*/
public void setAdjustForBinSize(boolean adjust) {
this.adjustForBinSize = adjust;
notifyListeners(new DatasetChangeEvent(this, this));
}
/**
* Returns the number of series in the dataset (always 1 for this dataset).
*
* @return The series count.
*/
@Override
public int getSeriesCount() {
return 1;
}
/**
* Returns the key for a series. Since this dataset only stores a single
* series, the <code>series</code> argument is ignored.
*
* @param series the series (zero-based index, ignored in this dataset).
*
* @return The key for the series.
*/
@Override
public Comparable getSeriesKey(int series) {
return this.key;
}
/**
* Returns the order of the domain (or X) values returned by the dataset.
*
* @return The order (never <code>null</code>).
*/
@Override
public DomainOrder getDomainOrder() {
return DomainOrder.ASCENDING;
}
/**
* Returns the number of items in a series. Since this dataset only stores
* a single series, the <code>series</code> argument is ignored.
*
* @param series the series index (zero-based, ignored in this dataset).
*
* @return The item count.
*/
@Override
public int getItemCount(int series) {
return this.bins.size();
}
/**
* Adds a bin to the dataset. An exception is thrown if the bin overlaps
* with any existing bin in the dataset.
*
* @param bin the bin (<code>null</code> not permitted).
*
* @see #removeAllBins()
*/
public void addBin(SimpleHistogramBin bin) {
// check that the new bin doesn't overlap with any existing bin
for (SimpleHistogramBin existingBin : this.bins) {
if (bin.overlapsWith(existingBin)) {
throw new RuntimeException("Overlapping bin");
}
}
this.bins.add(bin);
Collections.sort(this.bins);
}
/**
* Adds an observation to the dataset (by incrementing the item count for
* the appropriate bin). A runtime exception is thrown if the value does
* not fit into any bin.
*
* @param value the value.
*/
public void addObservation(double value) {
addObservation(value, true);
}
/**
* Adds an observation to the dataset (by incrementing the item count for
* the appropriate bin). A runtime exception is thrown if the value does
* not fit into any bin.
*
* @param value the value.
* @param notify send {@link DatasetChangeEvent} to listeners?
*/
public void addObservation(double value, boolean notify) {
boolean placed = false;
for (SimpleHistogramBin bin : this.bins) {
if (bin.accepts(value)) {
bin.setItemCount(bin.getItemCount() + 1);
placed = true;
break;
}
}
if (!placed) {
throw new RuntimeException("No bin.");
}
if (notify) {
notifyListeners(new DatasetChangeEvent(this, this));
}
}
/**
* Adds a set of values to the dataset and sends a
* {@link DatasetChangeEvent} to all registered listeners.
*
* @param values the values (<code>null</code> not permitted).
*
* @see #clearObservations()
*/
public void addObservations(double[] values) {
for (double value : values) {
addObservation(value, false);
}
notifyListeners(new DatasetChangeEvent(this, this));
}
/**
* Removes all current observation data and sends a
* {@link DatasetChangeEvent} to all registered listeners.
*
* @since 1.0.6
*
* @see #addObservations(double[])
* @see #removeAllBins()
*/
public void clearObservations() {
for (SimpleHistogramBin bin : this.bins) {
bin.setItemCount(0);
}
notifyListeners(new DatasetChangeEvent(this, this));
}
/**
* Removes all bins and sends a {@link DatasetChangeEvent} to all
* registered listeners.
*
* @since 1.0.6
*
* @see #addBin(SimpleHistogramBin)
*/
public void removeAllBins() {
this.bins = new ArrayList<SimpleHistogramBin>();
notifyListeners(new DatasetChangeEvent(this, this));
}
/**
* Returns the x-value for an item within a series. The x-values may or
* may not be returned in ascending order, that is up to the class
* implementing the interface.
*
* @param series the series index (zero-based).
* @param item the item index (zero-based).
*
* @return The x-value (never <code>null</code>).
*/
@Override
public Number getX(int series, int item) {
return getXValue(series, item);
}
/**
* Returns the x-value (as a double primitive) for an item within a series.
*
* @param series the series index (zero-based).
* @param item the item index (zero-based).
*
* @return The x-value.
*/
@Override
public double getXValue(int series, int item) {
SimpleHistogramBin bin = this.bins.get(item);
return (bin.getLowerBound() + bin.getUpperBound()) / 2.0;
}
/**
* Returns the y-value for an item within a series.
*
* @param series the series index (zero-based).
* @param item the item index (zero-based).
*
* @return The y-value (possibly <code>null</code>).
*/
@Override
public Number getY(int series, int item) {
return getYValue(series, item);
}
/**
* Returns the y-value (as a double primitive) for an item within a series.
*
* @param series the series index (zero-based).
* @param item the item index (zero-based).
*
* @return The y-value.
*
* @see #getAdjustForBinSize()
*/
@Override
public double getYValue(int series, int item) {
SimpleHistogramBin bin = this.bins.get(item);
if (this.adjustForBinSize) {
return bin.getItemCount()
/ (bin.getUpperBound() - bin.getLowerBound());
}
else {
return bin.getItemCount();
}
}
/**
* Returns the starting X value for the specified series and item.
*
* @param series the series index (zero-based).
* @param item the item index (zero-based).
*
* @return The value.
*/
@Override
public Number getStartX(int series, int item) {
return getStartXValue(series, item);
}
/**
* Returns the start 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 start x-value.
*/
@Override
public double getStartXValue(int series, int item) {
SimpleHistogramBin bin = this.bins.get(item);
return bin.getLowerBound();
}
/**
* Returns the ending X value for the specified series and item.
*
* @param series the series index (zero-based).
* @param item the item index (zero-based).
*
* @return The value.
*/
@Override
public Number getEndX(int series, int item) {
return getEndXValue(series, item);
}
/**
* Returns the end x-value (as a double primitive) for an item within a
* series.
*
* @param series the series index (zero-based).
* @param item the item index (zero-based).
*
* @return The end x-value.
*/
@Override
public double getEndXValue(int series, int item) {
SimpleHistogramBin bin = this.bins.get(item);
return bin.getUpperBound();
}
/**
* Returns the starting Y value for the specified series and item.
*
* @param series the series index (zero-based).
* @param item the item index (zero-based).
*
* @return The value.
*/
@Override
public Number getStartY(int series, int item) {
return getY(series, item);
}
/**
* Returns the start y-value (as a double primitive) for an item within a
* series.
*
* @param series the series index (zero-based).
* @param item the item index (zero-based).
*
* @return The start y-value.
*/
@Override
public double getStartYValue(int series, int item) {
return getYValue(series, item);
}
/**
* Returns the ending Y value for the specified series and item.
*
* @param series the series index (zero-based).
* @param item the item index (zero-based).
*
* @return The value.
*/
@Override
public Number getEndY(int series, int item) {
return getY(series, item);
}
/**
* Returns the end y-value (as a double primitive) for an item within a
* series.
*
* @param series the series index (zero-based).
* @param item the item index (zero-based).
*
* @return The end y-value.
*/
@Override
public double getEndYValue(int series, int item) {
return getYValue(series, item);
}
/**
* Compares the dataset 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 SimpleHistogramDataset)) {
return false;
}
SimpleHistogramDataset that = (SimpleHistogramDataset) obj;
if (!this.key.equals(that.key)) {
return false;
}
if (this.adjustForBinSize != that.adjustForBinSize) {
return false;
}
if (!this.bins.equals(that.bins)) {
return false;
}
return true;
}
/**
* Returns a clone of the dataset.
*
* @return A clone.
*
* @throws CloneNotSupportedException not thrown by this class, but maybe
* by subclasses (if any).
*/
@Override
public Object clone() throws CloneNotSupportedException {
SimpleHistogramDataset clone = (SimpleHistogramDataset) super.clone();
clone.bins = ObjectUtilities.deepClone(this.bins);
return clone;
}
}
| 14,410 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
Statistics.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/data/statistics/Statistics.java | /* ===========================================================
* JFreeChart : a free chart library for the Java(tm) platform
* ===========================================================
*
* (C) Copyright 2000-2011, 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.]
*
* ---------------
* Statistics.java
* ---------------
* (C) Copyright 2000-2008, by Matthew Wright and Contributors.
*
* Original Author: Matthew Wright;
* Contributor(s): David Gilbert (for Object Refinery Limited);
*
* Changes (from 08-Nov-2001)
* --------------------------
* 08-Nov-2001 : Added standard header and tidied Javadoc comments (DG);
* Moved from JFreeChart to package com.jrefinery.data.* in
* JCommon class library (DG);
* 24-Jun-2002 : Removed unnecessary local variable (DG);
* 07-Oct-2002 : Fixed errors reported by Checkstyle (DG);
* 26-May-2004 : Moved calculateMean() method from BoxAndWhiskerCalculator (DG);
* 02-Jun-2004 : Fixed bug in calculateMedian() method (DG);
* 11-Jan-2005 : Removed deprecated code in preparation for the 1.0.0
* release (DG);
*
*/
package org.jfree.data.statistics;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
/**
* A utility class that provides some common statistical functions.
*/
public abstract class Statistics {
/**
* Returns the mean of an array of numbers. This is equivalent to calling
* <code>calculateMean(values, true)</code>.
*
* @param values the values (<code>null</code> not permitted).
*
* @return The mean.
*/
public static double calculateMean(Number[] values) {
return calculateMean(values, true);
}
/**
* Returns the mean of an array of numbers.
*
* @param values the values (<code>null</code> not permitted).
* @param includeNullAndNaN a flag that controls whether or not
* <code>null</code> and <code>Double.NaN</code> values are included
* in the calculation (if either is present in the array, the result is
* {@link Double#NaN}).
*
* @return The mean.
*
* @since 1.0.3
*/
public static double calculateMean(Number[] values,
boolean includeNullAndNaN) {
if (values == null) {
throw new IllegalArgumentException("Null 'values' argument.");
}
double sum = 0.0;
double current;
int counter = 0;
for (Number value : values) {
// treat nulls the same as NaNs
if (value != null) {
current = value.doubleValue();
} else {
current = Double.NaN;
}
// calculate the sum and count
if (includeNullAndNaN || !Double.isNaN(current)) {
sum = sum + current;
counter++;
}
}
double result = (sum / counter);
return result;
}
/**
* Returns the mean of a collection of <code>Number</code> objects.
*
* @param values the values (<code>null</code> not permitted).
*
* @return The mean.
*/
public static double calculateMean(Collection<Number> values) {
return calculateMean(values, true);
}
/**
* Returns the mean of a collection of <code>Number</code> objects.
*
* @param values the values (<code>null</code> not permitted).
* @param includeNullAndNaN a flag that controls whether or not
* <code>null</code> and <code>Double.NaN</code> values are included
* in the calculation (if either is present in the array, the result is
* {@link Double#NaN}).
*
* @return The mean.
*
* @since 1.0.3
*/
public static double calculateMean(Collection<Number> values,
boolean includeNullAndNaN) {
if (values == null) {
throw new IllegalArgumentException("Null 'values' argument.");
}
int count = 0;
double total = 0.0;
for (Number n : values) {
if (n == null) {
if (includeNullAndNaN) {
return Double.NaN;
}
else {
continue;
}
}
double value = n.doubleValue();
if (Double.isNaN(value)) {
if (includeNullAndNaN) {
return Double.NaN;
}
else {
continue;
}
}
total = total + value;
count = count + 1;
}
return total / count;
}
/**
* Calculates the median for a list of values (<code>Number</code> objects).
* The list of values will be copied, and the copy sorted, before
* calculating the median. To avoid this step (if your list of values
* is already sorted), use the {@link #calculateMedian(List, boolean)}
* method.
*
* @param values the values (<code>null</code> permitted).
*
* @return The median.
*/
public static double calculateMedian(List<Number> values) {
return calculateMedian(values, true);
}
/**
* Calculates the median for a list of values (<code>Number</code> objects).
* If <code>copyAndSort</code> is <code>false</code>, the list is assumed
* to be presorted in ascending order by value.
*
* @param values the values (<code>null</code> permitted).
* @param copyAndSort a flag that controls whether the list of values is
* copied and sorted.
*
* @return The median.
*/
public static double calculateMedian(List<Number> values,
boolean copyAndSort) {
if (values == null) {
return Double.NaN;
}
double result = Double.NaN;
if (copyAndSort) {
List<Number> copy = new ArrayList<Number>(values);
Collections.sort((List) copy);
values = copy;
}
int count = values.size();
if (count > 0) {
if (count % 2 == 1) {
if (count > 1) {
Number value = values.get((count - 1) / 2);
result = value.doubleValue();
}
else {
Number value = values.get(0);
result = value.doubleValue();
}
}
else {
Number value1 = values.get(count / 2 - 1);
Number value2 = values.get(count / 2);
result = (value1.doubleValue() + value2.doubleValue()) / 2.0;
}
}
return result;
}
/**
* Calculates the median for a sublist within a list of values
* (<code>Number</code> objects).
*
* @param values the values, in any order (<code>null</code> not
* permitted).
* @param start the start index.
* @param end the end index.
*
* @return The median.
*/
public static double calculateMedian(List<Number> values, int start, int end) {
return calculateMedian(values, start, end, true);
}
/**
* Calculates the median for a sublist within a list of values
* (<code>Number</code> objects). The entire list will be sorted if the
* <code>ascending</code< argument is <code>false</code>.
*
* @param values the values (<code>null</code> not permitted).
* @param start the start index.
* @param end the end index.
* @param copyAndSort a flag that that controls whether the list of values
* is copied and sorted.
*
* @return The median.
*/
public static double calculateMedian(List<Number> values,
int start, int end, boolean copyAndSort) {
double result = Double.NaN;
if (copyAndSort) {
List<Number> working = new ArrayList<Number>(end - start + 1);
for (int i = start; i <= end; i++) {
working.add(values.get(i));
}
Collections.sort((List) working);
result = calculateMedian(working, false);
}
else {
int count = end - start + 1;
if (count > 0) {
if (count % 2 == 1) {
if (count > 1) {
Number value = values.get(start + (count - 1) / 2);
result = value.doubleValue();
}
else {
Number value = values.get(start);
result = value.doubleValue();
}
}
else {
Number v1 = values.get(start + count / 2 - 1);
Number v2 = values.get(start + count / 2);
result = (v1.doubleValue() + v2.doubleValue()) / 2.0;
}
}
}
return result;
}
/**
* Returns the standard deviation of a set of numbers.
*
* @param data the data (<code>null</code> or zero length array not
* permitted).
*
* @return The standard deviation of a set of numbers.
*/
public static double getStdDev(Number[] data) {
if (data == null) {
throw new IllegalArgumentException("Null 'data' array.");
}
if (data.length == 0) {
throw new IllegalArgumentException("Zero length 'data' array.");
}
double avg = calculateMean(data);
double sum = 0.0;
for (Number aData : data) {
double diff = aData.doubleValue() - avg;
sum = sum + diff * diff;
}
return Math.sqrt(sum / (data.length - 1));
}
/**
* Fits a straight line to a set of (x, y) data, returning the slope and
* intercept.
*
* @param xData the x-data (<code>null</code> not permitted).
* @param yData the y-data (<code>null</code> not permitted).
*
* @return A double array with the intercept in [0] and the slope in [1].
*/
public static double[] getLinearFit(Number[] xData, Number[] yData) {
if (xData == null) {
throw new IllegalArgumentException("Null 'xData' argument.");
}
if (yData == null) {
throw new IllegalArgumentException("Null 'yData' argument.");
}
if (xData.length != yData.length) {
throw new IllegalArgumentException(
"Statistics.getLinearFit(): array lengths must be equal.");
}
double[] result = new double[2];
// slope
result[1] = getSlope(xData, yData);
// intercept
result[0] = calculateMean(yData) - result[1] * calculateMean(xData);
return result;
}
/**
* Finds the slope of a regression line using least squares.
*
* @param xData the x-values (<code>null</code> not permitted).
* @param yData the y-values (<code>null</code> not permitted).
*
* @return The slope.
*/
public static double getSlope(Number[] xData, Number[] yData) {
if (xData == null) {
throw new IllegalArgumentException("Null 'xData' argument.");
}
if (yData == null) {
throw new IllegalArgumentException("Null 'yData' argument.");
}
if (xData.length != yData.length) {
throw new IllegalArgumentException("Array lengths must be equal.");
}
// ********* stat function for linear slope ********
// y = a + bx
// a = ybar - b * xbar
// sum(x * y) - (sum (x) * sum(y)) / n
// b = ------------------------------------
// sum (x^2) - (sum(x)^2 / n
// *************************************************
// sum of x, x^2, x * y, y
double sx = 0.0, sxx = 0.0, sxy = 0.0, sy = 0.0;
int counter;
for (counter = 0; counter < xData.length; counter++) {
sx = sx + xData[counter].doubleValue();
sxx = sxx + Math.pow(xData[counter].doubleValue(), 2);
sxy = sxy + yData[counter].doubleValue()
* xData[counter].doubleValue();
sy = sy + yData[counter].doubleValue();
}
return (sxy - (sx * sy) / counter) / (sxx - (sx * sx) / counter);
}
/**
* Calculates the correlation between two datasets. Both arrays should
* contain the same number of items. Null values are treated as zero.
* <P>
* Information about the correlation calculation was obtained from:
*
* http://trochim.human.cornell.edu/kb/statcorr.htm
*
* @param data1 the first dataset.
* @param data2 the second dataset.
*
* @return The correlation.
*/
public static double getCorrelation(Number[] data1, Number[] data2) {
if (data1 == null) {
throw new IllegalArgumentException("Null 'data1' argument.");
}
if (data2 == null) {
throw new IllegalArgumentException("Null 'data2' argument.");
}
if (data1.length != data2.length) {
throw new IllegalArgumentException(
"'data1' and 'data2' arrays must have same length."
);
}
int n = data1.length;
double sumX = 0.0;
double sumY = 0.0;
double sumX2 = 0.0;
double sumY2 = 0.0;
double sumXY = 0.0;
for (int i = 0; i < n; i++) {
double x = 0.0;
if (data1[i] != null) {
x = data1[i].doubleValue();
}
double y = 0.0;
if (data2[i] != null) {
y = data2[i].doubleValue();
}
sumX = sumX + x;
sumY = sumY + y;
sumXY = sumXY + (x * y);
sumX2 = sumX2 + (x * x);
sumY2 = sumY2 + (y * y);
}
return (n * sumXY - sumX * sumY) / Math.pow((n * sumX2 - sumX * sumX)
* (n * sumY2 - sumY * sumY), 0.5);
}
/**
* Returns a data set for a moving average on the data set passed in.
*
* @param xData an array of the x data.
* @param yData an array of the y data.
* @param period the number of data points to average
*
* @return A double[][] the length of the data set in the first dimension,
* with two doubles for x and y in the second dimension
*/
public static double[][] getMovingAverage(Number[] xData,
Number[] yData,
int period) {
// check arguments...
if (xData.length != yData.length) {
throw new IllegalArgumentException("Array lengths must be equal.");
}
if (period > xData.length) {
throw new IllegalArgumentException(
"Period can't be longer than dataset."
);
}
double[][] result = new double[xData.length - period][2];
for (int i = 0; i < result.length; i++) {
result[i][0] = xData[i + period].doubleValue();
// holds the moving average sum
double sum = 0.0;
for (int j = 0; j < period; j++) {
sum += yData[i + j].doubleValue();
}
sum = sum / period;
result[i][1] = sum;
}
return result;
}
}
| 16,441 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
BoxAndWhiskerItem.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/data/statistics/BoxAndWhiskerItem.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.]
*
* ----------------------
* BoxAndWhiskerItem.java
* ----------------------
* (C) Copyright 2003-2012, by Object Refinery Limited and Contributors.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 27-Aug-2003 : Version 1 (DG);
* 01-Mar-2004 : Added equals() method and implemented Serializable (DG);
* ------------- JFREECHART 1.0.x ---------------------------------------------
* 15-Nov-2006 : Added toString() method override (DG);
* 02-Oct-2007 : Added new constructor (for convenience) (DG);
* 16-Jun-2012 : Removed JCommon dependencies (DG);
*
*/
package org.jfree.data.statistics;
import java.io.Serializable;
import java.util.Collections;
import java.util.List;
import org.jfree.chart.util.ObjectUtilities;
/**
* Represents one data item within a box-and-whisker dataset. Instances of
* this class are immutable.
*/
public class BoxAndWhiskerItem implements Serializable {
/** For serialization. */
private static final long serialVersionUID = 7329649623148167423L;
/** The mean. */
private Number mean;
/** The median. */
private Number median;
/** The first quarter. */
private Number q1;
/** The third quarter. */
private Number q3;
/** The minimum regular value. */
private Number minRegularValue;
/** The maximum regular value. */
private Number maxRegularValue;
/** The minimum outlier. */
private Number minOutlier;
/** The maximum outlier. */
private Number maxOutlier;
/** The outliers. */
private List<Number> outliers;
/**
* Creates a new box-and-whisker item.
*
* @param mean the mean (<code>null</code> permitted).
* @param median the median (<code>null</code> permitted).
* @param q1 the first quartile (<code>null</code> permitted).
* @param q3 the third quartile (<code>null</code> permitted).
* @param minRegularValue the minimum regular value (<code>null</code>
* permitted).
* @param maxRegularValue the maximum regular value (<code>null</code>
* permitted).
* @param minOutlier the minimum outlier (<code>null</code> permitted).
* @param maxOutlier the maximum outlier (<code>null</code> permitted).
* @param outliers the outliers (<code>null</code> permitted).
*/
public BoxAndWhiskerItem(Number mean,
Number median,
Number q1,
Number q3,
Number minRegularValue,
Number maxRegularValue,
Number minOutlier,
Number maxOutlier,
List<Number> outliers) {
this.mean = mean;
this.median = median;
this.q1 = q1;
this.q3 = q3;
this.minRegularValue = minRegularValue;
this.maxRegularValue = maxRegularValue;
this.minOutlier = minOutlier;
this.maxOutlier = maxOutlier;
this.outliers = outliers;
}
/**
* Creates a new box-and-whisker item.
*
* @param mean the mean.
* @param median the median
* @param q1 the first quartile.
* @param q3 the third quartile.
* @param minRegularValue the minimum regular value.
* @param maxRegularValue the maximum regular value.
* @param minOutlier the minimum outlier value.
* @param maxOutlier the maximum outlier value.
* @param outliers a list of the outliers.
*
* @since 1.0.7
*/
public BoxAndWhiskerItem(double mean, double median, double q1, double q3,
double minRegularValue, double maxRegularValue, double minOutlier,
double maxOutlier, List<Number> outliers) {
// pass values to other constructor
this(new Double(mean), new Double(median), new Double(q1),
new Double(q3), new Double(minRegularValue),
new Double(maxRegularValue), new Double(minOutlier),
new Double(maxOutlier), outliers);
}
/**
* Returns the mean.
*
* @return The mean (possibly <code>null</code>).
*/
public Number getMean() {
return this.mean;
}
/**
* Returns the median.
*
* @return The median (possibly <code>null</code>).
*/
public Number getMedian() {
return this.median;
}
/**
* Returns the first quartile.
*
* @return The first quartile (possibly <code>null</code>).
*/
public Number getQ1() {
return this.q1;
}
/**
* Returns the third quartile.
*
* @return The third quartile (possibly <code>null</code>).
*/
public Number getQ3() {
return this.q3;
}
/**
* Returns the minimum regular value.
*
* @return The minimum regular value (possibly <code>null</code>).
*/
public Number getMinRegularValue() {
return this.minRegularValue;
}
/**
* Returns the maximum regular value.
*
* @return The maximum regular value (possibly <code>null</code>).
*/
public Number getMaxRegularValue() {
return this.maxRegularValue;
}
/**
* Returns the minimum outlier.
*
* @return The minimum outlier (possibly <code>null</code>).
*/
public Number getMinOutlier() {
return this.minOutlier;
}
/**
* Returns the maximum outlier.
*
* @return The maximum outlier (possibly <code>null</code>).
*/
public Number getMaxOutlier() {
return this.maxOutlier;
}
/**
* Returns a list of outliers.
*
* @return A list of outliers (possibly <code>null</code>).
*/
public List<Number> getOutliers() {
if (this.outliers == null) {
return null;
}
return Collections.unmodifiableList(this.outliers);
}
/**
* Returns a string representation of this instance, primarily for
* debugging purposes.
*
* @return A string representation of this instance.
*/
@Override
public String toString() {
return super.toString() + "[mean=" + this.mean + ",median="
+ this.median + ",q1=" + this.q1 + ",q3=" + this.q3 + "]";
}
/**
* Tests this object 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 BoxAndWhiskerItem)) {
return false;
}
BoxAndWhiskerItem that = (BoxAndWhiskerItem) obj;
if (!ObjectUtilities.equal(this.mean, that.mean)) {
return false;
}
if (!ObjectUtilities.equal(this.median, that.median)) {
return false;
}
if (!ObjectUtilities.equal(this.q1, that.q1)) {
return false;
}
if (!ObjectUtilities.equal(this.q3, that.q3)) {
return false;
}
if (!ObjectUtilities.equal(this.minRegularValue,
that.minRegularValue)) {
return false;
}
if (!ObjectUtilities.equal(this.maxRegularValue,
that.maxRegularValue)) {
return false;
}
if (!ObjectUtilities.equal(this.minOutlier, that.minOutlier)) {
return false;
}
if (!ObjectUtilities.equal(this.maxOutlier, that.maxOutlier)) {
return false;
}
if (!ObjectUtilities.equal(this.outliers, that.outliers)) {
return false;
}
return true;
}
}
| 9,052 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
BoxAndWhiskerCategoryDataset.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/data/statistics/BoxAndWhiskerCategoryDataset.java | /* ===========================================================
* JFreeChart : a free chart library for the Java(tm) platform
* ===========================================================
*
* (C) Copyright 2000-2011, 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.]
*
* ---------------------------------
* BoxAndWhiskerCategoryDataset.java
* ---------------------------------
* (C) Copyright 2003-2008, by David Browning and Contributors.
*
* Original Author: David Browning (for Australian Institute of Marine
* Science);
* Contributor(s): -;
*
* Changes
* -------
* 05-Aug-2003 : Version 1, contributed by David Browning (DG);
* 27-Aug-2003 : Renamed getAverageValue --> getMeanValue, changed
* getAllOutliers to return a List rather than an array (DG);
* ------------- JFREECHART 1.0.x ---------------------------------------------
* 02-Feb-2007 : Removed author tags from all over JFreeChart sources (DG);
*
*/
package org.jfree.data.statistics;
import java.util.List;
import org.jfree.data.category.CategoryDataset;
/**
* A category dataset that defines various medians, outliers and an average
* value for each item.
*/
public interface BoxAndWhiskerCategoryDataset extends CategoryDataset {
/**
* Returns the mean value for an item.
*
* @param row the row index (zero-based).
* @param column the column index (zero-based).
*
* @return The mean value.
*/
public Number getMeanValue(int row, int column);
/**
* Returns the average value for an item.
*
* @param rowKey the row key.
* @param columnKey the columnKey.
*
* @return The average value.
*/
public Number getMeanValue(Comparable rowKey, Comparable columnKey);
/**
* Returns the median value for an item.
*
* @param row the row index (zero-based).
* @param column the column index (zero-based).
*
* @return The median value.
*/
public Number getMedianValue(int row, int column);
/**
* Returns the median value for an item.
*
* @param rowKey the row key.
* @param columnKey the columnKey.
*
* @return The median value.
*/
public Number getMedianValue(Comparable rowKey, Comparable columnKey);
/**
* Returns the q1median value for an item.
*
* @param row the row index (zero-based).
* @param column the column index (zero-based).
*
* @return The q1median value.
*/
public Number getQ1Value(int row, int column);
/**
* Returns the q1median value for an item.
*
* @param rowKey the row key.
* @param columnKey the columnKey.
*
* @return The q1median value.
*/
public Number getQ1Value(Comparable rowKey, Comparable columnKey);
/**
* Returns the q3median value for an item.
*
* @param row the row index (zero-based).
* @param column the column index (zero-based).
*
* @return The q3median value.
*/
public Number getQ3Value(int row, int column);
/**
* Returns the q3median value for an item.
*
* @param rowKey the row key.
* @param columnKey the columnKey.
*
* @return The q3median value.
*/
public Number getQ3Value(Comparable rowKey, Comparable columnKey);
/**
* Returns the minimum regular (non-outlier) value for an item.
*
* @param row the row index (zero-based).
* @param column the column index (zero-based).
*
* @return The minimum regular value.
*/
public Number getMinRegularValue(int row, int column);
/**
* Returns the minimum regular (non-outlier) value for an item.
*
* @param rowKey the row key.
* @param columnKey the columnKey.
*
* @return The minimum regular value.
*/
public Number getMinRegularValue(Comparable rowKey, Comparable columnKey);
/**
* Returns the maximum regular (non-outlier) value for an item.
*
* @param row the row index (zero-based).
* @param column the column index (zero-based).
*
* @return The maximum regular value.
*/
public Number getMaxRegularValue(int row, int column);
/**
* Returns the maximum regular (non-outlier) value for an item.
*
* @param rowKey the row key.
* @param columnKey the columnKey.
*
* @return The maximum regular value.
*/
public Number getMaxRegularValue(Comparable rowKey, Comparable columnKey);
/**
* Returns the minimum outlier (non-farout) for an item.
*
* @param row the row index (zero-based).
* @param column the column index (zero-based).
*
* @return The minimum outlier.
*/
public Number getMinOutlier(int row, int column);
/**
* Returns the minimum outlier (non-farout) for an item.
*
* @param rowKey the row key.
* @param columnKey the columnKey.
*
* @return The minimum outlier.
*/
public Number getMinOutlier(Comparable rowKey, Comparable columnKey);
/**
* Returns the maximum outlier (non-farout) for an item.
*
* @param row the row index (zero-based).
* @param column the column index (zero-based).
*
* @return The maximum outlier.
*/
public Number getMaxOutlier(int row, int column);
/**
* Returns the maximum outlier (non-farout) for an item.
*
* @param rowKey the row key.
* @param columnKey the columnKey.
*
* @return The maximum outlier.
*/
public Number getMaxOutlier(Comparable rowKey, Comparable columnKey);
/**
* Returns a list of outlier values for an item. The list may be empty,
* but should never be <code>null</code>.
*
* @param row the row index (zero-based).
* @param column the column index (zero-based).
*
* @return A list of outliers for an item.
*/
public List<Number> getOutliers(int row, int column);
/**
* Returns a list of outlier values for an item. The list may be empty,
* but should never be <code>null</code>.
*
* @param rowKey the row key.
* @param columnKey the columnKey.
*
* @return A list of outlier values for an item.
*/
public List<Number> getOutliers(Comparable rowKey, Comparable columnKey);
}
| 7,330 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
HistogramDataset.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/data/statistics/HistogramDataset.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.]
*
* ---------------------
* HistogramDataset.java
* ---------------------
* (C) Copyright 2003-2012, by Jelai Wang and Contributors.
*
* Original Author: Jelai Wang (jelaiw AT mindspring.com);
* Contributor(s): David Gilbert (for Object Refinery Limited);
* Cameron Hayne;
* Rikard Bj?rklind;
* Thomas A Caswell (patch 2902842);
*
* Changes
* -------
* 06-Jul-2003 : Version 1, contributed by Jelai Wang (DG);
* 07-Jul-2003 : Changed package and added Javadocs (DG);
* 15-Oct-2003 : Updated Javadocs and removed array sorting (JW);
* 09-Jan-2004 : Added fix by "Z." posted in the JFreeChart forum (DG);
* 01-Mar-2004 : Added equals() and clone() methods and implemented
* Serializable. Also added new addSeries() method (DG);
* 06-May-2004 : Now extends AbstractIntervalXYDataset (DG);
* 15-Jul-2004 : Switched getX() with getXValue() and getY() with
* getYValue() (DG);
* 20-May-2005 : Speed up binning - see patch 1026151 contributed by Cameron
* Hayne (DG);
* 08-Jun-2005 : Fixed bug in getSeriesKey() method (DG);
* 22-Nov-2005 : Fixed cast in getSeriesKey() method - see patch 1329287 (DG);
* ------------- JFREECHART 1.0.x ---------------------------------------------
* 03-Aug-2006 : Improved precision of bin boundary calculation (DG);
* 07-Sep-2006 : Fixed bug 1553088 (DG);
* 22-May-2008 : Implemented clone() method override (DG);
* 08-Dec-2009 : Fire change event in addSeries() - see patch 2902842
* contributed by Thomas A Caswell (DG);
* 17-Jun-2012 : Removed JCommon dependencies (DG);
*
*/
package org.jfree.data.statistics;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.jfree.chart.util.ObjectUtilities;
import org.jfree.chart.util.PublicCloneable;
import org.jfree.data.general.DatasetChangeEvent;
import org.jfree.data.xy.AbstractIntervalXYDataset;
import org.jfree.data.xy.IntervalXYDataset;
/**
* A dataset that can be used for creating histograms.
*
* @see SimpleHistogramDataset
*/
public class HistogramDataset extends AbstractIntervalXYDataset
implements IntervalXYDataset, Cloneable, PublicCloneable,
Serializable {
/** For serialization. */
private static final long serialVersionUID = -6341668077370231153L;
/** A list of maps. */
private List<Map<String, Object>> list; //FIXME MMC this should really be an internal historgram type rather than object
/** The histogram type. */
private HistogramType type;
/**
* Creates a new (empty) dataset with a default type of
* {@link HistogramType}.FREQUENCY.
*/
public HistogramDataset() {
this.list = new ArrayList<Map<String, Object>>();
this.type = HistogramType.FREQUENCY;
}
/**
* Returns the histogram type.
*
* @return The type (never <code>null</code>).
*/
public HistogramType getType() {
return this.type;
}
/**
* Sets the histogram type and sends a {@link DatasetChangeEvent} to all
* registered listeners.
*
* @param type the type (<code>null</code> not permitted).
*/
public void setType(HistogramType type) {
if (type == null) {
throw new IllegalArgumentException("Null 'type' argument");
}
this.type = type;
fireDatasetChanged();
}
/**
* Adds a series to the dataset, using the specified number of bins,
* and sends a {@link DatasetChangeEvent} to all registered listeners.
*
* @param key the series key (<code>null</code> not permitted).
* @param values the values (<code>null</code> not permitted).
* @param bins the number of bins (must be at least 1).
*/
public void addSeries(Comparable key, double[] values, int bins) {
// defer argument checking...
double minimum = getMinimum(values);
double maximum = getMaximum(values);
addSeries(key, values, bins, minimum, maximum);
}
/**
* Adds a series to the dataset. Any data value less than minimum will be
* assigned to the first bin, and any data value greater than maximum will
* be assigned to the last bin. Values falling on the boundary of
* adjacent bins will be assigned to the higher indexed bin.
*
* @param key the series key (<code>null</code> not permitted).
* @param values the raw observations.
* @param bins the number of bins (must be at least 1).
* @param minimum the lower bound of the bin range.
* @param maximum the upper bound of the bin range.
*/
public void addSeries(Comparable key, double[] values, int bins,
double minimum, double maximum) {
if (key == null) {
throw new IllegalArgumentException("Null 'key' argument.");
}
if (values == null) {
throw new IllegalArgumentException("Null 'values' argument.");
}
else if (bins < 1) {
throw new IllegalArgumentException(
"The 'bins' value must be at least 1.");
}
double binWidth = (maximum - minimum) / bins;
double lower = minimum;
double upper;
List<HistogramBin> binList = new ArrayList<HistogramBin>(bins);
for (int i = 0; i < bins; i++) {
HistogramBin bin;
// make sure bins[bins.length]'s upper boundary ends at maximum
// to avoid the rounding issue. the bins[0] lower boundary is
// guaranteed start from min
if (i == bins - 1) {
bin = new HistogramBin(lower, maximum);
}
else {
upper = minimum + (i + 1) * binWidth;
bin = new HistogramBin(lower, upper);
lower = upper;
}
binList.add(bin);
}
// fill the bins
for (double value : values) {
int binIndex = bins - 1;
if (value < maximum) {
double fraction = (value - minimum) / (maximum - minimum);
if (fraction < 0.0) {
fraction = 0.0;
}
binIndex = (int) (fraction * bins);
// rounding could result in binIndex being equal to bins
// which will cause an IndexOutOfBoundsException - see bug
// report 1553088
if (binIndex >= bins) {
binIndex = bins - 1;
}
}
HistogramBin bin = binList.get(binIndex);
bin.incrementCount();
}
// generic map for each series
Map<String, Object> map = new HashMap<String, Object>();
map.put("key", key);
map.put("bins", binList);
map.put("values.length", values.length);
map.put("bin width", binWidth);
this.list.add(map);
fireDatasetChanged();
}
/**
* Returns the minimum value in an array of values.
*
* @param values the values (<code>null</code> not permitted and
* zero-length array not permitted).
*
* @return The minimum value.
*/
private double getMinimum(double[] values) {
if (values == null || values.length < 1) {
throw new IllegalArgumentException(
"Null or zero length 'values' argument.");
}
double min = Double.MAX_VALUE;
for (double value : values) {
if (value < min) {
min = value;
}
}
return min;
}
/**
* Returns the maximum value in an array of values.
*
* @param values the values (<code>null</code> not permitted and
* zero-length array not permitted).
*
* @return The maximum value.
*/
private double getMaximum(double[] values) {
if (values == null || values.length < 1) {
throw new IllegalArgumentException(
"Null or zero length 'values' argument.");
}
double max = -Double.MAX_VALUE;
for (double value : values) {
if (value > max) {
max = value;
}
}
return max;
}
/**
* Returns the bins for a series.
*
* @param series the series index (in the range <code>0</code> to
* <code>getSeriesCount() - 1</code>).
*
* @return A list of bins.
*
* @throws IndexOutOfBoundsException if <code>series</code> is outside the
* specified range.
*/
List<HistogramBin> getBins(int series) {
Map<String, Object> map = this.list.get(series);
return (List<HistogramBin>) map.get("bins");
}
/**
* Returns the total number of observations for a series.
*
* @param series the series index.
*
* @return The total.
*/
private int getTotal(int series) {
Map<String, Object> map = this.list.get(series);
return (Integer) map.get("values.length");
}
/**
* Returns the bin width for a series.
*
* @param series the series index (zero based).
*
* @return The bin width.
*/
private double getBinWidth(int series) {
Map<String, Object> map = this.list.get(series);
return (Double) map.get("bin width");
}
/**
* Returns the number of series in the dataset.
*
* @return The series count.
*/
@Override
public int getSeriesCount() {
return this.list.size();
}
/**
* Returns the key for a series.
*
* @param series the series index (in the range <code>0</code> to
* <code>getSeriesCount() - 1</code>).
*
* @return The series key.
*
* @throws IndexOutOfBoundsException if <code>series</code> is outside the
* specified range.
*/
@Override
public Comparable getSeriesKey(int series) {
Map<String, Object> map = this.list.get(series);
return (Comparable) map.get("key");
}
/**
* Returns the number of data items for a series.
*
* @param series the series index (in the range <code>0</code> to
* <code>getSeriesCount() - 1</code>).
*
* @return The item count.
*
* @throws IndexOutOfBoundsException if <code>series</code> is outside the
* specified range.
*/
@Override
public int getItemCount(int series) {
return getBins(series).size();
}
/**
* Returns the X value for a bin. This value won't be used for plotting
* histograms, since the renderer will ignore it. But other renderers can
* use it (for example, you could use the dataset to create a line
* chart).
*
* @param series the series index (in the range <code>0</code> to
* <code>getSeriesCount() - 1</code>).
* @param item the item index (zero based).
*
* @return The start value.
*
* @throws IndexOutOfBoundsException if <code>series</code> is outside the
* specified range.
*/
@Override
public Number getX(int series, int item) {
List<HistogramBin> bins = getBins(series);
HistogramBin bin = bins.get(item);
double x = (bin.getStartBoundary() + bin.getEndBoundary()) / 2.;
return x;
}
/**
* Returns the y-value for a bin (calculated to take into account the
* histogram type).
*
* @param series the series index (in the range <code>0</code> to
* <code>getSeriesCount() - 1</code>).
* @param item the item index (zero based).
*
* @return The y-value.
*
* @throws IndexOutOfBoundsException if <code>series</code> is outside the
* specified range.
*/
@Override
public Number getY(int series, int item) {
List<HistogramBin> bins = getBins(series);
HistogramBin bin = bins.get(item);
double total = getTotal(series);
double binWidth = getBinWidth(series);
if (this.type == HistogramType.FREQUENCY) {
return (double) bin.getCount();
}
else if (this.type == HistogramType.RELATIVE_FREQUENCY) {
return bin.getCount() / total;
}
else if (this.type == HistogramType.SCALE_AREA_TO_1) {
return bin.getCount() / (binWidth * total);
}
else { // pretty sure this shouldn't ever happen
throw new IllegalStateException();
}
}
/**
* Returns the start value for a bin.
*
* @param series the series index (in the range <code>0</code> to
* <code>getSeriesCount() - 1</code>).
* @param item the item index (zero based).
*
* @return The start value.
*
* @throws IndexOutOfBoundsException if <code>series</code> is outside the
* specified range.
*/
@Override
public Number getStartX(int series, int item) {
List<HistogramBin> bins = getBins(series);
HistogramBin bin = bins.get(item);
return bin.getStartBoundary();
}
/**
* Returns the end value for a bin.
*
* @param series the series index (in the range <code>0</code> to
* <code>getSeriesCount() - 1</code>).
* @param item the item index (zero based).
*
* @return The end value.
*
* @throws IndexOutOfBoundsException if <code>series</code> is outside the
* specified range.
*/
@Override
public Number getEndX(int series, int item) {
List<HistogramBin> bins = getBins(series);
HistogramBin bin = bins.get(item);
return bin.getEndBoundary();
}
/**
* Returns the start y-value for a bin (which is the same as the y-value,
* this method exists only to support the general form of the
* {@link IntervalXYDataset} interface).
*
* @param series the series index (in the range <code>0</code> to
* <code>getSeriesCount() - 1</code>).
* @param item the item index (zero based).
*
* @return The y-value.
*
* @throws IndexOutOfBoundsException if <code>series</code> is outside the
* specified range.
*/
@Override
public Number getStartY(int series, int item) {
return getY(series, item);
}
/**
* Returns the end y-value for a bin (which is the same as the y-value,
* this method exists only to support the general form of the
* {@link IntervalXYDataset} interface).
*
* @param series the series index (in the range <code>0</code> to
* <code>getSeriesCount() - 1</code>).
* @param item the item index (zero based).
*
* @return The Y value.
*
* @throws IndexOutOfBoundsException if <code>series</code> is outside the
* specified range.
*/
@Override
public Number getEndY(int series, int item) {
return getY(series, item);
}
/**
* Tests this dataset 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 HistogramDataset)) {
return false;
}
HistogramDataset that = (HistogramDataset) obj;
if (!ObjectUtilities.equal(this.type, that.type)) {
return false;
}
if (!ObjectUtilities.equal(this.list, that.list)) {
return false;
}
return true;
}
/**
* Returns a clone of the dataset.
*
* @return A clone of the dataset.
*
* @throws CloneNotSupportedException if the object cannot be cloned.
*/
@Override
public Object clone() throws CloneNotSupportedException {
HistogramDataset clone = (HistogramDataset) super.clone();
int seriesCount = getSeriesCount();
clone.list = new java.util.ArrayList<Map<String, Object>>(seriesCount);
for (int i = 0; i < seriesCount; i++) {
clone.list.add(new HashMap<String, Object>(this.list.get(i)));
}
return clone;
}
}
| 17,557 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
LineFunction2D.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/data/function/LineFunction2D.java | /* ===========================================================
* JFreeChart : a free chart library for the Java(tm) platform
* ===========================================================
*
* (C) Copyright 2000-2011, 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.]
*
* -------------------
* LineFunction2D.java
* -------------------
* (C) Copyright 2002-2009, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes:
* --------
* 01-Oct-2002 : Version 1 (DG);
* 28-May-2009 : Added accessor methods for co-efficients, implemented
* equals() and hashCode(), and added Serialization support (DG);
*
*/
package org.jfree.data.function;
import java.io.Serializable;
import org.jfree.chart.HashUtilities;
/**
* A function in the form y = a + bx.
*/
public class LineFunction2D implements Function2D, Serializable {
/** The intercept. */
private double a;
/** The slope of the line. */
private double b;
/**
* Constructs a new line function.
*
* @param a the intercept.
* @param b the slope.
*/
public LineFunction2D(double a, double b) {
this.a = a;
this.b = b;
}
/**
* Returns the 'a' coefficient that was specified in the constructor.
*
* @return The 'a' coefficient.
*
* @since 1.0.14
*/
public double getIntercept() {
return this.a;
}
/**
* Returns the 'b' coefficient that was specified in the constructor.
*
* @return The 'b' coefficient.
*
* @since 1.0.14
*/
public double getSlope() {
return this.b;
}
/**
* Returns the function value.
*
* @param x the x-value.
*
* @return The value.
*/
@Override
public double getValue(double x) {
return this.a + this.b * x;
}
/**
* Tests this function 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 LineFunction2D)) {
return false;
}
LineFunction2D that = (LineFunction2D) obj;
if (this.a != that.a) {
return false;
}
if (this.b != that.b) {
return false;
}
return true;
}
/**
* Returns a hash code for this instance.
*
* @return A hash code.
*/
@Override
public int hashCode() {
int result = 29;
result = HashUtilities.hashCode(result, this.a);
result = HashUtilities.hashCode(result, this.b);
return result;
}
}
| 3,710 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
Function2D.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/data/function/Function2D.java | /* ===========================================================
* JFreeChart : a free chart library for the Java(tm) platform
* ===========================================================
*
* (C) Copyright 2000-2011, 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.]
*
* ---------------
* Function2D.java
* ---------------
* (C) Copyright 2002-2008, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes:
* --------
* 01-Oct-2002 : Version 1 (DG);
* 20-Jan-2005 : Minor Javadoc update (DG);
*
*/
package org.jfree.data.function;
/**
* A function of the form <code>y = f(x)</code>.
*/
public interface Function2D {
/**
* Returns the value of the function ('y') for a given input ('x').
*
* @param x the x-value.
*
* @return The function value.
*/
public double getValue(double x);
}
| 1,872 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
PowerFunction2D.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/data/function/PowerFunction2D.java | /* ===========================================================
* JFreeChart : a free chart library for the Java(tm) platform
* ===========================================================
*
* (C) Copyright 2000-2011, 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.]
*
* --------------------
* PowerFunction2D.java
* --------------------
* (C) Copyright 2002-2009, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes:
* --------
* 01-Oct-2002 : Version 1 (DG);
* 28-May-2009 : Added accessor methods for co-efficients, implemented
* equals() and hashCode(), and added Serialization support (DG);
*
*/
package org.jfree.data.function;
import java.io.Serializable;
import org.jfree.chart.HashUtilities;
/**
* A function of the form y = a * x ^ b.
*/
public class PowerFunction2D implements Function2D, Serializable {
/** The 'a' coefficient. */
private double a;
/** The 'b' coefficient. */
private double b;
/**
* Creates a new power function.
*
* @param a the 'a' coefficient.
* @param b the 'b' coefficient.
*/
public PowerFunction2D(double a, double b) {
this.a = a;
this.b = b;
}
/**
* Returns the 'a' coefficient that was specified in the constructor.
*
* @return The 'a' coefficient.
*
* @since 1.0.14
*/
public double getA() {
return this.a;
}
/**
* Returns the 'b' coefficient that was specified in the constructor.
*
* @return The 'b' coefficient.
*
* @since 1.0.14
*/
public double getB() {
return this.b;
}
/**
* Returns the value of the function for a given input ('x').
*
* @param x the x-value.
*
* @return The value.
*/
@Override
public double getValue(double x) {
return this.a * Math.pow(x, this.b);
}
/**
* Tests this function 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 PowerFunction2D)) {
return false;
}
PowerFunction2D that = (PowerFunction2D) obj;
if (this.a != that.a) {
return false;
}
if (this.b != that.b) {
return false;
}
return true;
}
/**
* Returns a hash code for this instance.
*
* @return A hash code.
*/
@Override
public int hashCode() {
int result = 29;
result = HashUtilities.hashCode(result, this.a);
result = HashUtilities.hashCode(result, this.b);
return result;
}
}
| 3,767 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
NormalDistributionFunction2D.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/data/function/NormalDistributionFunction2D.java | /* ===========================================================
* JFreeChart : a free chart library for the Java(tm) platform
* ===========================================================
*
* (C) Copyright 2000-2011, 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.]
*
* ---------------------------------
* NormalDistributionFunction2D.java
* ---------------------------------
* (C)opyright 2004-2009, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 25-May-2004 : Version 1 (DG);
* 21-Nov-2005 : Added getters for the mean and standard deviation (DG);
* 12-Feb-2009 : Precompute some constants from the function - see bug
* 2572016 (DG);
* 28-May-2009 : Implemented equals() and hashCode(), and added serialization
* support (DG);
*
*/
package org.jfree.data.function;
import java.io.Serializable;
import org.jfree.chart.HashUtilities;
/**
* A normal distribution function. See
* http://en.wikipedia.org/wiki/Normal_distribution.
*/
public class NormalDistributionFunction2D implements Function2D, Serializable {
/** The mean. */
private double mean;
/** The standard deviation. */
private double std;
/** Precomputed factor for the function value. */
private double factor;
/** Precomputed denominator for the function value. */
private double denominator;
/**
* Constructs a new normal distribution function.
*
* @param mean the mean.
* @param std the standard deviation (> 0).
*/
public NormalDistributionFunction2D(double mean, double std) {
if (std <= 0) {
throw new IllegalArgumentException("Requires 'std' > 0.");
}
this.mean = mean;
this.std = std;
// calculate constant values
this.factor = 1 / (std * Math.sqrt(2.0 * Math.PI));
this.denominator = 2 * std * std;
}
/**
* Returns the mean for the function.
*
* @return The mean.
*/
public double getMean() {
return this.mean;
}
/**
* Returns the standard deviation for the function.
*
* @return The standard deviation.
*/
public double getStandardDeviation() {
return this.std;
}
/**
* Returns the function value.
*
* @param x the x-value.
*
* @return The value.
*/
@Override
public double getValue(double x) {
double z = x - this.mean;
return this.factor * Math.exp(-z * z / this.denominator);
}
/**
* Tests this function 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 NormalDistributionFunction2D)) {
return false;
}
NormalDistributionFunction2D that = (NormalDistributionFunction2D) obj;
if (this.mean != that.mean) {
return false;
}
if (this.std != that.std) {
return false;
}
return true;
}
/**
* Returns a hash code for this instance.
*
* @return A hash code.
*/
@Override
public int hashCode() {
int result = 29;
result = HashUtilities.hashCode(result, this.mean);
result = HashUtilities.hashCode(result, this.std);
return result;
}
}
| 4,452 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
PolynomialFunction2D.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/data/function/PolynomialFunction2D.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.]
*
* -------------------------
* PolynomialFunction2D.java
* -------------------------
* (C) Copyright 2009, by Object Refinery Limited.
*
* Original Author: Peter Kolb;
* Contributor(s): David Gilbert (for Object Refinery Limited);
*
* Changes:
* --------
* 23-Mar-2009 : Version 1, patch 2795746 (PK);
* 28-May-2009 : Integrated in JFreeChart with modifications (DG);
*
*/
package org.jfree.data.function;
import java.io.Serializable;
import java.util.Arrays;
import org.jfree.chart.HashUtilities;
/**
* A function in the form <code>y = a0 + a1 * x + a2 * x^2 + ... + an *
* x^n</code>. Instances of this class are immutable.
*
* @since 1.0.14
*/
public class PolynomialFunction2D implements Function2D, Serializable {
/** The coefficients. */
private double[] coefficients;
/**
* Constructs a new polynomial function <code>y = a0 + a1 * x + a2 * x^2 +
* ... + an * x^n</code>
*
* @param coefficients an array with the coefficients [a0, a1, ..., an]
* (<code>null</code> not permitted).
*/
public PolynomialFunction2D(double[] coefficients) {
if (coefficients == null) {
throw new IllegalArgumentException("Null 'coefficients' argument");
}
this.coefficients = coefficients.clone();
}
/**
* Returns a copy of the coefficients array that was specified in the
* constructor.
*
* @return The coefficients array.
*/
public double[] getCoefficients() {
return this.coefficients.clone();
}
/**
* Returns the order of the polynomial.
*
* @return The order.
*/
public int getOrder() {
return this.coefficients.length - 1;
}
/**
* Returns the function value.
*
* @param x the x-value.
*
* @return The value.
*/
@Override
public double getValue(double x) {
double y = 0;
for(int i = 0; i < this.coefficients.length; i++){
y += coefficients[i] * Math.pow(x, i);
}
return y;
}
/**
* Tests this function 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 PolynomialFunction2D)) {
return false;
}
PolynomialFunction2D that = (PolynomialFunction2D) obj;
return Arrays.equals(this.coefficients, that.coefficients);
}
/**
* Returns a hash code for this instance.
*
* @return A hash code.
*/
@Override
public int hashCode() {
return HashUtilities.hashCodeForDoubleArray(this.coefficients);
}
}
| 3,976 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
SlidingGanttCategoryDataset.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/data/gantt/SlidingGanttCategoryDataset.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.]
*
* --------------------------------
* SlidingGanttCategoryDataset.java
* --------------------------------
* (C) Copyright 2008-2012, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 09-May-2008 : Version 1 (DG);
* 17-Jun-2012 : Removed JCommon dependencies (DG);
*
*/
package org.jfree.data.gantt;
import java.util.Collections;
import java.util.List;
import org.jfree.chart.util.PublicCloneable;
import org.jfree.data.UnknownKeyException;
import org.jfree.data.general.AbstractDataset;
import org.jfree.data.general.DatasetChangeEvent;
/**
* A {@link GanttCategoryDataset} implementation that presents a subset of the
* categories in an underlying dataset. The index of the first "visible"
* category can be modified, which provides a means of "sliding" through
* the categories in the underlying dataset.
*
* @since 1.0.10
*/
public class SlidingGanttCategoryDataset extends AbstractDataset
implements GanttCategoryDataset {
/** The underlying dataset. */
private GanttCategoryDataset underlying;
/** The index of the first category to present. */
private int firstCategoryIndex;
/** The maximum number of categories to present. */
private int maximumCategoryCount;
/**
* Creates a new instance.
*
* @param underlying the underlying dataset (<code>null</code> not
* permitted).
* @param firstColumn the index of the first visible column from the
* underlying dataset.
* @param maxColumns the maximumColumnCount.
*/
public SlidingGanttCategoryDataset(GanttCategoryDataset underlying,
int firstColumn, int maxColumns) {
this.underlying = underlying;
this.firstCategoryIndex = firstColumn;
this.maximumCategoryCount = maxColumns;
}
/**
* Returns the underlying dataset that was supplied to the constructor.
*
* @return The underlying dataset (never <code>null</code>).
*/
public GanttCategoryDataset getUnderlyingDataset() {
return this.underlying;
}
/**
* Returns the index of the first visible category.
*
* @return The index.
*
* @see #setFirstCategoryIndex(int)
*/
public int getFirstCategoryIndex() {
return this.firstCategoryIndex;
}
/**
* Sets the index of the first category that should be used from the
* underlying dataset, and sends a {@link DatasetChangeEvent} to all
* registered listeners.
*
* @param first the index.
*
* @see #getFirstCategoryIndex()
*/
public void setFirstCategoryIndex(int first) {
if (first < 0 || first >= this.underlying.getColumnCount()) {
throw new IllegalArgumentException("Invalid index.");
}
this.firstCategoryIndex = first;
fireDatasetChanged();
}
/**
* Returns the maximum category count.
*
* @return The maximum category count.
*
* @see #setMaximumCategoryCount(int)
*/
public int getMaximumCategoryCount() {
return this.maximumCategoryCount;
}
/**
* Sets the maximum category count and sends a {@link DatasetChangeEvent}
* to all registered listeners.
*
* @param max the maximum.
*
* @see #getMaximumCategoryCount()
*/
public void setMaximumCategoryCount(int max) {
if (max < 0) {
throw new IllegalArgumentException("Requires 'max' >= 0.");
}
this.maximumCategoryCount = max;
fireDatasetChanged();
}
/**
* Returns the index of the last column for this dataset, or -1.
*
* @return The index.
*/
private int lastCategoryIndex() {
if (this.maximumCategoryCount == 0) {
return -1;
}
return Math.min(this.firstCategoryIndex + this.maximumCategoryCount,
this.underlying.getColumnCount()) - 1;
}
/**
* Returns the index for the specified column key.
*
* @param key the key.
*
* @return The column index, or -1 if the key is not recognised.
*/
@Override
public int getColumnIndex(Comparable key) {
int index = this.underlying.getColumnIndex(key);
if (index >= this.firstCategoryIndex && index <= lastCategoryIndex()) {
return index - this.firstCategoryIndex;
}
return -1; // we didn't find the key
}
/**
* Returns the column key for a given index.
*
* @param column the column index (zero-based).
*
* @return The column key.
*
* @throws IndexOutOfBoundsException if <code>row</code> is out of bounds.
*/
@Override
public Comparable getColumnKey(int column) {
return this.underlying.getColumnKey(column + this.firstCategoryIndex);
}
/**
* Returns the column keys.
*
* @return The keys.
*
* @see #getColumnKey(int)
*/
@Override
public List<Comparable> getColumnKeys() {
List<Comparable> result = new java.util.ArrayList<Comparable>();
int last = lastCategoryIndex();
for (int i = this.firstCategoryIndex; i < last; i++) {
result.add(this.underlying.getColumnKey(i));
}
return Collections.unmodifiableList(result);
}
/**
* Returns the row index for a given key.
*
* @param key the row key.
*
* @return The row index, or <code>-1</code> if the key is unrecognised.
*/
@Override
public int getRowIndex(Comparable key) {
return this.underlying.getRowIndex(key);
}
/**
* Returns the row key for a given index.
*
* @param row the row index (zero-based).
*
* @return The row key.
*
* @throws IndexOutOfBoundsException if <code>row</code> is out of bounds.
*/
@Override
public Comparable getRowKey(int row) {
return this.underlying.getRowKey(row);
}
/**
* Returns the row keys.
*
* @return The keys.
*/
@Override
public List<Comparable> getRowKeys() {
return this.underlying.getRowKeys();
}
/**
* Returns the value for a pair of keys.
*
* @param rowKey the row key (<code>null</code> not permitted).
* @param columnKey the column key (<code>null</code> not permitted).
*
* @return The value (possibly <code>null</code>).
*
* @throws UnknownKeyException if either key is not defined in the dataset.
*/
@Override
public Number getValue(Comparable rowKey, Comparable columnKey) {
int r = getRowIndex(rowKey);
int c = getColumnIndex(columnKey);
if (c != -1) {
return this.underlying.getValue(r, c + this.firstCategoryIndex);
}
else {
throw new UnknownKeyException("Unknown columnKey: " + columnKey);
}
}
/**
* Returns the number of columns in the table.
*
* @return The column count.
*/
@Override
public int getColumnCount() {
int last = lastCategoryIndex();
if (last == -1) {
return 0;
}
else {
return Math.max(last - this.firstCategoryIndex + 1, 0);
}
}
/**
* Returns the number of rows in the table.
*
* @return The row count.
*/
@Override
public int getRowCount() {
return this.underlying.getRowCount();
}
/**
* Returns a value from the table.
*
* @param row the row index (zero-based).
* @param column the column index (zero-based).
*
* @return The value (possibly <code>null</code>).
*/
@Override
public Number getValue(int row, int column) {
return this.underlying.getValue(row, column + this.firstCategoryIndex);
}
/**
* Returns the percent complete for a given item.
*
* @param rowKey the row key.
* @param columnKey the column key.
*
* @return The percent complete.
*/
@Override
public Number getPercentComplete(Comparable rowKey, Comparable columnKey) {
int r = getRowIndex(rowKey);
int c = getColumnIndex(columnKey);
if (c != -1) {
return this.underlying.getPercentComplete(r,
c + this.firstCategoryIndex);
}
else {
throw new UnknownKeyException("Unknown columnKey: " + columnKey);
}
}
/**
* Returns the percentage complete value of a sub-interval for a given item.
*
* @param rowKey the row key.
* @param columnKey the column key.
* @param subinterval the sub-interval.
*
* @return The percent complete value (possibly <code>null</code>).
*
* @see #getPercentComplete(int, int, int)
*/
@Override
public Number getPercentComplete(Comparable rowKey, Comparable columnKey,
int subinterval) {
int r = getRowIndex(rowKey);
int c = getColumnIndex(columnKey);
if (c != -1) {
return this.underlying.getPercentComplete(r,
c + this.firstCategoryIndex, subinterval);
}
else {
throw new UnknownKeyException("Unknown columnKey: " + columnKey);
}
}
/**
* Returns the end value of a sub-interval for a given item.
*
* @param rowKey the row key.
* @param columnKey the column key.
* @param subinterval the sub-interval.
*
* @return The end value (possibly <code>null</code>).
*
* @see #getStartValue(Comparable, Comparable, int)
*/
@Override
public Number getEndValue(Comparable rowKey, Comparable columnKey,
int subinterval) {
int r = getRowIndex(rowKey);
int c = getColumnIndex(columnKey);
if (c != -1) {
return this.underlying.getEndValue(r,
c + this.firstCategoryIndex, subinterval);
}
else {
throw new UnknownKeyException("Unknown columnKey: " + columnKey);
}
}
/**
* Returns the end value of a sub-interval for a given item.
*
* @param row the row index (zero-based).
* @param column the column index (zero-based).
* @param subinterval the sub-interval.
*
* @return The end value (possibly <code>null</code>).
*
* @see #getStartValue(int, int, int)
*/
@Override
public Number getEndValue(int row, int column, int subinterval) {
return this.underlying.getEndValue(row,
column + this.firstCategoryIndex, subinterval);
}
/**
* Returns the percent complete for a given item.
*
* @param series the row index (zero-based).
* @param category the column index (zero-based).
*
* @return The percent complete.
*/
@Override
public Number getPercentComplete(int series, int category) {
return this.underlying.getPercentComplete(series,
category + this.firstCategoryIndex);
}
/**
* Returns the percentage complete value of a sub-interval for a given item.
*
* @param row the row index (zero-based).
* @param column the column index (zero-based).
* @param subinterval the sub-interval.
*
* @return The percent complete value (possibly <code>null</code>).
*
* @see #getPercentComplete(Comparable, Comparable, int)
*/
@Override
public Number getPercentComplete(int row, int column, int subinterval) {
return this.underlying.getPercentComplete(row,
column + this.firstCategoryIndex, subinterval);
}
/**
* Returns the start value of a sub-interval for a given item.
*
* @param rowKey the row key.
* @param columnKey the column key.
* @param subinterval the sub-interval.
*
* @return The start value (possibly <code>null</code>).
*
* @see #getEndValue(Comparable, Comparable, int)
*/
@Override
public Number getStartValue(Comparable rowKey, Comparable columnKey,
int subinterval) {
int r = getRowIndex(rowKey);
int c = getColumnIndex(columnKey);
if (c != -1) {
return this.underlying.getStartValue(r,
c + this.firstCategoryIndex, subinterval);
}
else {
throw new UnknownKeyException("Unknown columnKey: " + columnKey);
}
}
/**
* Returns the start value of a sub-interval for a given item.
*
* @param row the row index (zero-based).
* @param column the column index (zero-based).
* @param subinterval the sub-interval index (zero-based).
*
* @return The start value (possibly <code>null</code>).
*
* @see #getEndValue(int, int, int)
*/
@Override
public Number getStartValue(int row, int column, int subinterval) {
return this.underlying.getStartValue(row,
column + this.firstCategoryIndex, subinterval);
}
/**
* Returns the number of sub-intervals for a given item.
*
* @param rowKey the row key.
* @param columnKey the column key.
*
* @return The sub-interval count.
*
* @see #getSubIntervalCount(int, int)
*/
@Override
public int getSubIntervalCount(Comparable rowKey, Comparable columnKey) {
int r = getRowIndex(rowKey);
int c = getColumnIndex(columnKey);
if (c != -1) {
return this.underlying.getSubIntervalCount(r,
c + this.firstCategoryIndex);
}
else {
throw new UnknownKeyException("Unknown columnKey: " + columnKey);
}
}
/**
* Returns the number of sub-intervals for a given item.
*
* @param row the row index (zero-based).
* @param column the column index (zero-based).
*
* @return The sub-interval count.
*
* @see #getSubIntervalCount(Comparable, Comparable)
*/
@Override
public int getSubIntervalCount(int row, int column) {
return this.underlying.getSubIntervalCount(row,
column + this.firstCategoryIndex);
}
/**
* Returns the start value for the interval for a given series and category.
*
* @param rowKey the series key.
* @param columnKey the category key.
*
* @return The start value (possibly <code>null</code>).
*
* @see #getEndValue(Comparable, Comparable)
*/
@Override
public Number getStartValue(Comparable rowKey, Comparable columnKey) {
int r = getRowIndex(rowKey);
int c = getColumnIndex(columnKey);
if (c != -1) {
return this.underlying.getStartValue(r,
c + this.firstCategoryIndex);
}
else {
throw new UnknownKeyException("Unknown columnKey: " + columnKey);
}
}
/**
* Returns the start value for the interval for a given series and category.
*
* @param row the series (zero-based index).
* @param column the category (zero-based index).
*
* @return The start value (possibly <code>null</code>).
*
* @see #getEndValue(int, int)
*/
@Override
public Number getStartValue(int row, int column) {
return this.underlying.getStartValue(row,
column + this.firstCategoryIndex);
}
/**
* Returns the end value for the interval for a given series and category.
*
* @param rowKey the series key.
* @param columnKey the category key.
*
* @return The end value (possibly <code>null</code>).
*
* @see #getStartValue(Comparable, Comparable)
*/
@Override
public Number getEndValue(Comparable rowKey, Comparable columnKey) {
int r = getRowIndex(rowKey);
int c = getColumnIndex(columnKey);
if (c != -1) {
return this.underlying.getEndValue(r, c + this.firstCategoryIndex);
}
else {
throw new UnknownKeyException("Unknown columnKey: " + columnKey);
}
}
/**
* Returns the end value for the interval for a given series and category.
*
* @param series the series (zero-based index).
* @param category the category (zero-based index).
*
* @return The end value (possibly <code>null</code>).
*/
@Override
public Number getEndValue(int series, int category) {
return this.underlying.getEndValue(series,
category + this.firstCategoryIndex);
}
/**
* Tests this <code>SlidingCategoryDataset</code> 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 SlidingGanttCategoryDataset)) {
return false;
}
SlidingGanttCategoryDataset that = (SlidingGanttCategoryDataset) obj;
if (this.firstCategoryIndex != that.firstCategoryIndex) {
return false;
}
if (this.maximumCategoryCount != that.maximumCategoryCount) {
return false;
}
if (!this.underlying.equals(that.underlying)) {
return false;
}
return true;
}
/**
* Returns an independent copy of the dataset. Note that:
* <ul>
* <li>the underlying dataset is only cloned if it implements the
* {@link PublicCloneable} interface;</li>
* <li>the listeners registered with this dataset are not carried over to
* the cloned dataset.</li>
* </ul>
*
* @return An independent copy of the dataset.
*
* @throws CloneNotSupportedException if the dataset cannot be cloned for
* any reason.
*/
@Override
public Object clone() throws CloneNotSupportedException {
SlidingGanttCategoryDataset clone
= (SlidingGanttCategoryDataset) super.clone();
if (this.underlying instanceof PublicCloneable) {
PublicCloneable pc = (PublicCloneable) this.underlying;
clone.underlying = (GanttCategoryDataset) pc.clone();
}
return clone;
}
}
| 19,591 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
XYTaskDataset.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/data/gantt/XYTaskDataset.java | /* ===========================================================
* JFreeChart : a free chart library for the Java(tm) platform
* ===========================================================
*
* (C) Copyright 2000-2011, 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.]
*
* ------------------
* XYTaskDataset.java
* ------------------
* (C) Copyright 2008, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 17-Sep-2008 : Version 1 (DG);
*
*/
package org.jfree.data.gantt;
import java.util.Date;
import org.jfree.chart.axis.SymbolAxis;
import org.jfree.chart.renderer.xy.XYBarRenderer;
import org.jfree.data.general.DatasetChangeEvent;
import org.jfree.data.general.DatasetChangeListener;
import org.jfree.data.time.TimePeriod;
import org.jfree.data.xy.AbstractXYDataset;
import org.jfree.data.xy.IntervalXYDataset;
/**
* A dataset implementation that wraps a {@link TaskSeriesCollection} and
* presents it as an {@link IntervalXYDataset}, allowing a set of tasks to
* be displayed using an {@link XYBarRenderer} (and usually a
* {@link SymbolAxis}). This is a very specialised dataset implementation
* ---before using it, you should take some time to understand the use-cases
* that it is designed for.
*
* @since 1.0.11
*/
public class XYTaskDataset extends AbstractXYDataset
implements IntervalXYDataset, DatasetChangeListener {
/** The underlying tasks. */
private TaskSeriesCollection underlying;
/** The series interval width (typically 0.0 < w <= 1.0). */
private double seriesWidth;
/** A flag that controls whether or not the data values are transposed. */
private boolean transposed;
/**
* Creates a new dataset based on the supplied collection of tasks.
*
* @param tasks the underlying dataset (<code>null</code> not permitted).
*/
public XYTaskDataset(TaskSeriesCollection tasks) {
if (tasks == null) {
throw new IllegalArgumentException("Null 'tasks' argument.");
}
this.underlying = tasks;
this.seriesWidth = 0.8;
this.underlying.addChangeListener(this);
}
/**
* Returns the underlying task series collection that was supplied to the
* constructor.
*
* @return The underlying collection (never <code>null</code>).
*/
public TaskSeriesCollection getTasks() {
return this.underlying;
}
/**
* Returns the width of the interval for each series this dataset.
*
* @return The width of the series interval.
*
* @see #setSeriesWidth(double)
*/
public double getSeriesWidth() {
return this.seriesWidth;
}
/**
* Sets the series interval width and sends a {@link DatasetChangeEvent} to
* all registered listeners.
*
* @param w the width.
*
* @see #getSeriesWidth()
*/
public void setSeriesWidth(double w) {
if (w <= 0.0) {
throw new IllegalArgumentException("Requires 'w' > 0.0.");
}
this.seriesWidth = w;
fireDatasetChanged();
}
/**
* Returns a flag that indicates whether or not the dataset is transposed.
* The default is <code>false</code> which means the x-values are integers
* corresponding to the series indices, and the y-values are millisecond
* values corresponding to the task date/time intervals. If the flag
* is set to <code>true</code>, the x and y-values are reversed.
*
* @return The flag.
*
* @see #setTransposed(boolean)
*/
public boolean isTransposed() {
return this.transposed;
}
/**
* Sets the flag that controls whether or not the dataset is transposed
* and sends a {@link DatasetChangeEvent} to all registered listeners.
*
* @param transposed the new flag value.
*
* @see #isTransposed()
*/
public void setTransposed(boolean transposed) {
this.transposed = transposed;
fireDatasetChanged();
}
/**
* Returns the number of series in the dataset.
*
* @return The series count.
*/
@Override
public int getSeriesCount() {
return this.underlying.getSeriesCount();
}
/**
* Returns the name of a series.
*
* @param series the series index (zero-based).
*
* @return The name of a series.
*/
@Override
public Comparable getSeriesKey(int series) {
return this.underlying.getSeriesKey(series);
}
/**
* Returns the number of items (tasks) in the specified series.
*
* @param series the series index (zero-based).
*
* @return The item count.
*/
@Override
public int getItemCount(int series) {
return this.underlying.getSeries(series).getItemCount();
}
/**
* Returns the x-value (as a double primitive) for an item within a series.
*
* @param series the series index (zero-based).
* @param item the item index (zero-based).
*
* @return The value.
*/
@Override
public double getXValue(int series, int item) {
if (!this.transposed) {
return getSeriesValue(series);
}
else {
return getItemValue(series, item);
}
}
/**
* Returns the starting date/time for the specified item (task) in the
* given series, measured in milliseconds since 1-Jan-1970 (as in
* java.util.Date).
*
* @param series the series index.
* @param item the item (or task) index.
*
* @return The start date/time.
*/
@Override
public double getStartXValue(int series, int item) {
if (!this.transposed) {
return getSeriesStartValue(series);
}
else {
return getItemStartValue(series, item);
}
}
/**
* Returns the ending date/time for the specified item (task) in the
* given series, measured in milliseconds since 1-Jan-1970 (as in
* java.util.Date).
*
* @param series the series index.
* @param item the item (or task) index.
*
* @return The end date/time.
*/
@Override
public double getEndXValue(int series, int item) {
if (!this.transposed) {
return getSeriesEndValue(series);
}
else {
return getItemEndValue(series, item);
}
}
/**
* Returns the x-value for the specified series.
*
* @param series the series index.
* @param item the item index.
*
* @return The x-value (in milliseconds).
*/
@Override
public Number getX(int series, int item) {
return getXValue(series, item);
}
/**
* Returns the starting date/time for the specified item (task) in the
* given series, measured in milliseconds since 1-Jan-1970 (as in
* java.util.Date).
*
* @param series the series index.
* @param item the item (or task) index.
*
* @return The start date/time.
*/
@Override
public Number getStartX(int series, int item) {
return getStartXValue(series, item);
}
/**
* Returns the ending date/time for the specified item (task) in the
* given series, measured in milliseconds since 1-Jan-1970 (as in
* java.util.Date).
*
* @param series the series index.
* @param item the item (or task) index.
*
* @return The end date/time.
*/
@Override
public Number getEndX(int series, int item) {
return getEndXValue(series, item);
}
/**
* Returns the y-value (as a double primitive) for an item within a series.
*
* @param series the series index (zero-based).
* @param item the item index (zero-based).
*
* @return The value.
*/
@Override
public double getYValue(int series, int item) {
if (!this.transposed) {
return getItemValue(series, item);
}
else {
return getSeriesValue(series);
}
}
/**
* Returns the starting value of the y-interval for an item in the
* given series.
*
* @param series the series index.
* @param item the item (or task) index.
*
* @return The y-interval start.
*/
@Override
public double getStartYValue(int series, int item) {
if (!this.transposed) {
return getItemStartValue(series, item);
}
else {
return getSeriesStartValue(series);
}
}
/**
* Returns the ending value of the y-interval for an item in the
* given series.
*
* @param series the series index.
* @param item the item (or task) index.
*
* @return The y-interval end.
*/
@Override
public double getEndYValue(int series, int item) {
if (!this.transposed) {
return getItemEndValue(series, item);
}
else {
return getSeriesEndValue(series);
}
}
/**
* Returns the y-value for the specified series/item. In this
* implementation, we return the series index as the y-value (this means
* that every item in the series has a constant integer value).
*
* @param series the series index.
* @param item the item index.
*
* @return The y-value.
*/
@Override
public Number getY(int series, int item) {
return getYValue(series, item);
}
/**
* Returns the starting value of the y-interval for an item in the
* given series.
*
* @param series the series index.
* @param item the item (or task) index.
*
* @return The y-interval start.
*/
@Override
public Number getStartY(int series, int item) {
return getStartYValue(series, item);
}
/**
* Returns the ending value of the y-interval for an item in the
* given series.
*
* @param series the series index.
* @param item the item (or task) index.
*
* @return The y-interval end.
*/
@Override
public Number getEndY(int series, int item) {
return getEndYValue(series, item);
}
private double getSeriesValue(int series) {
return series;
}
private double getSeriesStartValue(int series) {
return series - this.seriesWidth / 2.0;
}
private double getSeriesEndValue(int series) {
return series + this.seriesWidth / 2.0;
}
private double getItemValue(int series, int item) {
TaskSeries s = this.underlying.getSeries(series);
Task t = s.get(item);
TimePeriod duration = t.getDuration();
Date start = duration.getStart();
Date end = duration.getEnd();
return (start.getTime() + end.getTime()) / 2.0;
}
private double getItemStartValue(int series, int item) {
TaskSeries s = this.underlying.getSeries(series);
Task t = s.get(item);
TimePeriod duration = t.getDuration();
Date start = duration.getStart();
return start.getTime();
}
private double getItemEndValue(int series, int item) {
TaskSeries s = this.underlying.getSeries(series);
Task t = s.get(item);
TimePeriod duration = t.getDuration();
Date end = duration.getEnd();
return end.getTime();
}
/**
* Receives a change event from the underlying dataset and responds by
* firing a change event for this dataset.
*
* @param event the event.
*/
@Override
public void datasetChanged(DatasetChangeEvent event) {
fireDatasetChanged();
}
/**
* Tests this dataset 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 XYTaskDataset)) {
return false;
}
XYTaskDataset that = (XYTaskDataset) obj;
if (this.seriesWidth != that.seriesWidth) {
return false;
}
if (this.transposed != that.transposed) {
return false;
}
if (!this.underlying.equals(that.underlying)) {
return false;
}
return true;
}
/**
* Returns a clone of this dataset.
*
* @return A clone of this dataset.
*
* @throws CloneNotSupportedException if there is a problem cloning.
*/
@Override
public Object clone() throws CloneNotSupportedException {
XYTaskDataset clone = (XYTaskDataset) super.clone();
clone.underlying = (TaskSeriesCollection) this.underlying.clone();
return clone;
}
}
| 13,837 | 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/data/gantt/package-info.java | /**
* Data interfaces and classes for Gantt charts.
*/
package org.jfree.data.gantt;
| 87 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
TaskSeries.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/data/gantt/TaskSeries.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.]
*
* ---------------
* TaskSeries.java
* ---------------
* (C) Copyright 2002-2012, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 06-Jun-2002 : Version 1 (DG);
* 07-Oct-2002 : Fixed errors reported by Checkstyle (DG);
* 24-Oct-2002 : Added methods to get TimeAllocation by task index (DG);
* 10-Jan-2003 : Renamed GanttSeries --> TaskSeries (DG);
* 30-Jul-2004 : Added equals() method (DG);
* 09-May-2008 : Fixed cloning bug (DG);
* 16-Jun-2012 : Removed JCommon dependencies (DG);
*
*/
package org.jfree.data.gantt;
import java.util.Collections;
import java.util.List;
import org.jfree.chart.util.ObjectUtilities;
import org.jfree.data.general.Series;
/**
* A series that contains zero, one or many {@link Task} objects.
* <P>
* This class is used as a building block for the {@link TaskSeriesCollection}
* class that can be used to construct basic Gantt charts.
*/
public class TaskSeries extends Series {
/** Storage for the tasks in the series. */
private List<Task> tasks;
/**
* Constructs a new series with the specified name.
*
* @param name the series name (<code>null</code> not permitted).
*/
public TaskSeries(String name) {
super(name);
this.tasks = new java.util.ArrayList<Task>();
}
/**
* Adds a task to the series and sends a
* {@link org.jfree.data.general.SeriesChangeEvent} to all registered
* listeners.
*
* @param task the task (<code>null</code> not permitted).
*/
public void add(Task task) {
if (task == null) {
throw new IllegalArgumentException("Null 'task' argument.");
}
this.tasks.add(task);
fireSeriesChanged();
}
/**
* Removes a task from the series and sends
* a {@link org.jfree.data.general.SeriesChangeEvent}
* to all registered listeners.
*
* @param task the task.
*/
public void remove(Task task) {
this.tasks.remove(task);
fireSeriesChanged();
}
/**
* Removes all tasks from the series and sends
* a {@link org.jfree.data.general.SeriesChangeEvent}
* to all registered listeners.
*/
public void removeAll() {
this.tasks.clear();
fireSeriesChanged();
}
/**
* Returns the number of items in the series.
*
* @return The item count.
*/
@Override
public int getItemCount() {
return this.tasks.size();
}
/**
* Returns a task from the series.
*
* @param index the task index (zero-based).
*
* @return The task.
*/
public Task get(int index) {
return this.tasks.get(index);
}
/**
* Returns the task in the series that has the specified description.
*
* @param description the name (<code>null</code> not permitted).
*
* @return The task (possibly <code>null</code>).
*/
public Task get(String description) {
Task result = null;
for (Task t : this.tasks) {
if (t.getDescription().equals(description)) {
result = t;
break;
}
}
return result;
}
/**
* Returns an unmodifialble list of the tasks in the series.
*
* @return The tasks.
*/
public List<Task> getTasks() {
return Collections.unmodifiableList(this.tasks);
}
/**
* Tests this object 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 TaskSeries)) {
return false;
}
if (!super.equals(obj)) {
return false;
}
TaskSeries that = (TaskSeries) obj;
if (!this.tasks.equals(that.tasks)) {
return false;
}
return true;
}
/**
* Returns an independent copy of this series.
*
* @return A clone of the series.
*
* @throws CloneNotSupportedException if there is some problem cloning
* the dataset.
*/
@Override
public Object clone() throws CloneNotSupportedException {
TaskSeries clone = (TaskSeries) super.clone();
clone.tasks = ObjectUtilities.deepClone(this.tasks);
return clone;
}
}
| 5,772 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
TaskSeriesCollection.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/data/gantt/TaskSeriesCollection.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.]
*
* -------------------------
* TaskSeriesCollection.java
* -------------------------
* (C) Copyright 2002-2012, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): Thomas Schuster;
*
* Changes
* -------
* 06-Jun-2002 : Version 1 (DG);
* 07-Oct-2002 : Fixed errors reported by Checkstyle (DG);
* 24-Oct-2002 : Amendments for changes in CategoryDataset interface and
* CategoryToolTipGenerator interface (DG);
* 10-Jan-2003 : Renamed GanttSeriesCollection --> TaskSeriesCollection (DG);
* 04-Sep-2003 : Fixed bug 800324 (DG);
* 16-Sep-2003 : Implemented GanttCategoryDataset (DG);
* 12-Jan-2005 : Fixed bug 1099331 (DG);
* 18-Jan-2006 : Added new methods getSeries(int) and
* getSeries(Comparable) (DG);
* 09-May-2008 : Fixed cloning bug (DG);
* 16-Jun-2012 : Removed JCommon dependencies (DG);
*
*/
package org.jfree.data.gantt;
import java.io.Serializable;
import java.util.List;
import org.jfree.chart.util.ObjectUtilities;
import org.jfree.chart.util.PublicCloneable;
import org.jfree.data.general.AbstractSeriesDataset;
import org.jfree.data.general.SeriesChangeEvent;
import org.jfree.data.time.TimePeriod;
/**
* A collection of {@link TaskSeries} objects. This class provides one
* implementation of the {@link GanttCategoryDataset} interface.
*/
public class TaskSeriesCollection extends AbstractSeriesDataset
implements GanttCategoryDataset, Cloneable, PublicCloneable,
Serializable {
/** For serialization. */
private static final long serialVersionUID = -2065799050738449903L;
/**
* Storage for aggregate task keys (the task description is used as the
* key).
*/
private List<Comparable> keys;
/** Storage for the series. */
private List<TaskSeries> data;
/**
* Default constructor.
*/
public TaskSeriesCollection() {
this.keys = new java.util.ArrayList<Comparable>();
this.data = new java.util.ArrayList<TaskSeries>();
}
/**
* Returns a series from the collection.
*
* @param key the series key (<code>null</code> not permitted).
*
* @return The series.
*
* @since 1.0.1
*/
public TaskSeries getSeries(Comparable key) {
if (key == null) {
throw new NullPointerException("Null 'key' argument.");
}
TaskSeries result = null;
int index = getRowIndex(key);
if (index >= 0) {
result = getSeries(index);
}
return result;
}
/**
* Returns a series from the collection.
*
* @param series the series index (zero-based).
*
* @return The series.
*
* @since 1.0.1
*/
public TaskSeries getSeries(int series) {
if ((series < 0) || (series >= getSeriesCount())) {
throw new IllegalArgumentException("Series index out of bounds");
}
return this.data.get(series);
}
/**
* Returns the number of series in the collection.
*
* @return The series count.
*/
@Override
public int getSeriesCount() {
return getRowCount();
}
/**
* Returns the name of a series.
*
* @param series the series index (zero-based).
*
* @return The name of a series.
*/
@Override
public Comparable getSeriesKey(int series) {
TaskSeries ts = this.data.get(series);
return ts.getKey();
}
/**
* Returns the number of rows (series) in the collection.
*
* @return The series count.
*/
@Override
public int getRowCount() {
return this.data.size();
}
/**
* Returns the row keys. In this case, each series is a key.
*
* @return The row keys.
*/
@Override
public List getRowKeys() { //FIXME MMC this should be typed
return this.data;
}
/**
* Returns the number of column in the dataset.
*
* @return The column count.
*/
@Override
public int getColumnCount() {
return this.keys.size();
}
/**
* Returns a list of the column keys in the dataset.
*
* @return The category list.
*/
@Override
public List<Comparable> getColumnKeys() {
return this.keys;
}
/**
* Returns a column key.
*
* @param index the column index.
*
* @return The column key.
*/
@Override
public Comparable getColumnKey(int index) {
return this.keys.get(index);
}
/**
* Returns the column index for a column key.
*
* @param columnKey the column key (<code>null</code> not permitted).
*
* @return The column index.
*/
@Override
public int getColumnIndex(Comparable columnKey) {
if (columnKey == null) {
throw new IllegalArgumentException("Null 'columnKey' argument.");
}
return this.keys.indexOf(columnKey);
}
/**
* Returns the row index for the given row key.
*
* @param rowKey the row key.
*
* @return The index.
*/
@Override
public int getRowIndex(Comparable rowKey) {
int result = -1;
int count = this.data.size();
for (int i = 0; i < count; i++) {
TaskSeries s = this.data.get(i);
if (s.getKey().equals(rowKey)) {
result = i;
break;
}
}
return result;
}
/**
* Returns the key for a row.
*
* @param index the row index (zero-based).
*
* @return The key.
*/
@Override
public Comparable getRowKey(int index) {
TaskSeries series = this.data.get(index);
return series.getKey();
}
/**
* Adds a series to the dataset and sends a
* {@link org.jfree.data.general.DatasetChangeEvent} to all registered
* listeners.
*
* @param series the series (<code>null</code> not permitted).
*/
public void add(TaskSeries series) {
if (series == null) {
throw new IllegalArgumentException("Null 'series' argument.");
}
this.data.add(series);
series.addChangeListener(this);
// look for any keys that we don't already know about...
for (Task task : series.getTasks()) {
String key = task.getDescription();
int index = this.keys.indexOf(key);
if (index < 0) {
this.keys.add(key);
}
}
fireDatasetChanged();
}
/**
* Removes a series from the collection and sends
* a {@link org.jfree.data.general.DatasetChangeEvent}
* to all registered listeners.
*
* @param series the series.
*/
public void remove(TaskSeries series) {
if (series == null) {
throw new IllegalArgumentException("Null 'series' argument.");
}
if (this.data.contains(series)) {
series.removeChangeListener(this);
this.data.remove(series);
fireDatasetChanged();
}
}
/**
* Removes a series from the collection and sends
* a {@link org.jfree.data.general.DatasetChangeEvent}
* to all registered listeners.
*
* @param series the series (zero based index).
*/
public void remove(int series) {
if ((series < 0) || (series >= getSeriesCount())) {
throw new IllegalArgumentException(
"TaskSeriesCollection.remove(): index outside valid range.");
}
// fetch the series, remove the change listener, then remove the series.
TaskSeries ts = this.data.get(series);
ts.removeChangeListener(this);
this.data.remove(series);
fireDatasetChanged();
}
/**
* Removes all the series from the collection and sends
* a {@link org.jfree.data.general.DatasetChangeEvent}
* to all registered listeners.
*/
public void removeAll() {
// deregister the collection as a change listener to each series in
// the collection.
for (TaskSeries series : this.data) {
series.removeChangeListener(this);
}
// remove all the series from the collection and notify listeners.
this.data.clear();
fireDatasetChanged();
}
/**
* Returns the value for an item.
*
* @param rowKey the row key.
* @param columnKey the column key.
*
* @return The item value.
*/
@Override
public Number getValue(Comparable rowKey, Comparable columnKey) {
return getStartValue(rowKey, columnKey);
}
/**
* Returns the value for a task.
*
* @param row the row index (zero-based).
* @param column the column index (zero-based).
*
* @return The start value.
*/
@Override
public Number getValue(int row, int column) {
return getStartValue(row, column);
}
/**
* Returns the start value for a task. This is a date/time value, measured
* in milliseconds since 1-Jan-1970.
*
* @param rowKey the series.
* @param columnKey the category.
*
* @return The start value (possibly <code>null</code>).
*/
@Override
public Number getStartValue(Comparable rowKey, Comparable columnKey) {
Number result = null;
int row = getRowIndex(rowKey);
TaskSeries series = this.data.get(row);
Task task = series.get(columnKey.toString());
if (task != null) {
TimePeriod duration = task.getDuration();
if (duration != null) {
result = duration.getStart().getTime();
}
}
return result;
}
/**
* Returns the start value for a task.
*
* @param row the row index (zero-based).
* @param column the column index (zero-based).
*
* @return The start value.
*/
@Override
public Number getStartValue(int row, int column) {
Comparable rowKey = getRowKey(row);
Comparable columnKey = getColumnKey(column);
return getStartValue(rowKey, columnKey);
}
/**
* Returns the end value for a task. This is a date/time value, measured
* in milliseconds since 1-Jan-1970.
*
* @param rowKey the series.
* @param columnKey the category.
*
* @return The end value (possibly <code>null</code>).
*/
@Override
public Number getEndValue(Comparable rowKey, Comparable columnKey) {
Number result = null;
int row = getRowIndex(rowKey);
TaskSeries series = this.data.get(row);
Task task = series.get(columnKey.toString());
if (task != null) {
TimePeriod duration = task.getDuration();
if (duration != null) {
result = duration.getEnd().getTime();
}
}
return result;
}
/**
* Returns the end value for a task.
*
* @param row the row index (zero-based).
* @param column the column index (zero-based).
*
* @return The end value.
*/
@Override
public Number getEndValue(int row, int column) {
Comparable rowKey = getRowKey(row);
Comparable columnKey = getColumnKey(column);
return getEndValue(rowKey, columnKey);
}
/**
* Returns the percent complete for a given item.
*
* @param row the row index (zero-based).
* @param column the column index (zero-based).
*
* @return The percent complete (possibly <code>null</code>).
*/
@Override
public Number getPercentComplete(int row, int column) {
Comparable rowKey = getRowKey(row);
Comparable columnKey = getColumnKey(column);
return getPercentComplete(rowKey, columnKey);
}
/**
* Returns the percent complete for a given item.
*
* @param rowKey the row key.
* @param columnKey the column key.
*
* @return The percent complete.
*/
@Override
public Number getPercentComplete(Comparable rowKey, Comparable columnKey) {
Number result = null;
int row = getRowIndex(rowKey);
TaskSeries series = this.data.get(row);
Task task = series.get(columnKey.toString());
if (task != null) {
result = task.getPercentComplete();
}
return result;
}
/**
* Returns the number of sub-intervals for a given item.
*
* @param row the row index (zero-based).
* @param column the column index (zero-based).
*
* @return The sub-interval count.
*/
@Override
public int getSubIntervalCount(int row, int column) {
Comparable rowKey = getRowKey(row);
Comparable columnKey = getColumnKey(column);
return getSubIntervalCount(rowKey, columnKey);
}
/**
* Returns the number of sub-intervals for a given item.
*
* @param rowKey the row key.
* @param columnKey the column key.
*
* @return The sub-interval count.
*/
@Override
public int getSubIntervalCount(Comparable rowKey, Comparable columnKey) {
int result = 0;
int row = getRowIndex(rowKey);
TaskSeries series = this.data.get(row);
Task task = series.get(columnKey.toString());
if (task != null) {
result = task.getSubtaskCount();
}
return result;
}
/**
* Returns the start value of a sub-interval for a given item.
*
* @param row the row index (zero-based).
* @param column the column index (zero-based).
* @param subinterval the sub-interval index (zero-based).
*
* @return The start value (possibly <code>null</code>).
*/
@Override
public Number getStartValue(int row, int column, int subinterval) {
Comparable rowKey = getRowKey(row);
Comparable columnKey = getColumnKey(column);
return getStartValue(rowKey, columnKey, subinterval);
}
/**
* Returns the start value of a sub-interval for a given item.
*
* @param rowKey the row key.
* @param columnKey the column key.
* @param subinterval the subinterval.
*
* @return The start value (possibly <code>null</code>).
*/
@Override
public Number getStartValue(Comparable rowKey, Comparable columnKey,
int subinterval) {
Number result = null;
int row = getRowIndex(rowKey);
TaskSeries series = this.data.get(row);
Task task = series.get(columnKey.toString());
if (task != null) {
Task sub = task.getSubtask(subinterval);
if (sub != null) {
TimePeriod duration = sub.getDuration();
result = duration.getStart().getTime();
}
}
return result;
}
/**
* Returns the end value of a sub-interval for a given item.
*
* @param row the row index (zero-based).
* @param column the column index (zero-based).
* @param subinterval the subinterval.
*
* @return The end value (possibly <code>null</code>).
*/
@Override
public Number getEndValue(int row, int column, int subinterval) {
Comparable rowKey = getRowKey(row);
Comparable columnKey = getColumnKey(column);
return getEndValue(rowKey, columnKey, subinterval);
}
/**
* Returns the end value of a sub-interval for a given item.
*
* @param rowKey the row key.
* @param columnKey the column key.
* @param subinterval the subinterval.
*
* @return The end value (possibly <code>null</code>).
*/
@Override
public Number getEndValue(Comparable rowKey, Comparable columnKey,
int subinterval) {
Number result = null;
int row = getRowIndex(rowKey);
TaskSeries series = this.data.get(row);
Task task = series.get(columnKey.toString());
if (task != null) {
Task sub = task.getSubtask(subinterval);
if (sub != null) {
TimePeriod duration = sub.getDuration();
result = duration.getEnd().getTime();
}
}
return result;
}
/**
* Returns the percentage complete value of a sub-interval for a given item.
*
* @param row the row index (zero-based).
* @param column the column index (zero-based).
* @param subinterval the sub-interval.
*
* @return The percent complete value (possibly <code>null</code>).
*/
@Override
public Number getPercentComplete(int row, int column, int subinterval) {
Comparable rowKey = getRowKey(row);
Comparable columnKey = getColumnKey(column);
return getPercentComplete(rowKey, columnKey, subinterval);
}
/**
* Returns the percentage complete value of a sub-interval for a given item.
*
* @param rowKey the row key.
* @param columnKey the column key.
* @param subinterval the sub-interval.
*
* @return The percent complete value (possibly <code>null</code>).
*/
@Override
public Number getPercentComplete(Comparable rowKey, Comparable columnKey,
int subinterval) {
Number result = null;
int row = getRowIndex(rowKey);
TaskSeries series = this.data.get(row);
Task task = series.get(columnKey.toString());
if (task != null) {
Task sub = task.getSubtask(subinterval);
if (sub != null) {
result = sub.getPercentComplete();
}
}
return result;
}
/**
* Called when a series belonging to the dataset changes.
*
* @param event information about the change.
*/
@Override
public void seriesChanged(SeriesChangeEvent event) {
refreshKeys();
fireDatasetChanged();
}
/**
* Refreshes the keys.
*/
private void refreshKeys() {
this.keys.clear();
for (int i = 0; i < getSeriesCount(); i++) {
TaskSeries series = this.data.get(i);
// look for any keys that we don't already know about...
for (Task task : series.getTasks()) {
String key = task.getDescription();
int index = this.keys.indexOf(key);
if (index < 0) {
this.keys.add(key);
}
}
}
}
/**
* 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 TaskSeriesCollection)) {
return false;
}
TaskSeriesCollection that = (TaskSeriesCollection) obj;
if (!ObjectUtilities.equal(this.data, that.data)) {
return false;
}
return true;
}
/**
* Returns an independent copy of this dataset.
*
* @return A clone of the dataset.
*
* @throws CloneNotSupportedException if there is some problem cloning
* the dataset.
*/
@Override
public Object clone() throws CloneNotSupportedException {
TaskSeriesCollection clone = (TaskSeriesCollection) super.clone();
clone.data = ObjectUtilities.deepClone(this.data);
clone.keys = new java.util.ArrayList<Comparable>(this.keys);
return clone;
}
}
| 20,921 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
GanttCategoryDataset.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/data/gantt/GanttCategoryDataset.java | /* ===========================================================
* JFreeChart : a free chart library for the Java(tm) platform
* ===========================================================
*
* (C) Copyright 2000-2011, 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.]
*
* -------------------------
* GanttCategoryDataset.java
* -------------------------
* (C) Copyright 2003-2008, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 16-Sep-2003 : Version 1, based on MultiIntervalCategoryDataset (DG);
* 23-Sep-2003 : Fixed Checkstyle issues (DG);
* 12-May-2008 : Updated API docs (DG);
*
*/
package org.jfree.data.gantt;
import org.jfree.data.category.IntervalCategoryDataset;
/**
* An extension of the {@link IntervalCategoryDataset} interface that adds
* support for multiple sub-intervals.
*/
public interface GanttCategoryDataset extends IntervalCategoryDataset {
/**
* Returns the percent complete for a given item.
*
* @param row the row index (zero-based).
* @param column the column index (zero-based).
*
* @return The percent complete.
*
* @see #getPercentComplete(Comparable, Comparable)
*/
public Number getPercentComplete(int row, int column);
/**
* Returns the percent complete for a given item.
*
* @param rowKey the row key.
* @param columnKey the column key.
*
* @return The percent complete.
*
* @see #getPercentComplete(int, int)
*/
public Number getPercentComplete(Comparable rowKey, Comparable columnKey);
/**
* Returns the number of sub-intervals for a given item.
*
* @param row the row index (zero-based).
* @param column the column index (zero-based).
*
* @return The sub-interval count.
*
* @see #getSubIntervalCount(Comparable, Comparable)
*/
public int getSubIntervalCount(int row, int column);
/**
* Returns the number of sub-intervals for a given item.
*
* @param rowKey the row key.
* @param columnKey the column key.
*
* @return The sub-interval count.
*
* @see #getSubIntervalCount(int, int)
*/
public int getSubIntervalCount(Comparable rowKey, Comparable columnKey);
/**
* Returns the start value of a sub-interval for a given item.
*
* @param row the row index (zero-based).
* @param column the column index (zero-based).
* @param subinterval the sub-interval index (zero-based).
*
* @return The start value (possibly <code>null</code>).
*
* @see #getEndValue(int, int, int)
*/
public Number getStartValue(int row, int column, int subinterval);
/**
* Returns the start value of a sub-interval for a given item.
*
* @param rowKey the row key.
* @param columnKey the column key.
* @param subinterval the sub-interval.
*
* @return The start value (possibly <code>null</code>).
*
* @see #getEndValue(Comparable, Comparable, int)
*/
public Number getStartValue(Comparable rowKey, Comparable columnKey,
int subinterval);
/**
* Returns the end value of a sub-interval for a given item.
*
* @param row the row index (zero-based).
* @param column the column index (zero-based).
* @param subinterval the sub-interval.
*
* @return The end value (possibly <code>null</code>).
*
* @see #getStartValue(int, int, int)
*/
public Number getEndValue(int row, int column, int subinterval);
/**
* Returns the end value of a sub-interval for a given item.
*
* @param rowKey the row key.
* @param columnKey the column key.
* @param subinterval the sub-interval.
*
* @return The end value (possibly <code>null</code>).
*
* @see #getStartValue(Comparable, Comparable, int)
*/
public Number getEndValue(Comparable rowKey, Comparable columnKey,
int subinterval);
/**
* Returns the percentage complete value of a sub-interval for a given item.
*
* @param row the row index (zero-based).
* @param column the column index (zero-based).
* @param subinterval the sub-interval.
*
* @return The percent complete value (possibly <code>null</code>).
*
* @see #getPercentComplete(Comparable, Comparable, int)
*/
public Number getPercentComplete(int row, int column, int subinterval);
/**
* Returns the percentage complete value of a sub-interval for a given item.
*
* @param rowKey the row key.
* @param columnKey the column key.
* @param subinterval the sub-interval.
*
* @return The percent complete value (possibly <code>null</code>).
*
* @see #getPercentComplete(int, int, int)
*/
public Number getPercentComplete(Comparable rowKey, Comparable columnKey,
int subinterval);
}
| 6,040 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
Task.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/data/gantt/Task.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.]
*
* ---------
* Task.java
* ---------
* (C) Copyright 2003-2012, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 10-Jan-2003 : Version 1 (DG);
* 16-Sep-2003 : Added percentage complete (DG);
* 30-Jul-2004 : Added clone() and equals() methods and implemented
* Serializable (DG);
* 16-Jun-2012 : Removed JCommon dependencies (DG);
*
*/
package org.jfree.data.gantt;
import org.jfree.chart.util.ObjectUtilities;
import org.jfree.chart.util.PublicCloneable;
import org.jfree.data.time.SimpleTimePeriod;
import org.jfree.data.time.TimePeriod;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
/**
* A simple representation of a task. The task has a description and a
* duration. You can add sub-tasks to the task.
*/
public class Task implements Cloneable, PublicCloneable, Serializable {
/** For serialization. */
private static final long serialVersionUID = 1094303785346988894L;
/** The task description. */
private String description;
/** The time period for the task (estimated or actual). */
private TimePeriod duration;
/** The percent complete (<code>null</code> is permitted). */
private Double percentComplete;
/** Storage for the sub-tasks (if any). */
private List<Task> subtasks;
/**
* Creates a new task.
*
* @param description the task description (<code>null</code> not
* permitted).
* @param duration the task duration (<code>null</code> permitted).
*/
public Task(String description, TimePeriod duration) {
if (description == null) {
throw new IllegalArgumentException("Null 'description' argument.");
}
this.description = description;
this.duration = duration;
this.percentComplete = null;
this.subtasks = new java.util.ArrayList<Task>();
}
/**
* Creates a new task.
*
* @param description the task description (<code>null</code> not
* permitted).
* @param start the start date (<code>null</code> not permitted).
* @param end the end date (<code>null</code> not permitted).
*/
public Task(String description, Date start, Date end) {
this(description, new SimpleTimePeriod(start, end));
}
/**
* Returns the task description.
*
* @return The task description (never <code>null</code>).
*/
public String getDescription() {
return this.description;
}
/**
* Sets the task description.
*
* @param description the description (<code>null</code> not permitted).
*/
public void setDescription(String description) {
if (description == null) {
throw new IllegalArgumentException("Null 'description' argument.");
}
this.description = description;
}
/**
* Returns the duration (actual or estimated) of the task.
*
* @return The task duration (possibly <code>null</code>).
*/
public TimePeriod getDuration() {
return this.duration;
}
/**
* Sets the task duration (actual or estimated).
*
* @param duration the duration (<code>null</code> permitted).
*/
public void setDuration(TimePeriod duration) {
this.duration = duration;
}
/**
* Returns the percentage complete for this task.
*
* @return The percentage complete (possibly <code>null</code>).
*/
public Double getPercentComplete() {
return this.percentComplete;
}
/**
* Sets the percentage complete for the task.
*
* @param percent the percentage (<code>null</code> permitted).
*/
public void setPercentComplete(Double percent) {
this.percentComplete = percent;
}
/**
* Sets the percentage complete for the task.
*
* @param percent the percentage.
*/
public void setPercentComplete(double percent) {
setPercentComplete(new Double(percent));
}
/**
* Adds a sub-task to the task.
*
* @param subtask the subtask (<code>null</code> not permitted).
*/
public void addSubtask(Task subtask) {
if (subtask == null) {
throw new IllegalArgumentException("Null 'subtask' argument.");
}
this.subtasks.add(subtask);
}
/**
* Removes a sub-task from the task.
*
* @param subtask the subtask.
*/
public void removeSubtask(Task subtask) {
this.subtasks.remove(subtask);
}
/**
* Returns the sub-task count.
*
* @return The sub-task count.
*/
public int getSubtaskCount() {
return this.subtasks.size();
}
/**
* Returns a sub-task.
*
* @param index the index.
*
* @return The sub-task.
*/
public Task getSubtask(int index) {
return this.subtasks.get(index);
}
/**
* Tests this object for equality with an arbitrary object.
*
* @param object the other object (<code>null</code> permitted).
*
* @return A boolean.
*/
@Override
public boolean equals(Object object) {
if (object == this) {
return true;
}
if (!(object instanceof Task)) {
return false;
}
Task that = (Task) object;
if (!ObjectUtilities.equal(this.description, that.description)) {
return false;
}
if (!ObjectUtilities.equal(this.duration, that.duration)) {
return false;
}
if (!ObjectUtilities.equal(this.percentComplete,
that.percentComplete)) {
return false;
}
if (!ObjectUtilities.equal(this.subtasks, that.subtasks)) {
return false;
}
return true;
}
/**
* Returns a clone of the task.
*
* @return A clone.
*
* @throws CloneNotSupportedException never thrown by this class, but
* subclasses may not support cloning.
*/
@Override
public Object clone() throws CloneNotSupportedException {
Task clone = (Task) super.clone();
return clone;
}
}
| 7,519 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
MouseWheelHandler.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/MouseWheelHandler.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.]
*
* ----------------------
* MouseWheelHandler.java
* ----------------------
* (C) Copyright 2009, by Object Refinery Limited and Contributors.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): Ulrich Voigt - patch 2686040;
* Jim Goodwin - bug fix;
*
* Changes
* -------
* 18-Mar-2009 : Version 1, based on ideas by UV in patch 2686040 (DG);
* 26-Mar-2009 : Implemented Serializable (DG);
* 10-Sep-2009 : Bug fix by Jim Goodwin to respect domain/rangeZoomable flags
* in the ChartPanel (DG);
* 04-Nov-2009 : Pass mouse wheel notification to PiePlot (DG);
*
*/
package org.jfree.chart;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.awt.geom.Point2D;
import java.io.Serializable;
import org.jfree.chart.plot.PiePlot;
import org.jfree.chart.plot.Plot;
import org.jfree.chart.plot.PlotRenderingInfo;
import org.jfree.chart.plot.Zoomable;
/**
* A class that handles mouse wheel events for the {@link ChartPanel} class.
* Mouse wheel event support was added in JDK 1.4, so this class will be omitted
* from JFreeChart if you build it using JDK 1.3.
*
* @since 1.0.13
*/
class MouseWheelHandler implements MouseWheelListener, Serializable {
/** The chart panel. */
private ChartPanel chartPanel;
/** The zoom factor. */
double zoomFactor;
/**
* Creates a new instance for the specified chart panel.
*
* @param chartPanel the chart panel (<code>null</code> not permitted).
*/
public MouseWheelHandler(ChartPanel chartPanel) {
this.chartPanel = chartPanel;
this.zoomFactor = 0.10;
this.chartPanel.addMouseWheelListener(this);
}
/**
* Returns the current zoom factor. The default value is 0.10 (ten
* percent).
*
* @return The zoom factor.
*
* @see #setZoomFactor(double)
*/
public double getZoomFactor() {
return this.zoomFactor;
}
/**
* Sets the zoom factor.
*
* @param zoomFactor the zoom factor.
*
* @see #getZoomFactor()
*/
public void setZoomFactor(double zoomFactor) {
this.zoomFactor = zoomFactor;
}
/**
* Handles a mouse wheel event from the underlying chart panel.
*
* @param e the event.
*/
@Override
public void mouseWheelMoved(MouseWheelEvent e) {
JFreeChart chart = this.chartPanel.getChart();
if (chart == null) {
return;
}
Plot plot = chart.getPlot();
if (plot instanceof Zoomable) {
Zoomable zoomable = (Zoomable) plot;
handleZoomable(zoomable, e);
}
else if (plot instanceof PiePlot) {
PiePlot pp = (PiePlot) plot;
pp.handleMouseWheelRotation(e.getWheelRotation());
}
}
/**
* Handle the case where a plot implements the {@link Zoomable} interface.
*
* @param zoomable the zoomable plot.
* @param e the mouse wheel event.
*/
private void handleZoomable(Zoomable zoomable, MouseWheelEvent e) {
// don't zoom unless the mouse pointer is in the plot's data area
ChartRenderingInfo info = this.chartPanel.getChartRenderingInfo();
PlotRenderingInfo pinfo = info.getPlotInfo();
Point2D p = this.chartPanel.translateScreenToJava2D(e.getPoint());
if (!pinfo.getDataArea().contains(p)) {
return;
}
Plot plot = (Plot) zoomable;
// do not notify while zooming each axis
boolean notifyState = plot.isNotify();
plot.setNotify(false);
int clicks = e.getWheelRotation();
double zf = 1.0 + this.zoomFactor;
if (clicks < 0) {
zf = 1.0 / zf;
}
if (this.chartPanel.isDomainZoomable()) {
zoomable.zoomDomainAxes(zf, pinfo, p, true);
}
if (this.chartPanel.isRangeZoomable()) {
zoomable.zoomRangeAxes(zf, pinfo, p, true);
}
plot.setNotify(notifyState); // this generates the change event too
}
}
| 5,336 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
ChartRenderingInfo.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/ChartRenderingInfo.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.]
*
* -----------------------
* ChartRenderingInfo.java
* -----------------------
* (C) Copyright 2002-2012, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 22-Jan-2002 : Version 1 (DG);
* 05-Feb-2002 : Added a new constructor, completed Javadoc comments (DG);
* 05-Mar-2002 : Added a clear() method (DG);
* 23-May-2002 : Renamed DrawInfo --> ChartRenderingInfo (DG);
* 26-Sep-2002 : Fixed errors reported by Checkstyle (DG);
* 17-Sep-2003 : Added PlotRenderingInfo (DG);
* 01-Nov-2005 : Updated equals() method (DG);
* 30-Nov-2005 : Removed get/setPlotArea() (DG);
* ------------- JFREECHART 1.0.x ---------------------------------------------
* 01-Dec-2006 : Fixed equals() and clone() (DG);
* 16-Jun-2012 : Removed JCommon dependencies (DG);
*
*/
package org.jfree.chart;
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.util.ObjectUtilities;
import org.jfree.chart.util.PublicCloneable;
import org.jfree.chart.entity.EntityCollection;
import org.jfree.chart.entity.StandardEntityCollection;
import org.jfree.chart.plot.PlotRenderingInfo;
import org.jfree.chart.util.SerialUtilities;
/**
* A structure for storing rendering information from one call to the
* JFreeChart.draw() method.
* <P>
* An instance of the {@link JFreeChart} class can draw itself within an
* arbitrary rectangle on any <code>Graphics2D</code>. It is assumed that
* client code will sometimes render the same chart in more than one view, so
* the {@link JFreeChart} instance does not retain any information about its
* rendered dimensions. This information can be useful sometimes, so you have
* the option to collect the information at each call to
* <code>JFreeChart.draw()</code>, by passing an instance of this
* <code>ChartRenderingInfo</code> class.
*/
public class ChartRenderingInfo implements Cloneable, Serializable {
/** For serialization. */
private static final long serialVersionUID = 2751952018173406822L;
/** The area in which the chart is drawn. */
private transient Rectangle2D chartArea;
/** Rendering info for the chart's plot (and subplots, if any). */
private PlotRenderingInfo plotInfo;
/**
* Storage for the chart entities. Since retaining entity information for
* charts with a large number of data points consumes a lot of memory, it
* is intended that you can set this to <code>null</code> to prevent the
* information being collected.
*/
private EntityCollection entities;
/**
* Constructs a new ChartRenderingInfo structure that can be used to
* collect information about the dimensions of a rendered chart.
*/
public ChartRenderingInfo() {
this(new StandardEntityCollection());
}
/**
* Constructs a new instance. If an entity collection is supplied, it will
* be populated with information about the entities in a chart. If it is
* <code>null</code>, no entity information (including tool tips) will
* be collected.
*
* @param entities an entity collection (<code>null</code> permitted).
*/
public ChartRenderingInfo(EntityCollection entities) {
this.chartArea = new Rectangle2D.Double();
this.plotInfo = new PlotRenderingInfo(this);
this.entities = entities;
}
/**
* Returns the area in which the chart was drawn.
*
* @return The area in which the chart was drawn.
*
* @see #setChartArea(Rectangle2D)
*/
public Rectangle2D getChartArea() {
return this.chartArea;
}
/**
* Sets the area in which the chart was drawn.
*
* @param area the chart area.
*
* @see #getChartArea()
*/
public void setChartArea(Rectangle2D area) {
this.chartArea.setRect(area);
}
/**
* Returns the collection of entities maintained by this instance.
*
* @return The entity collection (possibly <code>null</code>).
*
* @see #setEntityCollection(EntityCollection)
*/
public EntityCollection getEntityCollection() {
return this.entities;
}
/**
* Sets the entity collection.
*
* @param entities the entity collection (<code>null</code> permitted).
*
* @see #getEntityCollection()
*/
public void setEntityCollection(EntityCollection entities) {
this.entities = entities;
}
/**
* Clears the information recorded by this object.
*/
public void clear() {
this.chartArea.setRect(0.0, 0.0, 0.0, 0.0);
this.plotInfo = new PlotRenderingInfo(this);
if (this.entities != null) {
this.entities.clear();
}
}
/**
* Returns the rendering info for the chart's plot.
*
* @return The rendering info for the plot.
*/
public PlotRenderingInfo getPlotInfo() {
return this.plotInfo;
}
/**
* Tests this object 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 ChartRenderingInfo)) {
return false;
}
ChartRenderingInfo that = (ChartRenderingInfo) obj;
if (!ObjectUtilities.equal(this.chartArea, that.chartArea)) {
return false;
}
if (!ObjectUtilities.equal(this.plotInfo, that.plotInfo)) {
return false;
}
if (!ObjectUtilities.equal(this.entities, that.entities)) {
return false;
}
return true;
}
/**
* Returns a clone of this object.
*
* @return A clone.
*
* @throws CloneNotSupportedException if the object cannot be cloned.
*/
@Override
public Object clone() throws CloneNotSupportedException {
ChartRenderingInfo clone = (ChartRenderingInfo) super.clone();
if (this.chartArea != null) {
clone.chartArea = (Rectangle2D) this.chartArea.clone();
}
if (this.entities instanceof PublicCloneable) {
PublicCloneable pc = (PublicCloneable) this.entities;
clone.entities = (EntityCollection) pc.clone();
}
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.chartArea, 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.chartArea = (Rectangle2D) SerialUtilities.readShape(stream);
}
}
| 8,573 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
HashUtilities.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/HashUtilities.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.]
*
* ------------------
* HashUtilities.java
* ------------------
* (C) Copyright 2006-2012, by Object Refinery Limited;
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 03-Oct-2006 : Version 1 (DG);
* 06-Mar-2007 : Fix for hashCodeForDoubleArray() method (DG);
* 13-Nov-2007 : Added new utility methods (DG);
* 22-Nov-2007 : Added hashCode() method for 'int' (DG);
* 05-Dec-2007 : Added special methods to handle BooleanList, PaintList,
* and StrokeList (DG);
* 15-Jun-2012 : Removed JCommon dependency (DG);
*
*/
package org.jfree.chart;
import java.awt.GradientPaint;
import java.awt.Paint;
import java.awt.Stroke;
import org.jfree.chart.util.BooleanList;
import org.jfree.chart.util.PaintList;
import org.jfree.chart.util.StrokeList;
/**
* Some utility methods for calculating hash codes.
*
* @since 1.0.3
*/
public class HashUtilities {
/**
* Returns a hash code for a <code>Paint</code> instance. If
* <code>p</code> is <code>null</code>, this method returns zero.
*
* @param p the paint (<code>null</code> permitted).
*
* @return The hash code.
*/
public static int hashCodeForPaint(Paint p) {
if (p == null) {
return 0;
}
int result = 0;
// handle GradientPaint as a special case
if (p instanceof GradientPaint) {
GradientPaint gp = (GradientPaint) p;
result = 193;
result = 37 * result + gp.getColor1().hashCode();
result = 37 * result + gp.getPoint1().hashCode();
result = 37 * result + gp.getColor2().hashCode();
result = 37 * result + gp.getPoint2().hashCode();
}
else {
// we assume that all other Paint instances implement equals() and
// hashCode()...of course that might not be true, but what can we
// do about it?
result = p.hashCode();
}
return result;
}
/**
* Returns a hash code for a <code>double[]</code> instance. If the array
* is <code>null</code>, this method returns zero.
*
* @param a the array (<code>null</code> permitted).
*
* @return The hash code.
*/
public static int hashCodeForDoubleArray(double[] a) {
if (a == null) {
return 0;
}
int result = 193;
long temp;
for (double anA : a) {
temp = Double.doubleToLongBits(anA);
result = 29 * result + (int) (temp ^ (temp >>> 32));
}
return result;
}
/**
* Returns a hash value based on a seed value and the value of a boolean
* primitive.
*
* @param pre the seed value.
* @param b the boolean value.
*
* @return A hash value.
*
* @since 1.0.7
*/
public static int hashCode(int pre, boolean b) {
return 37 * pre + (b ? 0 : 1);
}
/**
* Returns a hash value based on a seed value and the value of an int
* primitive.
*
* @param pre the seed value.
* @param i the int value.
*
* @return A hash value.
*
* @since 1.0.8
*/
public static int hashCode(int pre, int i) {
return 37 * pre + i;
}
/**
* Returns a hash value based on a seed value and the value of a double
* primitive.
*
* @param pre the seed value.
* @param d the double value.
*
* @return A hash value.
*
* @since 1.0.7
*/
public static int hashCode(int pre, double d) {
long l = Double.doubleToLongBits(d);
return 37 * pre + (int) (l ^ (l >>> 32));
}
/**
* Returns a hash value based on a seed value and a paint instance.
*
* @param pre the seed value.
* @param p the paint (<code>null</code> permitted).
*
* @return A hash value.
*
* @since 1.0.7
*/
public static int hashCode(int pre, Paint p) {
return 37 * pre + hashCodeForPaint(p);
}
/**
* Returns a hash value based on a seed value and a stroke instance.
*
* @param pre the seed value.
* @param s the stroke (<code>null</code> permitted).
*
* @return A hash value.
*
* @since 1.0.7
*/
public static int hashCode(int pre, Stroke s) {
int h = (s != null ? s.hashCode() : 0);
return 37 * pre + h;
}
/**
* Returns a hash value based on a seed value and a string instance.
*
* @param pre the seed value.
* @param s the string (<code>null</code> permitted).
*
* @return A hash value.
*
* @since 1.0.7
*/
public static int hashCode(int pre, String s) {
int h = (s != null ? s.hashCode() : 0);
return 37 * pre + h;
}
/**
* Returns a hash value based on a seed value and a <code>Comparable</code>
* instance.
*
* @param pre the seed value.
* @param c the comparable (<code>null</code> permitted).
*
* @return A hash value.
*
* @since 1.0.7
*/
public static int hashCode(int pre, Comparable c) {
int h = (c != null ? c.hashCode() : 0);
return 37 * pre + h;
}
/**
* Returns a hash value based on a seed value and an <code>Object</code>
* instance.
*
* @param pre the seed value.
* @param obj the object (<code>null</code> permitted).
*
* @return A hash value.
*
* @since 1.0.8
*/
public static int hashCode(int pre, Object obj) {
int h = (obj != null ? obj.hashCode() : 0);
return 37 * pre + h;
}
/**
* Computes a hash code for a {@link BooleanList}. In the latest version
* of JCommon, the {@link BooleanList} class should implement the hashCode()
* method correctly, but we compute it here anyway so that we can work with
* older versions of JCommon (back to 1.0.0).
*
* @param pre the seed value.
* @param list the list (<code>null</code> permitted).
*
* @return The hash code.
*
* @since 1.0.9
*/
public static int hashCode(int pre, BooleanList list) {
if (list == null) {
return pre;
}
int result = 127;
int size = list.size();
result = HashUtilities.hashCode(result, size);
// for efficiency, we just use the first, last and middle items to
// compute a hashCode...
if (size > 0) {
result = HashUtilities.hashCode(result, list.getBoolean(0));
if (size > 1) {
result = HashUtilities.hashCode(result,
list.getBoolean(size - 1));
if (size > 2) {
result = HashUtilities.hashCode(result,
list.getBoolean(size / 2));
}
}
}
return 37 * pre + result;
}
/**
* Computes a hash code for a {@link PaintList}. In the latest version
* of JCommon, the {@link PaintList} class should implement the hashCode()
* method correctly, but we compute it here anyway so that we can work with
* older versions of JCommon (back to 1.0.0).
*
* @param pre the seed value.
* @param list the list (<code>null</code> permitted).
*
* @return The hash code.
*
* @since 1.0.9
*/
public static int hashCode(int pre, PaintList list) {
if (list == null) {
return pre;
}
int result = 127;
int size = list.size();
result = HashUtilities.hashCode(result, size);
// for efficiency, we just use the first, last and middle items to
// compute a hashCode...
if (size > 0) {
result = HashUtilities.hashCode(result, list.getPaint(0));
if (size > 1) {
result = HashUtilities.hashCode(result,
list.getPaint(size - 1));
if (size > 2) {
result = HashUtilities.hashCode(result,
list.getPaint(size / 2));
}
}
}
return 37 * pre + result;
}
/**
* Computes a hash code for a {@link StrokeList}. In the latest version
* of JCommon, the {@link StrokeList} class should implement the hashCode()
* method correctly, but we compute it here anyway so that we can work with
* older versions of JCommon (back to 1.0.0).
*
* @param pre the seed value.
* @param list the list (<code>null</code> permitted).
*
* @return The hash code.
*
* @since 1.0.9
*/
public static int hashCode(int pre, StrokeList list) {
if (list == null) {
return pre;
}
int result = 127;
int size = list.size();
result = HashUtilities.hashCode(result, size);
// for efficiency, we just use the first, last and middle items to
// compute a hashCode...
if (size > 0) {
result = HashUtilities.hashCode(result, list.getStroke(0));
if (size > 1) {
result = HashUtilities.hashCode(result,
list.getStroke(size - 1));
if (size > 2) {
result = HashUtilities.hashCode(result,
list.getStroke(size / 2));
}
}
}
return 37 * pre + result;
}
}
| 10,840 | 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/package-info.java | /**
* Core classes, including {@link org.jfree.chart.JFreeChart} and
* {@link org.jfree.chart.ChartPanel}.
*/
package org.jfree.chart;
| 138 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
LegendRenderingOrder.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/LegendRenderingOrder.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.]
*
* -------------------------
* LegendRenderingOrder.java
* -------------------------
* (C) Copyright 2004-2008, by Object Refinery Limited and Contributors.
*
* Original Author: Angel;
* Contributor(s): -;
*
* Changes
* -------
* 26-Mar-2004 : Version 1 (DG);
*
*/
package org.jfree.chart;
/**
* Represents the order for rendering legend items.
*/
public enum LegendRenderingOrder {
/** In order. */
STANDARD("LegendRenderingOrder.STANDARD"),
/** In reverse order. */
REVERSE("LegendRenderingOrder.REVERSE");
/** The name. */
private String name;
/**
* Private constructor.
*
* @param name the name.
*/
private LegendRenderingOrder(String name) {
this.name = name;
}
/**
* Returns a string representing the object.
*
* @return The string.
*/
@Override
public String toString() {
return this.name;
}
}
| 2,157 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
LegendItemSource.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/LegendItemSource.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.]
*
* ---------------------
* LegendItemSource.java
* ---------------------
* (C) Copyright 2005-2014, by Object Refinery Limited and Contributors.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 23-Feb-2005 : Version 1 (DG);
* 10-Mar-2013 : Removed LegendItemCollection class (DG);
*
*/
package org.jfree.chart;
import java.util.List;
/**
* A source of legend items. A {@link org.jfree.chart.title.LegendTitle} will
* maintain a list of sources (often just one) from which it obtains legend
* items.
*/
public interface LegendItemSource {
/**
* Returns a (possibly empty) collection of legend items.
*
* @return The legend item collection (never <code>null</code>).
*/
public List<LegendItem> getLegendItems();
}
| 2,052 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
ChartMouseListener.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/ChartMouseListener.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.]
*
* -----------------------
* ChartMouseListener.java
* -----------------------
* (C) Copyright 2002-2008, by Object Refinery Limited and Contributors.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): Alex Weber;
*
* Changes
* -------
* 27-May-2002 : Version 1, incorporating code and ideas by Alex Weber (DG);
* 13-Jun-2002 : Added Javadocs (DG);
* 26-Sep-2002 : Fixed errors reported by Checkstyle (DG);
* 23-Nov-2005 : Now extends EventListener (DG);
* ------------- JFREECHART 1.0.x ---------------------------------------------
* 24-May-2007 : Updated API docs (DG);
*
*/
package org.jfree.chart;
import java.util.EventListener;
/**
* The interface that must be implemented by classes that wish to receive
* {@link ChartMouseEvent} notifications from a {@link ChartPanel}.
*
* @see ChartPanel#addChartMouseListener(ChartMouseListener)
*/
public interface ChartMouseListener extends EventListener {
/**
* Callback method for receiving notification of a mouse click on a chart.
*
* @param event information about the event.
*/
void chartMouseClicked(ChartMouseEvent event);
/**
* Callback method for receiving notification of a mouse movement on a
* chart.
*
* @param event information about the event.
*/
void chartMouseMoved(ChartMouseEvent event);
}
| 2,608 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
Effect3D.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/Effect3D.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.]
*
* -------------
* Effect3D.java
* -------------
* (C) Copyright 2002-2008, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 05-Nov-2002 : Version 1 (DG);
* 14-Nov-2002 : Modified to have independent x and y offsets (DG);
*
*/
package org.jfree.chart;
/**
* An interface that should be implemented by renderers that use a 3D effect.
* This allows the axes to mirror the same effect by querying the renderer.
*/
public interface Effect3D {
/**
* Returns the x-offset (in Java2D units) for the 3D effect.
*
* @return The offset.
*/
public double getXOffset();
/**
* Returns the y-offset (in Java2D units) for the 3D effect.
*
* @return The offset.
*/
public double getYOffset();
}
| 2,072 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
PolarChartPanel.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/PolarChartPanel.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.]
*
* --------------------
* PolarChartPanel.java
* --------------------
* (C) Copyright 2004-2008, by Solution Engineering, Inc. and Contributors.
*
* Original Author: Daniel Bridenbecker, Solution Engineering, Inc.;
* Contributor(s): David Gilbert (for Object Refinery Limited);
* Martin Hoeller;
*
* Changes
* -------
* 19-Jan-2004 : Version 1, contributed by DB with minor changes by DG (DG);
* ------------- JFREECHART 1.0.x ---------------------------------------------
* 02-Feb-2007 : Removed author tags all over JFreeChart sources (DG);
* 10-Oct-2011 : bug #3165708: localization (MH);
*
*/
package org.jfree.chart;
import java.awt.Component;
import java.awt.event.ActionEvent;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import org.jfree.chart.plot.Plot;
import org.jfree.chart.plot.PolarPlot;
/**
* <code>PolarChartPanel</code> is the top level object for using the
* {@link PolarPlot}. Since this class has a <code>JPanel</code> in the
* inheritance hierarchy, one uses this class to integrate the Polar plot into
* their application.
* <p>
* The main modification to <code>ChartPanel</code> is the popup menu. It
* removes <code>ChartPanel</code>'s versions of:
* <ul>
* <li><code>Zoom In</code></li>
* <li><code>Zoom Out</code></li>
* <li><code>Auto Range</code></li>
* </ul>
* and replaces them with versions more appropriate for {@link PolarPlot}.
*/
public class PolarChartPanel extends ChartPanel {
// -----------------
// --- Constants ---
// -----------------
/** Zoom in command string. */
private static final String POLAR_ZOOM_IN_ACTION_COMMAND = "Polar Zoom In";
/** Zoom out command string. */
private static final String POLAR_ZOOM_OUT_ACTION_COMMAND
= "Polar Zoom Out";
/** Auto range command string. */
private static final String POLAR_AUTO_RANGE_ACTION_COMMAND
= "Polar Auto Range";
// ------------------------
// --- Member Variables ---
// ------------------------
// --------------------
// --- Constructors ---
// --------------------
/**
* Constructs a JFreeChart panel.
*
* @param chart the chart.
*/
public PolarChartPanel(JFreeChart chart) {
this(chart, true);
}
/**
* Creates a new panel.
*
* @param chart the chart.
* @param useBuffer buffered?
*/
public PolarChartPanel(JFreeChart chart, boolean useBuffer) {
super(chart, useBuffer);
checkChart(chart);
setMinimumDrawWidth(200);
setMinimumDrawHeight(200);
setMaximumDrawWidth(2000);
setMaximumDrawHeight(2000);
}
// --------------------------
// --- ChartPanel Methods ---
// --------------------------
/**
* Sets the chart that is displayed in the panel.
*
* @param chart The chart.
*/
@Override
public void setChart(JFreeChart chart) {
checkChart(chart);
super.setChart(chart);
}
/**
* Creates a popup menu for the panel.
*
* @param properties include a menu item for the chart property editor.
* @param save include a menu item for saving the chart.
* @param print include a menu item for printing the chart.
* @param zoom include menu items for zooming.
*
* @return The popup menu.
*/
@Override
protected JPopupMenu createPopupMenu(boolean properties,
boolean save,
boolean print,
boolean zoom) {
JPopupMenu result = super.createPopupMenu(properties, save, print, zoom);
int zoomInIndex = getPopupMenuItem(result,
localizationResources.getString("Zoom_In"));
int zoomOutIndex = getPopupMenuItem(result,
localizationResources.getString("Zoom_Out"));
int autoIndex = getPopupMenuItem(result,
localizationResources.getString("Auto_Range"));
if (zoom) {
JMenuItem zoomIn = new JMenuItem(
localizationResources.getString("Zoom_In"));
zoomIn.setActionCommand(POLAR_ZOOM_IN_ACTION_COMMAND);
zoomIn.addActionListener(this);
JMenuItem zoomOut = new JMenuItem(
localizationResources.getString("Zoom_Out"));
zoomOut.setActionCommand(POLAR_ZOOM_OUT_ACTION_COMMAND);
zoomOut.addActionListener(this);
JMenuItem auto = new JMenuItem(
localizationResources.getString("Auto_Range"));
auto.setActionCommand(POLAR_AUTO_RANGE_ACTION_COMMAND);
auto.addActionListener(this);
if (zoomInIndex != -1) {
result.remove(zoomInIndex);
}
else {
zoomInIndex = result.getComponentCount() - 1;
}
result.add(zoomIn, zoomInIndex);
if (zoomOutIndex != -1) {
result.remove(zoomOutIndex);
}
else {
zoomOutIndex = zoomInIndex + 1;
}
result.add(zoomOut, zoomOutIndex);
if (autoIndex != -1) {
result.remove(autoIndex);
}
else {
autoIndex = zoomOutIndex + 1;
}
result.add(auto, autoIndex);
}
return result;
}
/**
* Handles action events generated by the popup menu.
*
* @param event the event.
*/
@Override
public void actionPerformed(ActionEvent event) {
String command = event.getActionCommand();
if (command.equals(POLAR_ZOOM_IN_ACTION_COMMAND)) {
PolarPlot plot = (PolarPlot) getChart().getPlot();
plot.zoom(0.5);
}
else if (command.equals(POLAR_ZOOM_OUT_ACTION_COMMAND)) {
PolarPlot plot = (PolarPlot) getChart().getPlot();
plot.zoom(2.0);
}
else if (command.equals(POLAR_AUTO_RANGE_ACTION_COMMAND)) {
PolarPlot plot = (PolarPlot) getChart().getPlot();
plot.getAxis().setAutoRange(true);
}
else {
super.actionPerformed(event);
}
}
// ----------------------
// --- Public Methods ---
// ----------------------
// -----------------------
// --- Private Methods ---
// -----------------------
/**
* Test that the chart is using an xy plot with time as the domain axis.
*
* @param chart the chart.
*/
private void checkChart(JFreeChart chart) {
Plot plot = chart.getPlot();
if (!(plot instanceof PolarPlot)) {
throw new IllegalArgumentException("plot is not a PolarPlot");
}
}
/**
* Returns the index of an item in a popup menu.
*
* @param menu the menu.
* @param text the label.
*
* @return The item index.
*/
private int getPopupMenuItem(JPopupMenu menu, String text) {
int index = -1;
for (int i = 0; (index == -1) && (i < menu.getComponentCount()); i++) {
Component comp = menu.getComponent(i);
if (comp instanceof JMenuItem) {
JMenuItem item = (JMenuItem) comp;
if (text.equals(item.getText())) {
index = i;
}
}
}
return index;
}
}
| 8,628 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
ChartTheme.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/ChartTheme.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.]
*
* ---------------
* ChartTheme.java
* ---------------
* (C) Copyright 2008, 2012, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 14-Aug-2008 : Version 1 (DG);
*
*/
package org.jfree.chart;
/**
* A {@link ChartTheme} a class that can apply a style or 'theme' to a chart.
* It can be implemented in an arbitrary manner, with the styling applied to
* the chart via the <code>apply(JFreeChart)</code> method. We provide one
* implementation ({@link StandardChartTheme}) that just mimics the manual
* process of calling methods to set various chart parameters.
*
* @since 1.0.11
*/
public interface ChartTheme {
/**
* Applies this theme to the supplied chart.
*
* @param chart the chart (<code>null</code> not permitted).
*/
public void apply(JFreeChart chart);
}
| 2,132 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
ChartTransferable.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/ChartTransferable.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.]
*
* -------------------
* ChartSelection.java
* -------------------
* (C) Copyright 2009, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 08-Apr-2009 : Version 1, with inspiration from patch 1460845 (DG);
* 05-May-2009 : Match the scaling options provided by the ChartPanel
* class (DG);
*
*/
package org.jfree.chart;
import java.awt.Graphics2D;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
/**
* A class used to represent a chart on the clipboard.
*
* @since 1.0.13
*/
public class ChartTransferable implements Transferable {
/** The data flavor. */
final DataFlavor imageFlavor = new DataFlavor(
"image/x-java-image; class=java.awt.Image", "Image");
/** The chart. */
private JFreeChart chart;
/** The width of the chart on the clipboard. */
private int width;
/** The height of the chart on the clipboard. */
private int height;
/**
* The smallest width at which the chart will be drawn (if necessary, the
* chart will then be scaled down to fit the requested width).
*
* @since 1.0.14
*/
private int minDrawWidth;
/**
* The smallest height at which the chart will be drawn (if necessary, the
* chart will then be scaled down to fit the requested height).
*
* @since 1.0.14
*/
private int minDrawHeight;
/**
* The largest width at which the chart will be drawn (if necessary, the
* chart will then be scaled up to fit the requested width).
*
* @since 1.0.14
*/
private int maxDrawWidth;
/**
* The largest height at which the chart will be drawn (if necessary, the
* chart will then be scaled up to fit the requested height).
*
* @since 1.0.14
*/
private int maxDrawHeight;
/**
* Creates a new chart selection.
*
* @param chart the chart.
* @param width the chart width.
* @param height the chart height.
*/
public ChartTransferable(JFreeChart chart, int width, int height) {
this(chart, width, height, true);
}
/**
* Creates a new chart selection.
*
* @param chart the chart.
* @param width the chart width.
* @param height the chart height.
* @param cloneData clone the dataset(s)?
*/
public ChartTransferable(JFreeChart chart, int width, int height,
boolean cloneData) {
this(chart, width, height, 0, 0, Integer.MAX_VALUE, Integer.MAX_VALUE,
true);
}
/**
* Creates a new chart selection. The minimum and maximum drawing
* dimensions are used to match the scaling behaviour in the
* {@link ChartPanel} class.
*
* @param chart the chart.
* @param width the chart width.
* @param height the chart height.
* @param minDrawW the minimum drawing width.
* @param minDrawH the minimum drawing height.
* @param maxDrawW the maximum drawing width.
* @param maxDrawH the maximum drawing height.
* @param cloneData clone the dataset(s)?
*
* @since 1.0.14
*/
public ChartTransferable(JFreeChart chart, int width, int height,
int minDrawW, int minDrawH, int maxDrawW, int maxDrawH,
boolean cloneData) {
// we clone the chart because presumably there can be some delay
// between putting this instance on the system clipboard and
// actually having the getTransferData() method called...
try {
this.chart = (JFreeChart) chart.clone();
}
catch (CloneNotSupportedException e) {
this.chart = chart;
}
// FIXME: we've cloned the chart, but the dataset(s) aren't cloned
// and we should do that
this.width = width;
this.height = height;
this.minDrawWidth = minDrawW;
this.minDrawHeight = minDrawH;
this.maxDrawWidth = maxDrawW;
this.maxDrawHeight = maxDrawH;
}
/**
* Returns the data flavors supported.
*
* @return The data flavors supported.
*/
@Override
public DataFlavor[] getTransferDataFlavors() {
return new DataFlavor[] {this.imageFlavor};
}
/**
* Returns <code>true</code> if the specified flavor is supported.
*
* @param flavor the flavor.
*
* @return A boolean.
*/
@Override
public boolean isDataFlavorSupported(DataFlavor flavor) {
return this.imageFlavor.equals(flavor);
}
/**
* Returns the content for the requested flavor, if it is supported.
*
* @param flavor the requested flavor.
*
* @return The content.
*
* @throws java.awt.datatransfer.UnsupportedFlavorException
* @throws java.io.IOException
*/
@Override
public Object getTransferData(DataFlavor flavor)
throws UnsupportedFlavorException, IOException {
if (this.imageFlavor.equals(flavor)) {
return createBufferedImage(this.chart, this.width, this.height,
this.minDrawWidth, this.minDrawHeight, this.maxDrawWidth,
this.maxDrawHeight);
}
else {
throw new UnsupportedFlavorException(flavor);
}
}
/**
* A utility method that creates an image of a chart, with scaling.
*
* @param chart the chart.
* @param w the image width.
* @param h the image height.
* @param minDrawW the minimum width for chart drawing.
* @param minDrawH the minimum height for chart drawing.
* @param maxDrawW the maximum width for chart drawing.
* @param maxDrawH the maximum height for chart drawing.
*
* @return A chart image.
*
* @since 1.0.14
*/
private BufferedImage createBufferedImage(JFreeChart chart, int w, int h,
int minDrawW, int minDrawH, int maxDrawW, int maxDrawH) {
BufferedImage image = new BufferedImage(w, h,
BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = image.createGraphics();
// work out if scaling is required...
boolean scale = false;
double drawWidth = w;
double drawHeight = h;
double scaleX = 1.0;
double scaleY = 1.0;
if (drawWidth < minDrawW) {
scaleX = drawWidth / minDrawW;
drawWidth = minDrawW;
scale = true;
}
else if (drawWidth > maxDrawW) {
scaleX = drawWidth / maxDrawW;
drawWidth = maxDrawW;
scale = true;
}
if (drawHeight < minDrawH) {
scaleY = drawHeight / minDrawH;
drawHeight = minDrawH;
scale = true;
}
else if (drawHeight > maxDrawH) {
scaleY = drawHeight / maxDrawH;
drawHeight = maxDrawH;
scale = true;
}
Rectangle2D chartArea = new Rectangle2D.Double(0.0, 0.0, drawWidth,
drawHeight);
if (scale) {
AffineTransform st = AffineTransform.getScaleInstance(scaleX,
scaleY);
g2.transform(st);
}
chart.draw(g2, chartArea, null, null);
g2.dispose();
return image;
}
}
| 8,785 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
StandardChartTheme.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/StandardChartTheme.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.]
*
* -----------------------
* StandardChartTheme.java
* -----------------------
* (C) Copyright 2008-2013, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 14-Aug-2008 : Version 1 (DG);
* 10-Apr-2009 : Added getter/setter for smallFont (DG);
* 10-Jul-2009 : Added shadowGenerator field (DG);
* 29-Oct-2011 : Fixed Eclipse warnings (DG);
* 16-Jun-2012 : Removed JCommon dependencies (DG);
*
*/
package org.jfree.chart;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Paint;
import java.awt.Stroke;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.List;
import org.jfree.chart.annotations.XYAnnotation;
import org.jfree.chart.annotations.XYTextAnnotation;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.PeriodAxis;
import org.jfree.chart.axis.PeriodAxisLabelInfo;
import org.jfree.chart.axis.SubCategoryAxis;
import org.jfree.chart.axis.SymbolAxis;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.block.Block;
import org.jfree.chart.block.BlockContainer;
import org.jfree.chart.block.LabelBlock;
import org.jfree.chart.ui.RectangleInsets;
import org.jfree.chart.util.PaintUtilities;
import org.jfree.chart.util.PublicCloneable;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.CombinedDomainCategoryPlot;
import org.jfree.chart.plot.CombinedDomainXYPlot;
import org.jfree.chart.plot.CombinedRangeCategoryPlot;
import org.jfree.chart.plot.CombinedRangeXYPlot;
import org.jfree.chart.plot.DefaultDrawingSupplier;
import org.jfree.chart.plot.DrawingSupplier;
import org.jfree.chart.plot.FastScatterPlot;
import org.jfree.chart.plot.MeterPlot;
import org.jfree.chart.plot.MultiplePiePlot;
import org.jfree.chart.plot.PieLabelLinkStyle;
import org.jfree.chart.plot.PiePlot;
import org.jfree.chart.plot.Plot;
import org.jfree.chart.plot.PolarPlot;
import org.jfree.chart.plot.SpiderWebPlot;
import org.jfree.chart.plot.ThermometerPlot;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.AbstractRenderer;
import org.jfree.chart.renderer.category.BarPainter;
import org.jfree.chart.renderer.category.BarRenderer;
import org.jfree.chart.renderer.category.BarRenderer3D;
import org.jfree.chart.renderer.category.CategoryItemRenderer;
import org.jfree.chart.renderer.category.GradientBarPainter;
import org.jfree.chart.renderer.category.LineRenderer3D;
import org.jfree.chart.renderer.category.MinMaxCategoryRenderer;
import org.jfree.chart.renderer.category.StatisticalBarRenderer;
import org.jfree.chart.renderer.xy.GradientXYBarPainter;
import org.jfree.chart.renderer.xy.XYBarPainter;
import org.jfree.chart.renderer.xy.XYBarRenderer;
import org.jfree.chart.renderer.xy.XYItemRenderer;
import org.jfree.chart.title.CompositeTitle;
import org.jfree.chart.title.LegendTitle;
import org.jfree.chart.title.PaintScaleLegend;
import org.jfree.chart.title.TextTitle;
import org.jfree.chart.title.Title;
import org.jfree.chart.util.DefaultShadowGenerator;
import org.jfree.chart.util.ParamChecks;
import org.jfree.chart.util.SerialUtilities;
import org.jfree.chart.util.ShadowGenerator;
/**
* A default implementation of the {@link ChartTheme} interface. This
* implementation just collects a whole bunch of chart attributes and mimics
* the manual process of applying each attribute to the right sub-object
* within the JFreeChart instance. It's not elegant code, but it works.
*
* @since 1.0.11
*/
public class StandardChartTheme implements ChartTheme, Cloneable,
PublicCloneable, Serializable {
private static final long serialVersionUID = 6387476296773755770L;
/** The name of this theme. */
private String name;
/**
* The largest font size. Use for the main chart title.
*/
private Font extraLargeFont;
/**
* A large font. Used for subtitles.
*/
private Font largeFont;
/**
* The regular font size. Used for axis tick labels, legend items etc.
*/
private Font regularFont;
/**
* The small font size.
*/
private Font smallFont;
/** The paint used to display the main chart title. */
private transient Paint titlePaint;
/** The paint used to display subtitles. */
private transient Paint subtitlePaint;
/** The background paint for the chart. */
private transient Paint chartBackgroundPaint;
/** The legend background paint. */
private transient Paint legendBackgroundPaint;
/** The legend item paint. */
private transient Paint legendItemPaint;
/** The drawing supplier. */
private DrawingSupplier drawingSupplier;
/** The background paint for the plot. */
private transient Paint plotBackgroundPaint;
/** The plot outline paint. */
private transient Paint plotOutlinePaint;
/** The label link style for pie charts. */
private PieLabelLinkStyle labelLinkStyle;
/** The label link paint for pie charts. */
private transient Paint labelLinkPaint;
/** The domain grid line paint. */
private transient Paint domainGridlinePaint;
/** The range grid line paint. */
private transient Paint rangeGridlinePaint;
/**
* The baseline paint (used for domain and range zero baselines)
*
* @since 1.0.13
*/
private transient Paint baselinePaint;
/** The crosshair paint. */
private transient Paint crosshairPaint;
/** The axis offsets. */
private RectangleInsets axisOffset;
/** The axis label paint. */
private transient Paint axisLabelPaint;
/** The tick label paint. */
private transient Paint tickLabelPaint;
/** The item label paint. */
private transient Paint itemLabelPaint;
/**
* A flag that controls whether or not shadows are visible (for example,
* in a bar renderer).
*/
private boolean shadowVisible;
/** The shadow paint. */
private transient Paint shadowPaint;
/** The bar painter. */
private BarPainter barPainter;
/** The XY bar painter. */
private XYBarPainter xyBarPainter;
/** The thermometer paint. */
private transient Paint thermometerPaint;
/**
* The paint used to fill the interior of the 'walls' in the background
* of a plot with a 3D effect. Applied to BarRenderer3D.
*/
private transient Paint wallPaint;
/** The error indicator paint for the {@link StatisticalBarRenderer}. */
private transient Paint errorIndicatorPaint;
/** The grid band paint for a {@link SymbolAxis}. */
private transient Paint gridBandPaint = SymbolAxis.DEFAULT_GRID_BAND_PAINT;
/** The grid band alternate paint for a {@link SymbolAxis}. */
private transient Paint gridBandAlternatePaint
= SymbolAxis.DEFAULT_GRID_BAND_ALTERNATE_PAINT;
/**
* The shadow generator (can be null).
*
* @since 1.0.14
*/
private ShadowGenerator shadowGenerator;
/**
* Creates and returns the default 'JFree' chart theme.
*
* @return A chart theme.
*/
public static ChartTheme createJFreeTheme() {
return new StandardChartTheme("JFree");
}
/**
* Creates and returns a theme called "Darkness". In this theme, the
* charts have a black background.
*
* @return The "Darkness" theme.
*/
public static ChartTheme createDarknessTheme() {
StandardChartTheme theme = new StandardChartTheme("Darkness");
theme.titlePaint = Color.WHITE;
theme.subtitlePaint = Color.WHITE;
theme.legendBackgroundPaint = Color.BLACK;
theme.legendItemPaint = Color.WHITE;
theme.chartBackgroundPaint = Color.BLACK;
theme.plotBackgroundPaint = Color.BLACK;
theme.plotOutlinePaint = Color.YELLOW;
theme.baselinePaint = Color.WHITE;
theme.crosshairPaint = Color.RED;
theme.labelLinkPaint = Color.LIGHT_GRAY;
theme.tickLabelPaint = Color.WHITE;
theme.axisLabelPaint = Color.WHITE;
theme.shadowPaint = Color.DARK_GRAY;
theme.itemLabelPaint = Color.WHITE;
theme.drawingSupplier = new DefaultDrawingSupplier(
new Paint[] {Color.decode("0xFFFF00"),
Color.decode("0x0036CC"), Color.decode("0xFF0000"),
Color.decode("0xFFFF7F"), Color.decode("0x6681CC"),
Color.decode("0xFF7F7F"), Color.decode("0xFFFFBF"),
Color.decode("0x99A6CC"), Color.decode("0xFFBFBF"),
Color.decode("0xA9A938"), Color.decode("0x2D4587")},
new Paint[] {Color.decode("0xFFFF00"),
Color.decode("0x0036CC")},
new Stroke[] {new BasicStroke(2.0f)},
new Stroke[] {new BasicStroke(0.5f)},
DefaultDrawingSupplier.DEFAULT_SHAPE_SEQUENCE);
theme.wallPaint = Color.DARK_GRAY;
theme.errorIndicatorPaint = Color.LIGHT_GRAY;
theme.gridBandPaint = new Color(255, 255, 255, 20);
theme.gridBandAlternatePaint = new Color(255, 255, 255, 40);
theme.shadowGenerator = null;
return theme;
}
/**
* Creates and returns a {@link ChartTheme} that doesn't apply any changes
* to the JFreeChart defaults. This produces the "legacy" look for
* JFreeChart.
*
* @return A legacy theme.
*/
public static ChartTheme createLegacyTheme() {
StandardChartTheme theme = new StandardChartTheme("Legacy") {
@Override
public void apply(JFreeChart chart) {
// do nothing at all
}
};
return theme;
}
/**
* Creates a new default instance.
*
* @param name the name of the theme (<code>null</code> not permitted).
*/
public StandardChartTheme(String name) {
this(name, false);
}
/**
* Creates a new default instance.
*
* @param name the name of the theme (<code>null</code> not permitted).
* @param shadow a flag that controls whether a shadow generator is
* included.
*
* @since 1.0.14
*/
public StandardChartTheme(String name, boolean shadow) {
ParamChecks.nullNotPermitted(name, "name");
this.name = name;
this.extraLargeFont = new Font("Tahoma", Font.BOLD, 20);
this.largeFont = new Font("Tahoma", Font.BOLD, 14);
this.regularFont = new Font("Tahoma", Font.PLAIN, 12);
this.smallFont = new Font("Tahoma", Font.PLAIN, 10);
this.titlePaint = Color.BLACK;
this.subtitlePaint = Color.BLACK;
this.legendBackgroundPaint = Color.WHITE;
this.legendItemPaint = Color.DARK_GRAY;
this.chartBackgroundPaint = Color.WHITE;
this.drawingSupplier = new DefaultDrawingSupplier();
this.plotBackgroundPaint = Color.LIGHT_GRAY;
this.plotOutlinePaint = Color.BLACK;
this.labelLinkPaint = Color.BLACK;
this.labelLinkStyle = PieLabelLinkStyle.CUBIC_CURVE;
this.axisOffset = new RectangleInsets(4, 4, 4, 4);
this.domainGridlinePaint = Color.WHITE;
this.rangeGridlinePaint = Color.WHITE;
this.baselinePaint = Color.BLACK;
this.crosshairPaint = Color.BLUE;
this.axisLabelPaint = Color.DARK_GRAY;
this.tickLabelPaint = Color.DARK_GRAY;
this.barPainter = new GradientBarPainter();
this.xyBarPainter = new GradientXYBarPainter();
this.shadowVisible = false;
this.shadowPaint = Color.GRAY;
this.itemLabelPaint = Color.BLACK;
this.thermometerPaint = Color.WHITE;
this.wallPaint = BarRenderer3D.DEFAULT_WALL_PAINT;
this.errorIndicatorPaint = Color.BLACK;
this.shadowGenerator = shadow ? new DefaultShadowGenerator() : null;
}
/**
* Returns the largest font for this theme.
*
* @return The largest font for this theme.
*
* @see #setExtraLargeFont(Font)
*/
public Font getExtraLargeFont() {
return this.extraLargeFont;
}
/**
* Sets the largest font for this theme.
*
* @param font the font (<code>null</code> not permitted).
*
* @see #getExtraLargeFont()
*/
public void setExtraLargeFont(Font font) {
ParamChecks.nullNotPermitted(font, "font");
this.extraLargeFont = font;
}
/**
* Returns the large font for this theme.
*
* @return The large font (never <code>null</code>).
*
* @see #setLargeFont(Font)
*/
public Font getLargeFont() {
return this.largeFont;
}
/**
* Sets the large font for this theme.
*
* @param font the font (<code>null</code> not permitted).
*
* @see #getLargeFont()
*/
public void setLargeFont(Font font) {
ParamChecks.nullNotPermitted(font, "font");
this.largeFont = font;
}
/**
* Returns the regular font.
*
* @return The regular font (never <code>null</code>).
*
* @see #setRegularFont(Font)
*/
public Font getRegularFont() {
return this.regularFont;
}
/**
* Sets the regular font for this theme.
*
* @param font the font (<code>null</code> not permitted).
*
* @see #getRegularFont()
*/
public void setRegularFont(Font font) {
ParamChecks.nullNotPermitted(font, "font");
this.regularFont = font;
}
/**
* Returns the small font.
*
* @return The small font (never <code>null</code>).
*
* @see #setSmallFont(Font)
*
* @since 1.0.13
*/
public Font getSmallFont() {
return this.smallFont;
}
/**
* Sets the small font for this theme.
*
* @param font the font (<code>null</code> not permitted).
*
* @see #getSmallFont()
*
* @since 1.0.13
*/
public void setSmallFont(Font font) {
if (font == null) {
throw new IllegalArgumentException("Null 'font' argument.");
}
this.smallFont = font;
}
/**
* Returns the title paint.
*
* @return The title paint (never <code>null</code>).
*
* @see #setTitlePaint(Paint)
*/
public Paint getTitlePaint() {
return this.titlePaint;
}
/**
* Sets the title paint.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getTitlePaint()
*/
public void setTitlePaint(Paint paint) {
ParamChecks.nullNotPermitted(paint, "paint");
this.titlePaint = paint;
}
/**
* Returns the subtitle paint.
*
* @return The subtitle paint (never <code>null</code>).
*
* @see #setSubtitlePaint(Paint)
*/
public Paint getSubtitlePaint() {
return this.subtitlePaint;
}
/**
* Sets the subtitle paint.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getSubtitlePaint()
*/
public void setSubtitlePaint(Paint paint) {
ParamChecks.nullNotPermitted(paint, "paint");
this.subtitlePaint = paint;
}
/**
* Returns the chart background paint.
*
* @return The chart background paint (never <code>null</code>).
*
* @see #setChartBackgroundPaint(Paint)
*/
public Paint getChartBackgroundPaint() {
return this.chartBackgroundPaint;
}
/**
* Sets the chart background paint.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getChartBackgroundPaint()
*/
public void setChartBackgroundPaint(Paint paint) {
ParamChecks.nullNotPermitted(paint, "paint");
this.chartBackgroundPaint = paint;
}
/**
* Returns the legend background paint.
*
* @return The legend background paint (never <code>null</code>).
*
* @see #setLegendBackgroundPaint(Paint)
*/
public Paint getLegendBackgroundPaint() {
return this.legendBackgroundPaint;
}
/**
* Sets the legend background paint.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getLegendBackgroundPaint()
*/
public void setLegendBackgroundPaint(Paint paint) {
if (paint == null) {
throw new IllegalArgumentException("Null 'paint' argument.");
}
this.legendBackgroundPaint = paint;
}
/**
* Returns the legend item paint.
*
* @return The legend item paint (never <code>null</code>).
*
* @see #setLegendItemPaint(Paint)
*/
public Paint getLegendItemPaint() {
return this.legendItemPaint;
}
/**
* Sets the legend item paint.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getLegendItemPaint()
*/
public void setLegendItemPaint(Paint paint) {
ParamChecks.nullNotPermitted(paint, "paint");
this.legendItemPaint = paint;
}
/**
* Returns the plot background paint.
*
* @return The plot background paint (never <code>null</code>).
*
* @see #setPlotBackgroundPaint(Paint)
*/
public Paint getPlotBackgroundPaint() {
return this.plotBackgroundPaint;
}
/**
* Sets the plot background paint.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getPlotBackgroundPaint()
*/
public void setPlotBackgroundPaint(Paint paint) {
ParamChecks.nullNotPermitted(paint, "paint");
this.plotBackgroundPaint = paint;
}
/**
* Returns the plot outline paint.
*
* @return The plot outline paint (never <code>null</code>).
*
* @see #setPlotOutlinePaint(Paint)
*/
public Paint getPlotOutlinePaint() {
return this.plotOutlinePaint;
}
/**
* Sets the plot outline paint.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getPlotOutlinePaint()
*/
public void setPlotOutlinePaint(Paint paint) {
ParamChecks.nullNotPermitted(paint, "paint");
this.plotOutlinePaint = paint;
}
/**
* Returns the label link style for pie charts.
*
* @return The label link style (never <code>null</code>).
*
* @see #setLabelLinkStyle(PieLabelLinkStyle)
*/
public PieLabelLinkStyle getLabelLinkStyle() {
return this.labelLinkStyle;
}
/**
* Sets the label link style for pie charts.
*
* @param style the style (<code>null</code> not permitted).
*
* @see #getLabelLinkStyle()
*/
public void setLabelLinkStyle(PieLabelLinkStyle style) {
if (style == null) {
throw new IllegalArgumentException("Null 'style' argument.");
}
this.labelLinkStyle = style;
}
/**
* Returns the label link paint for pie charts.
*
* @return The label link paint (never <code>null</code>).
*
* @see #setLabelLinkPaint(Paint)
*/
public Paint getLabelLinkPaint() {
return this.labelLinkPaint;
}
/**
* Sets the label link paint for pie charts.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getLabelLinkPaint()
*/
public void setLabelLinkPaint(Paint paint) {
ParamChecks.nullNotPermitted(paint, "paint");
this.labelLinkPaint = paint;
}
/**
* Returns the domain grid line paint.
*
* @return The domain grid line paint (never <code>null</code>).
*
* @see #setDomainGridlinePaint(Paint)
*/
public Paint getDomainGridlinePaint() {
return this.domainGridlinePaint;
}
/**
* Sets the domain grid line paint.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getDomainGridlinePaint()
*/
public void setDomainGridlinePaint(Paint paint) {
ParamChecks.nullNotPermitted(paint, "paint");
this.domainGridlinePaint = paint;
}
/**
* Returns the range grid line paint.
*
* @return The range grid line paint (never <code>null</code>).
*
* @see #setRangeGridlinePaint(Paint)
*/
public Paint getRangeGridlinePaint() {
return this.rangeGridlinePaint;
}
/**
* Sets the range grid line paint.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getRangeGridlinePaint()
*/
public void setRangeGridlinePaint(Paint paint) {
ParamChecks.nullNotPermitted(paint, "paint");
this.rangeGridlinePaint = paint;
}
/**
* Returns the baseline paint.
*
* @return The baseline paint.
*
* @since 1.0.13
*/
public Paint getBaselinePaint() {
return this.baselinePaint;
}
/**
* Sets the baseline paint.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @since 1.0.13
*/
public void setBaselinePaint(Paint paint) {
if (paint == null) {
throw new IllegalArgumentException("Null 'paint' argument.");
}
this.baselinePaint = paint;
}
/**
* Returns the crosshair paint.
*
* @return The crosshair paint.
*/
public Paint getCrosshairPaint() {
return this.crosshairPaint;
}
/**
* Sets the crosshair paint.
*
* @param paint the paint (<code>null</code> not permitted).
*/
public void setCrosshairPaint(Paint paint) {
ParamChecks.nullNotPermitted(paint, "paint");
this.crosshairPaint = paint;
}
/**
* Returns the axis offsets.
*
* @return The axis offsets (never <code>null</code>).
*
* @see #setAxisOffset(RectangleInsets)
*/
public RectangleInsets getAxisOffset() {
return this.axisOffset;
}
/**
* Sets the axis offset.
*
* @param offset the offset (<code>null</code> not permitted).
*
* @see #getAxisOffset()
*/
public void setAxisOffset(RectangleInsets offset) {
ParamChecks.nullNotPermitted(offset, "offset");
this.axisOffset = offset;
}
/**
* Returns the axis label paint.
*
* @return The axis label paint (never <code>null</code>).
*
* @see #setAxisLabelPaint(Paint)
*/
public Paint getAxisLabelPaint() {
return this.axisLabelPaint;
}
/**
* Sets the axis label paint.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getAxisLabelPaint()
*/
public void setAxisLabelPaint(Paint paint) {
ParamChecks.nullNotPermitted(paint, "paint");
this.axisLabelPaint = paint;
}
/**
* Returns the tick label paint.
*
* @return The tick label paint (never <code>null</code>).
*
* @see #setTickLabelPaint(Paint)
*/
public Paint getTickLabelPaint() {
return this.tickLabelPaint;
}
/**
* Sets the tick label paint.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getTickLabelPaint()
*/
public void setTickLabelPaint(Paint paint) {
if (paint == null) {
throw new IllegalArgumentException("Null 'paint' argument.");
}
this.tickLabelPaint = paint;
}
/**
* Returns the item label paint.
*
* @return The item label paint (never <code>null</code>).
*
* @see #setItemLabelPaint(Paint)
*/
public Paint getItemLabelPaint() {
return this.itemLabelPaint;
}
/**
* Sets the item label paint.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getItemLabelPaint()
*/
public void setItemLabelPaint(Paint paint) {
ParamChecks.nullNotPermitted(paint, "paint");
this.itemLabelPaint = paint;
}
/**
* Returns the shadow visibility flag.
*
* @return The shadow visibility flag.
*
* @see #setShadowVisible(boolean)
*/
public boolean isShadowVisible() {
return this.shadowVisible;
}
/**
* Sets the shadow visibility flag.
*
* @param visible the flag.
*
* @see #isShadowVisible()
*/
public void setShadowVisible(boolean visible) {
this.shadowVisible = visible;
}
/**
* Returns the shadow paint.
*
* @return The shadow paint (never <code>null</code>).
*
* @see #setShadowPaint(Paint)
*/
public Paint getShadowPaint() {
return this.shadowPaint;
}
/**
* Sets the shadow paint.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getShadowPaint()
*/
public void setShadowPaint(Paint paint) {
ParamChecks.nullNotPermitted(paint, "paint");
this.shadowPaint = paint;
}
/**
* Returns the bar painter.
*
* @return The bar painter (never <code>null</code>).
*
* @see #setBarPainter(BarPainter)
*/
public BarPainter getBarPainter() {
return this.barPainter;
}
/**
* Sets the bar painter.
*
* @param painter the painter (<code>null</code> not permitted).
*
* @see #getBarPainter()
*/
public void setBarPainter(BarPainter painter) {
ParamChecks.nullNotPermitted(painter, "painter");
this.barPainter = painter;
}
/**
* Returns the XY bar painter.
*
* @return The XY bar painter (never <code>null</code>).
*
* @see #setXYBarPainter(XYBarPainter)
*/
public XYBarPainter getXYBarPainter() {
return this.xyBarPainter;
}
/**
* Sets the XY bar painter.
*
* @param painter the painter (<code>null</code> not permitted).
*
* @see #getXYBarPainter()
*/
public void setXYBarPainter(XYBarPainter painter) {
if (painter == null) {
throw new IllegalArgumentException("Null 'painter' argument.");
}
this.xyBarPainter = painter;
}
/**
* Returns the thermometer paint.
*
* @return The thermometer paint (never <code>null</code>).
*
* @see #setThermometerPaint(Paint)
*/
public Paint getThermometerPaint() {
return this.thermometerPaint;
}
/**
* Sets the thermometer paint.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getThermometerPaint()
*/
public void setThermometerPaint(Paint paint) {
ParamChecks.nullNotPermitted(paint, "paint");
this.thermometerPaint = paint;
}
/**
* Returns the wall paint for charts with a 3D effect.
*
* @return The wall paint (never <code>null</code>).
*
* @see #setWallPaint(Paint)
*/
public Paint getWallPaint() {
return this.wallPaint;
}
/**
* Sets the wall paint for charts with a 3D effect.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getWallPaint()
*/
public void setWallPaint(Paint paint) {
ParamChecks.nullNotPermitted(paint, "paint");
this.wallPaint = paint;
}
/**
* Returns the error indicator paint.
*
* @return The error indicator paint (never <code>null</code>).
*
* @see #setErrorIndicatorPaint(Paint)
*/
public Paint getErrorIndicatorPaint() {
return this.errorIndicatorPaint;
}
/**
* Sets the error indicator paint.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getErrorIndicatorPaint()
*/
public void setErrorIndicatorPaint(Paint paint) {
ParamChecks.nullNotPermitted(paint, "paint");
this.errorIndicatorPaint = paint;
}
/**
* Returns the grid band paint.
*
* @return The grid band paint (never <code>null</code>).
*
* @see #setGridBandPaint(Paint)
*/
public Paint getGridBandPaint() {
return this.gridBandPaint;
}
/**
* Sets the grid band paint.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getGridBandPaint()
*/
public void setGridBandPaint(Paint paint) {
if (paint == null) {
throw new IllegalArgumentException("Null 'paint' argument.");
}
this.gridBandPaint = paint;
}
/**
* Returns the grid band alternate paint (used for a {@link SymbolAxis}).
*
* @return The paint (never <code>null</code>).
*
* @see #setGridBandAlternatePaint(Paint)
*/
public Paint getGridBandAlternatePaint() {
return this.gridBandAlternatePaint;
}
/**
* Sets the grid band alternate paint (used for a {@link SymbolAxis}).
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getGridBandAlternatePaint()
*/
public void setGridBandAlternatePaint(Paint paint) {
ParamChecks.nullNotPermitted(paint, "paint");
this.gridBandAlternatePaint = paint;
}
/**
* Returns the name of this theme.
*
* @return The name of this theme.
*/
public String getName() {
return this.name;
}
/**
* Returns a clone of the drawing supplier for this theme.
*
* @return A clone of the drawing supplier.
*/
public DrawingSupplier getDrawingSupplier() {
DrawingSupplier result = null;
if (this.drawingSupplier instanceof PublicCloneable) {
PublicCloneable pc = (PublicCloneable) this.drawingSupplier;
try {
result = (DrawingSupplier) pc.clone();
}
catch (CloneNotSupportedException e) {
throw new RuntimeException("Could not clone drawing supplier", e);
}
}
return result;
}
/**
* Sets the drawing supplier for this theme.
*
* @param supplier the supplier (<code>null</code> not permitted).
*
* @see #getDrawingSupplier()
*/
public void setDrawingSupplier(DrawingSupplier supplier) {
ParamChecks.nullNotPermitted(supplier, "supplier");
this.drawingSupplier = supplier;
}
/**
* Applies this theme to the supplied chart.
*
* @param chart the chart (<code>null</code> not permitted).
*/
@Override
public void apply(JFreeChart chart) {
ParamChecks.nullNotPermitted(chart, "chart");
TextTitle title = chart.getTitle();
if (title != null) {
title.setFont(this.extraLargeFont);
title.setPaint(this.titlePaint);
}
int subtitleCount = chart.getSubtitleCount();
for (int i = 0; i < subtitleCount; i++) {
applyToTitle(chart.getSubtitle(i));
}
chart.setBackgroundPaint(this.chartBackgroundPaint);
// now process the plot if there is one
Plot plot = chart.getPlot();
if (plot != null) {
applyToPlot(plot);
}
}
/**
* Applies the attributes of this theme to the specified title.
*
* @param title the title.
*/
protected void applyToTitle(Title title) {
if (title instanceof TextTitle) {
TextTitle tt = (TextTitle) title;
tt.setFont(this.largeFont);
tt.setPaint(this.subtitlePaint);
}
else if (title instanceof LegendTitle) {
LegendTitle lt = (LegendTitle) title;
if (lt.getBackgroundPaint() != null) {
lt.setBackgroundPaint(this.legendBackgroundPaint);
}
lt.setItemFont(this.regularFont);
lt.setItemPaint(this.legendItemPaint);
if (lt.getWrapper() != null) {
applyToBlockContainer(lt.getWrapper());
}
}
else if (title instanceof PaintScaleLegend) {
PaintScaleLegend psl = (PaintScaleLegend) title;
psl.setBackgroundPaint(this.legendBackgroundPaint);
ValueAxis axis = psl.getAxis();
if (axis != null) {
applyToValueAxis(axis);
}
}
else if (title instanceof CompositeTitle) {
CompositeTitle ct = (CompositeTitle) title;
BlockContainer bc = ct.getContainer();
List<Block> blocks = bc.getBlocks();
for (Block b : blocks) {
if (b instanceof Title) {
applyToTitle((Title) b);
}
}
}
}
/**
* Applies the attributes of this theme to the specified container.
*
* @param bc a block container (<code>null</code> not permitted).
*/
protected void applyToBlockContainer(BlockContainer bc) {
for (Block b : bc.getBlocks()) {
applyToBlock(b);
}
}
/**
* Applies the attributes of this theme to the specified block.
*
* @param b the block.
*/
protected void applyToBlock(Block b) {
if (b instanceof Title) {
applyToTitle((Title) b);
}
else if (b instanceof LabelBlock) {
LabelBlock lb = (LabelBlock) b;
lb.setFont(this.regularFont);
lb.setPaint(this.legendItemPaint);
}
}
/**
* Applies the attributes of this theme to a plot.
*
* @param plot the plot (<code>null</code>).
*/
protected void applyToPlot(Plot plot) {
ParamChecks.nullNotPermitted(plot, "plot");
if (plot.getDrawingSupplier() != null) {
plot.setDrawingSupplier(getDrawingSupplier());
}
if (plot.getBackgroundPaint() != null) {
plot.setBackgroundPaint(this.plotBackgroundPaint);
}
plot.setOutlinePaint(this.plotOutlinePaint);
// now handle specific plot types (and yes, I know this is some
// really ugly code that has to be manually updated any time a new
// plot type is added - I should have written something much cooler,
// but I didn't and neither did anyone else).
if (plot instanceof PiePlot) {
applyToPiePlot((PiePlot) plot);
}
else if (plot instanceof MultiplePiePlot) {
applyToMultiplePiePlot((MultiplePiePlot) plot);
}
else if (plot instanceof CategoryPlot) {
applyToCategoryPlot((CategoryPlot) plot);
}
else if (plot instanceof XYPlot) {
applyToXYPlot((XYPlot) plot);
}
else if (plot instanceof FastScatterPlot) {
applyToFastScatterPlot((FastScatterPlot) plot);
}
else if (plot instanceof MeterPlot) {
applyToMeterPlot((MeterPlot) plot);
}
else if (plot instanceof ThermometerPlot) {
applyToThermometerPlot((ThermometerPlot) plot);
}
else if (plot instanceof SpiderWebPlot) {
applyToSpiderWebPlot((SpiderWebPlot) plot);
}
else if (plot instanceof PolarPlot) {
applyToPolarPlot((PolarPlot) plot);
}
}
/**
* Applies the attributes of this theme to a {@link PiePlot} instance.
* This method also clears any set values for the section paint, outline
* etc, so that the theme's {@link DrawingSupplier} will be used.
*
* @param plot the plot (<code>null</code> not permitted).
*/
protected void applyToPiePlot(PiePlot plot) {
plot.setLabelLinkPaint(this.labelLinkPaint);
plot.setLabelLinkStyle(this.labelLinkStyle);
plot.setLabelFont(this.regularFont);
plot.setShadowGenerator(this.shadowGenerator);
// clear the section attributes so that the theme's DrawingSupplier
// will be used
if (plot.getAutoPopulateSectionPaint()) {
plot.clearSectionPaints(false);
}
if (plot.getAutoPopulateSectionOutlinePaint()) {
plot.clearSectionOutlinePaints(false);
}
if (plot.getAutoPopulateSectionOutlineStroke()) {
plot.clearSectionOutlineStrokes(false);
}
}
/**
* Applies the attributes of this theme to a {@link MultiplePiePlot}.
*
* @param plot the plot (<code>null</code> not permitted).
*/
protected void applyToMultiplePiePlot(MultiplePiePlot plot) {
apply(plot.getPieChart());
}
/**
* Applies the attributes of this theme to a {@link CategoryPlot}.
*
* @param plot the plot (<code>null</code> not permitted).
*/
protected void applyToCategoryPlot(CategoryPlot plot) {
plot.setAxisOffset(this.axisOffset);
plot.setDomainGridlinePaint(this.domainGridlinePaint);
plot.setRangeGridlinePaint(this.rangeGridlinePaint);
plot.setRangeZeroBaselinePaint(this.baselinePaint);
plot.setShadowGenerator(this.shadowGenerator);
// process all domain axes
int domainAxisCount = plot.getDomainAxisCount();
for (int i = 0; i < domainAxisCount; i++) {
CategoryAxis axis = plot.getDomainAxis(i);
if (axis != null) {
applyToCategoryAxis(axis);
}
}
// process all range axes
int rangeAxisCount = plot.getRangeAxisCount();
for (int i = 0; i < rangeAxisCount; i++) {
ValueAxis axis = plot.getRangeAxis(i);
if (axis != null) {
applyToValueAxis(axis);
}
}
// process all renderers
int rendererCount = plot.getRendererCount();
for (int i = 0; i < rendererCount; i++) {
CategoryItemRenderer r = plot.getRenderer(i);
if (r != null) {
applyToCategoryItemRenderer(r);
}
}
if (plot instanceof CombinedDomainCategoryPlot) {
CombinedDomainCategoryPlot cp = (CombinedDomainCategoryPlot) plot;
for (CategoryPlot subplot : cp.getSubplots()) {
if (subplot != null) {
applyToPlot(subplot);
}
}
}
if (plot instanceof CombinedRangeCategoryPlot) {
CombinedRangeCategoryPlot cp = (CombinedRangeCategoryPlot) plot;
for (CategoryPlot subplot : cp.getSubplots()) {
if (subplot != null) {
applyToPlot(subplot);
}
}
}
}
/**
* Applies the attributes of this theme to a {@link XYPlot}.
*
* @param plot the plot (<code>null</code> not permitted).
*/
protected void applyToXYPlot(XYPlot plot) {
plot.setAxisOffset(this.axisOffset);
plot.setDomainZeroBaselinePaint(this.baselinePaint);
plot.setRangeZeroBaselinePaint(this.baselinePaint);
plot.setDomainGridlinePaint(this.domainGridlinePaint);
plot.setRangeGridlinePaint(this.rangeGridlinePaint);
plot.setDomainCrosshairPaint(this.crosshairPaint);
plot.setRangeCrosshairPaint(this.crosshairPaint);
plot.setShadowGenerator(this.shadowGenerator);
// process all domain axes
int domainAxisCount = plot.getDomainAxisCount();
for (int i = 0; i < domainAxisCount; i++) {
ValueAxis axis = plot.getDomainAxis(i);
if (axis != null) {
applyToValueAxis(axis);
}
}
// process all range axes
int rangeAxisCount = plot.getRangeAxisCount();
for (int i = 0; i < rangeAxisCount; i++) {
ValueAxis axis = plot.getRangeAxis(i);
if (axis != null) {
applyToValueAxis(axis);
}
}
// process all renderers
int rendererCount = plot.getRendererCount();
for (int i = 0; i < rendererCount; i++) {
XYItemRenderer r = plot.getRenderer(i);
if (r != null) {
applyToXYItemRenderer(r);
}
}
// process all annotations
for (XYAnnotation a : plot.getAnnotations()) {
applyToXYAnnotation(a);
}
if (plot instanceof CombinedDomainXYPlot) {
CombinedDomainXYPlot cp = (CombinedDomainXYPlot) plot;
for (XYPlot subplot : cp.getSubplots()) {
if (subplot != null) {
applyToPlot(subplot);
}
}
}
if (plot instanceof CombinedRangeXYPlot) {
CombinedRangeXYPlot cp = (CombinedRangeXYPlot) plot;
for (XYPlot subplot : cp.getSubplots()) {
if (subplot != null) {
applyToPlot(subplot);
}
}
}
}
/**
* Applies the attributes of this theme to a {@link FastScatterPlot}.
* @param plot
*/
protected void applyToFastScatterPlot(FastScatterPlot plot) {
plot.setDomainGridlinePaint(this.domainGridlinePaint);
plot.setRangeGridlinePaint(this.rangeGridlinePaint);
ValueAxis xAxis = plot.getDomainAxis();
if (xAxis != null) {
applyToValueAxis(xAxis);
}
ValueAxis yAxis = plot.getRangeAxis();
if (yAxis != null) {
applyToValueAxis(yAxis);
}
}
/**
* Applies the attributes of this theme to a {@link PolarPlot}. This
* method is called from the {@link #applyToPlot(Plot)} method.
*
* @param plot the plot (<code>null</code> not permitted).
*/
protected void applyToPolarPlot(PolarPlot plot) {
plot.setAngleLabelFont(this.regularFont);
plot.setAngleLabelPaint(this.tickLabelPaint);
plot.setAngleGridlinePaint(this.domainGridlinePaint);
plot.setRadiusGridlinePaint(this.rangeGridlinePaint);
ValueAxis axis = plot.getAxis();
if (axis != null) {
applyToValueAxis(axis);
}
}
/**
* Applies the attributes of this theme to a {@link SpiderWebPlot}.
*
* @param plot the plot (<code>null</code> not permitted).
*/
protected void applyToSpiderWebPlot(SpiderWebPlot plot) {
plot.setLabelFont(this.regularFont);
plot.setLabelPaint(this.axisLabelPaint);
plot.setAxisLinePaint(this.axisLabelPaint);
}
/**
* Applies the attributes of this theme to a {@link MeterPlot}.
*
* @param plot the plot (<code>null</code> not permitted).
*/
protected void applyToMeterPlot(MeterPlot plot) {
plot.setDialBackgroundPaint(this.plotBackgroundPaint);
plot.setValueFont(this.largeFont);
plot.setValuePaint(this.axisLabelPaint);
plot.setDialOutlinePaint(this.plotOutlinePaint);
plot.setNeedlePaint(this.thermometerPaint);
plot.setTickLabelFont(this.regularFont);
plot.setTickLabelPaint(this.tickLabelPaint);
}
/**
* Applies the attributes for this theme to a {@link ThermometerPlot}.
* This method is called from the {@link #applyToPlot(Plot)} method.
*
* @param plot the plot.
*/
protected void applyToThermometerPlot(ThermometerPlot plot) {
plot.setValueFont(this.largeFont);
plot.setThermometerPaint(this.thermometerPaint);
ValueAxis axis = plot.getRangeAxis();
if (axis != null) {
applyToValueAxis(axis);
}
}
/**
* Applies the attributes for this theme to a {@link CategoryAxis}.
*
* @param axis the axis (<code>null</code> not permitted).
*/
protected void applyToCategoryAxis(CategoryAxis axis) {
axis.setLabelFont(this.largeFont);
axis.setLabelPaint(this.axisLabelPaint);
axis.setTickLabelFont(this.regularFont);
axis.setTickLabelPaint(this.tickLabelPaint);
if (axis instanceof SubCategoryAxis) {
SubCategoryAxis sca = (SubCategoryAxis) axis;
sca.setSubLabelFont(this.regularFont);
sca.setSubLabelPaint(this.tickLabelPaint);
}
}
/**
* Applies the attributes for this theme to a {@link ValueAxis}.
*
* @param axis the axis (<code>null</code> not permitted).
*/
protected void applyToValueAxis(ValueAxis axis) {
axis.setLabelFont(this.largeFont);
axis.setLabelPaint(this.axisLabelPaint);
axis.setTickLabelFont(this.regularFont);
axis.setTickLabelPaint(this.tickLabelPaint);
if (axis instanceof SymbolAxis) {
applyToSymbolAxis((SymbolAxis) axis);
}
if (axis instanceof PeriodAxis) {
applyToPeriodAxis((PeriodAxis) axis);
}
}
/**
* Applies the attributes for this theme to a {@link SymbolAxis}.
*
* @param axis the axis (<code>null</code> not permitted).
*/
protected void applyToSymbolAxis(SymbolAxis axis) {
axis.setGridBandPaint(this.gridBandPaint);
axis.setGridBandAlternatePaint(this.gridBandAlternatePaint);
}
/**
* Applies the attributes for this theme to a {@link PeriodAxis}.
*
* @param axis the axis (<code>null</code> not permitted).
*/
protected void applyToPeriodAxis(PeriodAxis axis) {
PeriodAxisLabelInfo[] info = axis.getLabelInfo();
for (int i = 0; i < info.length; i++) {
PeriodAxisLabelInfo e = info[i];
PeriodAxisLabelInfo n = new PeriodAxisLabelInfo(e.getPeriodClass(),
e.getDateFormat(), e.getPadding(), this.regularFont,
this.tickLabelPaint, e.getDrawDividers(),
e.getDividerStroke(), e.getDividerPaint());
info[i] = n;
}
axis.setLabelInfo(info);
}
/**
* Applies the attributes for this theme to an {@link AbstractRenderer}.
*
* @param renderer the renderer (<code>null</code> not permitted).
*/
protected void applyToAbstractRenderer(AbstractRenderer renderer) {
if (renderer.getAutoPopulateSeriesPaint()) {
renderer.clearSeriesPaints(false);
}
if (renderer.getAutoPopulateSeriesStroke()) {
renderer.clearSeriesStrokes(false);
}
}
/**
* Applies the settings of this theme to the specified renderer.
*
* @param renderer the renderer (<code>null</code> not permitted).
*/
protected void applyToCategoryItemRenderer(CategoryItemRenderer renderer) {
ParamChecks.nullNotPermitted(renderer, "renderer");
if (renderer instanceof AbstractRenderer) {
applyToAbstractRenderer((AbstractRenderer) renderer);
}
renderer.setDefaultItemLabelFont(this.regularFont);
renderer.setDefaultItemLabelPaint(this.itemLabelPaint);
// now we handle some special cases - yes, UGLY code alert!
// BarRenderer
if (renderer instanceof BarRenderer) {
BarRenderer br = (BarRenderer) renderer;
br.setBarPainter(this.barPainter);
br.setShadowVisible(this.shadowVisible);
br.setShadowPaint(this.shadowPaint);
}
// BarRenderer3D
if (renderer instanceof BarRenderer3D) {
BarRenderer3D br3d = (BarRenderer3D) renderer;
br3d.setWallPaint(this.wallPaint);
}
// LineRenderer3D
if (renderer instanceof LineRenderer3D) {
LineRenderer3D lr3d = (LineRenderer3D) renderer;
lr3d.setWallPaint(this.wallPaint);
}
// StatisticalBarRenderer
if (renderer instanceof StatisticalBarRenderer) {
StatisticalBarRenderer sbr = (StatisticalBarRenderer) renderer;
sbr.setErrorIndicatorPaint(this.errorIndicatorPaint);
}
// MinMaxCategoryRenderer
if (renderer instanceof MinMaxCategoryRenderer) {
MinMaxCategoryRenderer mmcr = (MinMaxCategoryRenderer) renderer;
mmcr.setGroupPaint(this.errorIndicatorPaint);
}
}
/**
* Applies the settings of this theme to the specified renderer.
*
* @param renderer the renderer (<code>null</code> not permitted).
*/
protected void applyToXYItemRenderer(XYItemRenderer renderer) {
ParamChecks.nullNotPermitted(renderer, "renderer");
if (renderer instanceof AbstractRenderer) {
applyToAbstractRenderer((AbstractRenderer) renderer);
}
renderer.setDefaultItemLabelFont(this.regularFont);
renderer.setDefaultItemLabelPaint(this.itemLabelPaint);
if (renderer instanceof XYBarRenderer) {
XYBarRenderer br = (XYBarRenderer) renderer;
br.setBarPainter(this.xyBarPainter);
br.setShadowVisible(this.shadowVisible);
}
}
/**
* Applies the settings of this theme to the specified annotation.
*
* @param annotation the annotation.
*/
protected void applyToXYAnnotation(XYAnnotation annotation) {
ParamChecks.nullNotPermitted(annotation, "annotation");
if (annotation instanceof XYTextAnnotation) {
XYTextAnnotation xyta = (XYTextAnnotation) annotation;
xyta.setFont(this.smallFont);
xyta.setPaint(this.itemLabelPaint);
}
}
/**
* Tests this theme 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 StandardChartTheme)) {
return false;
}
StandardChartTheme that = (StandardChartTheme) obj;
if (!this.name.equals(that.name)) {
return false;
}
if (!this.extraLargeFont.equals(that.extraLargeFont)) {
return false;
}
if (!this.largeFont.equals(that.largeFont)) {
return false;
}
if (!this.regularFont.equals(that.regularFont)) {
return false;
}
if (!this.smallFont.equals(that.smallFont)) {
return false;
}
if (!PaintUtilities.equal(this.titlePaint, that.titlePaint)) {
return false;
}
if (!PaintUtilities.equal(this.subtitlePaint, that.subtitlePaint)) {
return false;
}
if (!PaintUtilities.equal(this.chartBackgroundPaint,
that.chartBackgroundPaint)) {
return false;
}
if (!PaintUtilities.equal(this.legendBackgroundPaint,
that.legendBackgroundPaint)) {
return false;
}
if (!PaintUtilities.equal(this.legendItemPaint, that.legendItemPaint)) {
return false;
}
if (!this.drawingSupplier.equals(that.drawingSupplier)) {
return false;
}
if (!PaintUtilities.equal(this.plotBackgroundPaint,
that.plotBackgroundPaint)) {
return false;
}
if (!PaintUtilities.equal(this.plotOutlinePaint,
that.plotOutlinePaint)) {
return false;
}
if (!this.labelLinkStyle.equals(that.labelLinkStyle)) {
return false;
}
if (!PaintUtilities.equal(this.labelLinkPaint, that.labelLinkPaint)) {
return false;
}
if (!PaintUtilities.equal(this.domainGridlinePaint,
that.domainGridlinePaint)) {
return false;
}
if (!PaintUtilities.equal(this.rangeGridlinePaint,
that.rangeGridlinePaint)) {
return false;
}
if (!PaintUtilities.equal(this.crosshairPaint, that.crosshairPaint)) {
return false;
}
if (!this.axisOffset.equals(that.axisOffset)) {
return false;
}
if (!PaintUtilities.equal(this.axisLabelPaint, that.axisLabelPaint)) {
return false;
}
if (!PaintUtilities.equal(this.tickLabelPaint, that.tickLabelPaint)) {
return false;
}
if (!PaintUtilities.equal(this.itemLabelPaint, that.itemLabelPaint)) {
return false;
}
if (this.shadowVisible != that.shadowVisible) {
return false;
}
if (!PaintUtilities.equal(this.shadowPaint, that.shadowPaint)) {
return false;
}
if (!this.barPainter.equals(that.barPainter)) {
return false;
}
if (!this.xyBarPainter.equals(that.xyBarPainter)) {
return false;
}
if (!PaintUtilities.equal(this.thermometerPaint,
that.thermometerPaint)) {
return false;
}
if (!PaintUtilities.equal(this.wallPaint, that.wallPaint)) {
return false;
}
if (!PaintUtilities.equal(this.errorIndicatorPaint,
that.errorIndicatorPaint)) {
return false;
}
if (!PaintUtilities.equal(this.gridBandPaint, that.gridBandPaint)) {
return false;
}
if (!PaintUtilities.equal(this.gridBandAlternatePaint,
that.gridBandAlternatePaint)) {
return false;
}
return true;
}
/**
* Returns a clone of this theme.
*
* @return A clone.
*
* @throws CloneNotSupportedException if the theme cannot be cloned.
*/
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
/**
* Provides serialization support.
*
* @param stream the output stream (<code>null</code> not permitted).
*
* @throws IOException if there is an I/O error.
*/
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
SerialUtilities.writePaint(this.titlePaint, stream);
SerialUtilities.writePaint(this.subtitlePaint, stream);
SerialUtilities.writePaint(this.chartBackgroundPaint, stream);
SerialUtilities.writePaint(this.legendBackgroundPaint, stream);
SerialUtilities.writePaint(this.legendItemPaint, stream);
SerialUtilities.writePaint(this.plotBackgroundPaint, stream);
SerialUtilities.writePaint(this.plotOutlinePaint, stream);
SerialUtilities.writePaint(this.labelLinkPaint, stream);
SerialUtilities.writePaint(this.baselinePaint, stream);
SerialUtilities.writePaint(this.domainGridlinePaint, stream);
SerialUtilities.writePaint(this.rangeGridlinePaint, stream);
SerialUtilities.writePaint(this.crosshairPaint, stream);
SerialUtilities.writePaint(this.axisLabelPaint, stream);
SerialUtilities.writePaint(this.tickLabelPaint, stream);
SerialUtilities.writePaint(this.itemLabelPaint, stream);
SerialUtilities.writePaint(this.shadowPaint, stream);
SerialUtilities.writePaint(this.thermometerPaint, stream);
SerialUtilities.writePaint(this.wallPaint, stream);
SerialUtilities.writePaint(this.errorIndicatorPaint, stream);
SerialUtilities.writePaint(this.gridBandPaint, stream);
SerialUtilities.writePaint(this.gridBandAlternatePaint, stream);
}
/**
* Provides serialization support.
*
* @param stream the input stream (<code>null</code> not permitted).
*
* @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.titlePaint = SerialUtilities.readPaint(stream);
this.subtitlePaint = SerialUtilities.readPaint(stream);
this.chartBackgroundPaint = SerialUtilities.readPaint(stream);
this.legendBackgroundPaint = SerialUtilities.readPaint(stream);
this.legendItemPaint = SerialUtilities.readPaint(stream);
this.plotBackgroundPaint = SerialUtilities.readPaint(stream);
this.plotOutlinePaint = SerialUtilities.readPaint(stream);
this.labelLinkPaint = SerialUtilities.readPaint(stream);
this.baselinePaint = SerialUtilities.readPaint(stream);
this.domainGridlinePaint = SerialUtilities.readPaint(stream);
this.rangeGridlinePaint = SerialUtilities.readPaint(stream);
this.crosshairPaint = SerialUtilities.readPaint(stream);
this.axisLabelPaint = SerialUtilities.readPaint(stream);
this.tickLabelPaint = SerialUtilities.readPaint(stream);
this.itemLabelPaint = SerialUtilities.readPaint(stream);
this.shadowPaint = SerialUtilities.readPaint(stream);
this.thermometerPaint = SerialUtilities.readPaint(stream);
this.wallPaint = SerialUtilities.readPaint(stream);
this.errorIndicatorPaint = SerialUtilities.readPaint(stream);
this.gridBandPaint = SerialUtilities.readPaint(stream);
this.gridBandAlternatePaint = SerialUtilities.readPaint(stream);
}
}
| 58,448 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
ChartPanel.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/ChartPanel.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.]
*
* ---------------
* ChartPanel.java
* ---------------
* (C) Copyright 2000-2013, by Object Refinery Limited and Contributors.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): Andrzej Porebski;
* Soren Caspersen;
* Jonathan Nash;
* Hans-Jurgen Greiner;
* Andreas Schneider;
* Daniel van Enckevort;
* David M O'Donnell;
* Arnaud Lelievre;
* Matthias Rose;
* Onno vd Akker;
* Sergei Ivanov;
* Ulrich Voigt - patch 2686040;
* Alessandro Borges - patch 1460845;
* Martin Hoeller;
* Michael Zinsmaier;
*
* Changes (from 28-Jun-2001)
* --------------------------
* 28-Jun-2001 : Integrated buffering code contributed by S???ren
* Caspersen (DG);
* 18-Sep-2001 : Updated header and fixed DOS encoding problem (DG);
* 22-Nov-2001 : Added scaling to improve display of charts in small sizes (DG);
* 26-Nov-2001 : Added property editing, saving and printing (DG);
* 11-Dec-2001 : Transferred saveChartAsPNG method to new ChartUtilities
* class (DG);
* 13-Dec-2001 : Added tooltips (DG);
* 16-Jan-2002 : Added an optional crosshair, based on the implementation by
* Jonathan Nash. Renamed the tooltips class (DG);
* 23-Jan-2002 : Implemented zooming based on code by Hans-Jurgen Greiner (DG);
* 05-Feb-2002 : Improved tooltips setup. Renamed method attemptSaveAs()
* --> doSaveAs() and made it public rather than private (DG);
* 28-Mar-2002 : Added a new constructor (DG);
* 09-Apr-2002 : Changed initialisation of tooltip generation, as suggested by
* Hans-Jurgen Greiner (DG);
* 27-May-2002 : New interactive zooming methods based on code by Hans-Jurgen
* Greiner. Renamed JFreeChartPanel --> ChartPanel, moved
* constants to ChartPanelConstants interface (DG);
* 31-May-2002 : Fixed a bug with interactive zooming and added a way to
* control if the zoom rectangle is filled in or drawn as an
* outline. A mouse drag gesture towards the top left now causes
* an autoRangeBoth() and is a way to undo zooms (AS);
* 11-Jun-2002 : Reinstated handleClick method call in mouseClicked() to get
* crosshairs working again (DG);
* 13-Jun-2002 : Added check for null popup menu in mouseDragged method (DG);
* 18-Jun-2002 : Added get/set methods for minimum and maximum chart
* dimensions (DG);
* 25-Jun-2002 : Removed redundant code (DG);
* 27-Aug-2002 : Added get/set methods for popup menu (DG);
* 26-Sep-2002 : Fixed errors reported by Checkstyle (DG);
* 22-Oct-2002 : Added translation methods for screen <--> Java2D, contributed
* by Daniel van Enckevort (DG);
* 05-Nov-2002 : Added a chart reference to the ChartMouseEvent class (DG);
* 22-Nov-2002 : Added test in zoom method for inverted axes, supplied by
* David M O'Donnell (DG);
* 14-Jan-2003 : Implemented ChartProgressListener interface (DG);
* 14-Feb-2003 : Removed deprecated setGenerateTooltips method (DG);
* 12-Mar-2003 : Added option to enforce filename extension (see bug id
* 643173) (DG);
* 08-Sep-2003 : Added internationalization via use of properties
* resourceBundle (RFE 690236) (AL);
* 18-Sep-2003 : Added getScaleX() and getScaleY() methods (protected) as
* requested by Irv Thomae (DG);
* 12-Nov-2003 : Added zooming support for the FastScatterPlot class (DG);
* 24-Nov-2003 : Minor Javadoc updates (DG);
* 04-Dec-2003 : Added anchor point for crosshair calculation (DG);
* 17-Jan-2004 : Added new methods to set tooltip delays to be used in this
* chart panel. Refer to patch 877565 (MR);
* 02-Feb-2004 : Fixed bug in zooming trigger and added zoomTriggerDistance
* attribute (DG);
* 08-Apr-2004 : Changed getScaleX() and getScaleY() from protected to
* public (DG);
* 15-Apr-2004 : Added zoomOutFactor and zoomInFactor (DG);
* 21-Apr-2004 : Fixed zooming bug in mouseReleased() method (DG);
* 13-Jul-2004 : Added check for null chart (DG);
* 04-Oct-2004 : Renamed ShapeUtils --> ShapeUtilities (DG);
* 11-Nov-2004 : Moved constants back in from ChartPanelConstants (DG);
* 12-Nov-2004 : Modified zooming mechanism to support zooming within
* subplots (DG);
* 26-Jan-2005 : Fixed mouse zooming for horizontal category plots (DG);
* 11-Apr-2005 : Added getFillZoomRectangle() method, renamed
* setHorizontalZoom() --> setDomainZoomable(),
* setVerticalZoom() --> setRangeZoomable(), added
* isDomainZoomable() and isRangeZoomable(), added
* getHorizontalAxisTrace() and getVerticalAxisTrace(),
* renamed autoRangeBoth() --> restoreAutoBounds(),
* autoRangeHorizontal() --> restoreAutoDomainBounds(),
* autoRangeVertical() --> restoreAutoRangeBounds() (DG);
* 12-Apr-2005 : Removed working areas, added getAnchorPoint() method,
* added protected accessors for tracelines (DG);
* 18-Apr-2005 : Made constants final (DG);
* 26-Apr-2005 : Removed LOGGER (DG);
* 01-Jun-2005 : Fixed zooming for combined plots - see bug report
* 1212039, fix thanks to Onno vd Akker (DG);
* 25-Nov-2005 : Reworked event listener mechanism (DG);
* ------------- JFREECHART 1.0.x ---------------------------------------------
* 01-Aug-2006 : Fixed minor bug in restoreAutoRangeBounds() (DG);
* 04-Sep-2006 : Renamed attemptEditChartProperties() -->
* doEditChartProperties() and made public (DG);
* 13-Sep-2006 : Don't generate ChartMouseEvents if the panel's chart is null
* (fixes bug 1556951) (DG);
* 05-Mar-2007 : Applied patch 1672561 by Sergei Ivanov, to fix zoom rectangle
* drawing for dynamic charts (DG);
* 17-Apr-2007 : Fix NullPointerExceptions in zooming for combined plots (DG);
* 24-May-2007 : When the look-and-feel changes, update the popup menu if there
* is one (DG);
* 06-Jun-2007 : Fixed coordinates for drawing buffer image (DG);
* 24-Sep-2007 : Added zoomAroundAnchor flag, and handle clearing of chart
* buffer (DG);
* 25-Oct-2007 : Added default directory attribute (DG);
* 07-Nov-2007 : Fixed (rare) bug in refreshing off-screen image (DG);
* 07-May-2008 : Fixed bug in zooming that triggered zoom for a rectangle
* outside of the data area (DG);
* 08-May-2008 : Fixed serialization bug (DG);
* 15-Aug-2008 : Increased default maxDrawWidth/Height (DG);
* 18-Sep-2008 : Modified creation of chart buffer (DG);
* 18-Dec-2008 : Use ResourceBundleWrapper - see patch 1607918 by
* Jess Thrysoee (DG);
* 13-Jan-2009 : Fixed zooming methods to trigger only one plot
* change event (DG);
* 16-Jan-2009 : Use XOR for zoom rectangle only if useBuffer is false (DG);
* 18-Mar-2009 : Added mouse wheel support (DG);
* 19-Mar-2009 : Added panning on mouse drag support - based on Ulrich
* Voigt's patch 2686040 (DG);
* 26-Mar-2009 : Changed fillZoomRectangle default to true, and only change
* cursor for CTRL-mouse-click if panning is enabled (DG);
* 01-Apr-2009 : Fixed panning, and added different mouse event mask for
* MacOSX (DG);
* 08-Apr-2009 : Added copy to clipboard support, based on patch 1460845
* by Alessandro Borges (DG);
* 09-Apr-2009 : Added overlay support (DG);
* 10-Apr-2009 : Set chartBuffer background to match ChartPanel (DG);
* 05-May-2009 : Match scaling (and insets) in doCopy() (DG);
* 01-Jun-2009 : Check for null chart in mousePressed() method (DG);
* 08-Jun-2009 : Fixed bug in setMouseWheelEnabled() (DG);
* 06-Jul-2009 : Clear off-screen buffer to fully transparent (DG);
* 10-Oct-2011 : localization fix: bug #3353913 (MH);
* 15-Jun-2012 : Removed JCommon dependencies (DG);
*
*/
package org.jfree.chart;
import org.jfree.chart.editor.ChartEditor;
import org.jfree.chart.editor.ChartEditorManager;
import org.jfree.chart.entity.ChartEntity;
import org.jfree.chart.entity.EntityCollection;
import org.jfree.chart.event.*;
import org.jfree.chart.panel.AbstractMouseHandler;
import org.jfree.chart.panel.Overlay;
import org.jfree.chart.panel.PanHandler;
import org.jfree.chart.panel.ZoomHandler;
import org.jfree.chart.panel.selectionhandler.SelectionManager;
import org.jfree.chart.plot.*;
import org.jfree.chart.util.*;
import javax.swing.*;
import javax.swing.event.EventListenerList;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.event.*;
import java.awt.geom.*;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.io.*;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;
import java.util.List;
/**
* A Swing GUI component for displaying a {@link JFreeChart} object.
* <P>
* The panel registers with the chart to receive notification of changes to any
* component of the chart. The chart is redrawn automatically whenever this
* notification is received.
*/
public class ChartPanel extends JPanel implements ChartChangeListener,
ChartProgressListener, ActionListener, MouseListener,
MouseMotionListener, OverlayChangeListener, Printable, Serializable {
/** For serialization. */
private static final long serialVersionUID = 6046366297214274674L;
/**
* Default setting for buffer usage. The default has been changed to
* <code>true</code> from version 1.0.13 onwards, because of a severe
* performance problem with drawing the zoom rectangle using XOR (which
* now happens only when the buffer is NOT used).
*/
public static final boolean DEFAULT_BUFFER_USED = true;
/** The default panel width. */
public static final int DEFAULT_WIDTH = 680;
/** The default panel height. */
public static final int DEFAULT_HEIGHT = 420;
/** The default limit below which chart scaling kicks in. */
public static final int DEFAULT_MINIMUM_DRAW_WIDTH = 300;
/** The default limit below which chart scaling kicks in. */
public static final int DEFAULT_MINIMUM_DRAW_HEIGHT = 200;
/** The default limit above which chart scaling kicks in. */
public static final int DEFAULT_MAXIMUM_DRAW_WIDTH = 1024;
/** The default limit above which chart scaling kicks in. */
public static final int DEFAULT_MAXIMUM_DRAW_HEIGHT = 768;
/** The minimum size required to perform a zoom on a rectangle */
public static final int DEFAULT_ZOOM_TRIGGER_DISTANCE = 10;
/** Properties action command. */
public static final String PROPERTIES_COMMAND = "PROPERTIES";
/**
* Copy action command.
*
* @since 1.0.13
*/
public static final String COPY_COMMAND = "COPY";
/** Save action command. */
public static final String SAVE_COMMAND = "SAVE";
/** Action command to save as PNG. */
private static final String SAVE_AS_PNG_COMMAND = "SAVE_AS_PNG";
/** Action command to save as SVG. */
private static final String SAVE_AS_SVG_COMMAND = "SAVE_AS_SVG";
/** Action command to save as PDF. */
private static final String SAVE_AS_PDF_COMMAND = "SAVE_AS_PDF";
/** Print action command. */
public static final String PRINT_COMMAND = "PRINT";
/** Zoom in (both axes) action command. */
public static final String ZOOM_IN_BOTH_COMMAND = "ZOOM_IN_BOTH";
/** Zoom in (domain axis only) action command. */
public static final String ZOOM_IN_DOMAIN_COMMAND = "ZOOM_IN_DOMAIN";
/** Zoom in (range axis only) action command. */
public static final String ZOOM_IN_RANGE_COMMAND = "ZOOM_IN_RANGE";
/** Zoom out (both axes) action command. */
public static final String ZOOM_OUT_BOTH_COMMAND = "ZOOM_OUT_BOTH";
/** Zoom out (domain axis only) action command. */
public static final String ZOOM_OUT_DOMAIN_COMMAND = "ZOOM_DOMAIN_BOTH";
/** Zoom out (range axis only) action command. */
public static final String ZOOM_OUT_RANGE_COMMAND = "ZOOM_RANGE_BOTH";
/** Zoom reset (both axes) action command. */
public static final String ZOOM_RESET_BOTH_COMMAND = "ZOOM_RESET_BOTH";
/** Zoom reset (domain axis only) action command. */
public static final String ZOOM_RESET_DOMAIN_COMMAND = "ZOOM_RESET_DOMAIN";
/** Zoom reset (range axis only) action command. */
public static final String ZOOM_RESET_RANGE_COMMAND = "ZOOM_RESET_RANGE";
/** The chart that is displayed in the panel. */
private JFreeChart chart;
/** Storage for registered (chart) mouse listeners. */
private transient EventListenerList chartMouseListeners;
/** A flag that controls whether or not the off-screen buffer is used. */
private boolean useBuffer;
/** A flag that indicates that the buffer should be refreshed. */
private boolean refreshBuffer;
/** A buffer for the rendered chart. */
private transient Image chartBuffer;
/** The height of the chart buffer. */
private int chartBufferHeight;
/** The width of the chart buffer. */
private int chartBufferWidth;
/**
* The minimum width for drawing a chart (uses scaling for smaller widths).
*/
private int minimumDrawWidth;
/**
* The minimum height for drawing a chart (uses scaling for smaller
* heights).
*/
private int minimumDrawHeight;
/**
* The maximum width for drawing a chart (uses scaling for bigger
* widths).
*/
private int maximumDrawWidth;
/**
* The maximum height for drawing a chart (uses scaling for bigger
* heights).
*/
private int maximumDrawHeight;
/** The popup menu for the frame. */
private JPopupMenu popup;
/** The drawing info collected the last time the chart was drawn. */
private ChartRenderingInfo info;
/** The chart anchor point. */
private Point2D anchor;
/** The scale factor used to draw the chart. */
private double scaleX;
/** The scale factor used to draw the chart. */
private double scaleY;
/** The plot orientation. */
private PlotOrientation orientation = PlotOrientation.VERTICAL;
/** A flag that controls whether or not domain zooming is enabled. */
private boolean domainZoomable = false;
/** A flag that controls whether or not range zooming is enabled. */
private boolean rangeZoomable = false;
/**
* The zoom rectangle starting point (selected by the user with a mouse
* click). This is a point on the screen, not the chart (which may have
* been scaled up or down to fit the panel).
*/
private Point2D zoomPoint = null;
/** The zoom rectangle (selected by the user with the mouse). */
private transient Rectangle2D zoomRectangle = null;
/** Controls if the zoom rectangle is drawn as an outline or filled. */
private boolean fillZoomRectangle = true;
/** The minimum distance required to drag the mouse to trigger a zoom. */
private int zoomTriggerDistance;
/** A flag that controls whether or not horizontal tracing is enabled. */
private boolean horizontalAxisTrace = false;
/** A flag that controls whether or not vertical tracing is enabled. */
private boolean verticalAxisTrace = false;
/** A vertical trace line. */
private transient Line2D verticalTraceLine;
/** A horizontal trace line. */
private transient Line2D horizontalTraceLine;
/** Menu item for zooming in on a chart (both axes). */
private JMenuItem zoomInBothMenuItem;
/** Menu item for zooming in on a chart (domain axis). */
private JMenuItem zoomInDomainMenuItem;
/** Menu item for zooming in on a chart (range axis). */
private JMenuItem zoomInRangeMenuItem;
/** Menu item for zooming out on a chart. */
private JMenuItem zoomOutBothMenuItem;
/** Menu item for zooming out on a chart (domain axis). */
private JMenuItem zoomOutDomainMenuItem;
/** Menu item for zooming out on a chart (range axis). */
private JMenuItem zoomOutRangeMenuItem;
/** Menu item for resetting the zoom (both axes). */
private JMenuItem zoomResetBothMenuItem;
/** Menu item for resetting the zoom (domain axis only). */
private JMenuItem zoomResetDomainMenuItem;
/** Menu item for resetting the zoom (range axis only). */
private JMenuItem zoomResetRangeMenuItem;
/**
* The default directory for saving charts to file.
*
* @since 1.0.7
*/
private File defaultDirectoryForSaveAs;
/** A flag that controls whether or not file extensions are enforced. */
private boolean enforceFileExtensions;
/** A flag that indicates if original tooltip delays are changed. */
private boolean ownToolTipDelaysActive;
/** Original initial tooltip delay of ToolTipManager.sharedInstance(). */
private int originalToolTipInitialDelay;
/** Original reshow tooltip delay of ToolTipManager.sharedInstance(). */
private int originalToolTipReshowDelay;
/** Original dismiss tooltip delay of ToolTipManager.sharedInstance(). */
private int originalToolTipDismissDelay;
/** Own initial tooltip delay to be used in this chart panel. */
private int ownToolTipInitialDelay;
/** Own reshow tooltip delay to be used in this chart panel. */
private int ownToolTipReshowDelay;
/** Own dismiss tooltip delay to be used in this chart panel. */
private int ownToolTipDismissDelay;
/** The factor used to zoom in on an axis range. */
private double zoomInFactor = 0.5;
/** The factor used to zoom out on an axis range. */
private double zoomOutFactor = 2.0;
/**
* A flag that controls whether zoom operations are centred on the
* current anchor point, or the centre point of the relevant axis.
*
* @since 1.0.7
*/
private boolean zoomAroundAnchor;
/**
* The paint used to draw the zoom rectangle outline.
*
* @since 1.0.13
*/
private transient Paint zoomOutlinePaint;
/**
* The zoom fill paint (should use transparency).
*
* @since 1.0.13
*/
private transient Paint zoomFillPaint;
/** The resourceBundle for the localization. */
protected static ResourceBundle localizationResources
= ResourceBundleWrapper.getBundle(
"org.jfree.chart.LocalizationBundle");
/**
* A list of overlays for the panel.
*
* @since 1.0.13
*/
private List<Overlay> overlays;
//adding mouse handlers to support selection ...
private SelectionManager selectionManager;
/**
* The mouse handlers that are available to deal with mouse events.
*
* @since 1.0.14
*/
private List<AbstractMouseHandler> availableLiveMouseHandlers;
/**
* The current "live" mouse handler. One of the handlers from the
* 'availableMouseHandlers' list will be selected (typically in the
* mousePressed() method) to be the live handler.
*
* @since 1.0.14
*/
private AbstractMouseHandler liveMouseHandler;
/**
* A list of auxiliary mouse handlers that will be called after the live
* handler has done it's work.
*/
private List<AbstractMouseHandler> auxiliaryMouseHandlers;
/**
* The zoom handler that is installed by default.
*
* @since 1.0.14
*/
private ZoomHandler zoomHandler;
/**
* The selection shape (may be <code>null</code>).
*/
private Shape selectionShape;
/**
* The selection fill paint (may be <code>null</code>).
*/
private Paint selectionFillPaint;
/**
* The selection outline paint
*/
private Paint selectionOutlinePaint = Color.darkGray;
/**
* The selection outline stroke
*/
private transient Stroke selectionOutlineStroke = new BasicStroke(1.0f,
BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 4.0f, new float[] {
3.0f, 3.0f }, 0.0f);
private double dLeft;
private double dRight;
/**
* Constructs a panel that displays the specified chart.
*
* @param chart the chart.
*/
public ChartPanel(JFreeChart chart) {
this(
chart,
DEFAULT_WIDTH,
DEFAULT_HEIGHT,
DEFAULT_MINIMUM_DRAW_WIDTH,
DEFAULT_MINIMUM_DRAW_HEIGHT,
DEFAULT_MAXIMUM_DRAW_WIDTH,
DEFAULT_MAXIMUM_DRAW_HEIGHT,
DEFAULT_BUFFER_USED,
true, // properties
true, // save
true, // print
true, // zoom
true // tooltips
);
}
/**
* Constructs a panel containing a chart. The <code>useBuffer</code> flag
* controls whether or not an offscreen <code>BufferedImage</code> is
* maintained for the chart. If the buffer is used, more memory is
* consumed, but panel repaints will be a lot quicker in cases where the
* chart itself hasn't changed (for example, when another frame is moved
* to reveal the panel). WARNING: If you set the <code>useBuffer</code>
* flag to false, note that the mouse zooming rectangle will (in that case)
* be drawn using XOR, and there is a SEVERE performance problem with that
* on JRE6 on Windows.
*
* @param chart the chart.
* @param useBuffer a flag controlling whether or not an off-screen buffer
* is used (read the warning above before setting this
* to <code>false</code>).
*/
public ChartPanel(JFreeChart chart, boolean useBuffer) {
this(chart, DEFAULT_WIDTH, DEFAULT_HEIGHT, DEFAULT_MINIMUM_DRAW_WIDTH,
DEFAULT_MINIMUM_DRAW_HEIGHT, DEFAULT_MAXIMUM_DRAW_WIDTH,
DEFAULT_MAXIMUM_DRAW_HEIGHT, useBuffer,
true, // properties
true, // save
true, // print
true, // zoom
true // tooltips
);
}
/**
* Constructs a JFreeChart panel.
*
* @param chart the chart.
* @param properties a flag indicating whether or not the chart property
* editor should be available via the popup menu.
* @param save a flag indicating whether or not save options should be
* available via the popup menu.
* @param print a flag indicating whether or not the print option
* should be available via the popup menu.
* @param zoom a flag indicating whether or not zoom options should
* be added to the popup menu.
* @param tooltips a flag indicating whether or not tooltips should be
* enabled for the chart.
*/
public ChartPanel(JFreeChart chart,
boolean properties,
boolean save,
boolean print,
boolean zoom,
boolean tooltips) {
this(chart,
DEFAULT_WIDTH,
DEFAULT_HEIGHT,
DEFAULT_MINIMUM_DRAW_WIDTH,
DEFAULT_MINIMUM_DRAW_HEIGHT,
DEFAULT_MAXIMUM_DRAW_WIDTH,
DEFAULT_MAXIMUM_DRAW_HEIGHT,
DEFAULT_BUFFER_USED,
properties,
save,
print,
zoom,
tooltips
);
}
/**
* Constructs a JFreeChart panel.
*
* @param chart the chart.
* @param width the preferred width of the panel.
* @param height the preferred height of the panel.
* @param minimumDrawWidth the minimum drawing width.
* @param minimumDrawHeight the minimum drawing height.
* @param maximumDrawWidth the maximum drawing width.
* @param maximumDrawHeight the maximum drawing height.
* @param useBuffer a flag that indicates whether to use the off-screen
* buffer to improve performance (at the expense of
* memory).
* @param properties a flag indicating whether or not the chart property
* editor should be available via the popup menu.
* @param save a flag indicating whether or not save options should be
* available via the popup menu.
* @param print a flag indicating whether or not the print option
* should be available via the popup menu.
* @param zoom a flag indicating whether or not zoom options should be
* added to the popup menu.
* @param tooltips a flag indicating whether or not tooltips should be
* enabled for the chart.
*/
public ChartPanel(JFreeChart chart, int width, int height,
int minimumDrawWidth, int minimumDrawHeight, int maximumDrawWidth,
int maximumDrawHeight, boolean useBuffer, boolean properties,
boolean save, boolean print, boolean zoom, boolean tooltips) {
this(chart, width, height, minimumDrawWidth, minimumDrawHeight,
maximumDrawWidth, maximumDrawHeight, useBuffer, properties,
true, save, print, zoom, tooltips);
}
/**
* Constructs a JFreeChart panel.
*
* @param chart the chart.
* @param width the preferred width of the panel.
* @param height the preferred height of the panel.
* @param minimumDrawWidth the minimum drawing width.
* @param minimumDrawHeight the minimum drawing height.
* @param maximumDrawWidth the maximum drawing width.
* @param maximumDrawHeight the maximum drawing height.
* @param useBuffer a flag that indicates whether to use the off-screen
* buffer to improve performance (at the expense of
* memory).
* @param properties a flag indicating whether or not the chart property
* editor should be available via the popup menu.
* @param copy a flag indicating whether or not a copy option should be
* available via the popup menu.
* @param save a flag indicating whether or not save options should be
* available via the popup menu.
* @param print a flag indicating whether or not the print option
* should be available via the popup menu.
* @param zoom a flag indicating whether or not zoom options should be
* added to the popup menu.
* @param tooltips a flag indicating whether or not tooltips should be
* enabled for the chart.
*
* @since 1.0.13
*/
public ChartPanel(JFreeChart chart, int width, int height,
int minimumDrawWidth, int minimumDrawHeight, int maximumDrawWidth,
int maximumDrawHeight, boolean useBuffer, boolean properties,
boolean copy, boolean save, boolean print, boolean zoom,
boolean tooltips) {
setChart(chart);
this.chartMouseListeners = new EventListenerList();
this.info = new ChartRenderingInfo();
setPreferredSize(new Dimension(width, height));
this.useBuffer = useBuffer;
this.refreshBuffer = false;
this.minimumDrawWidth = minimumDrawWidth;
this.minimumDrawHeight = minimumDrawHeight;
this.maximumDrawWidth = maximumDrawWidth;
this.maximumDrawHeight = maximumDrawHeight;
this.zoomTriggerDistance = DEFAULT_ZOOM_TRIGGER_DISTANCE;
// set up popup menu...
this.popup = null;
if (properties || copy || save || print || zoom) {
this.popup = createPopupMenu(properties, copy, save, print, zoom);
}
enableEvents(AWTEvent.MOUSE_EVENT_MASK);
enableEvents(AWTEvent.MOUSE_MOTION_EVENT_MASK);
setDisplayToolTips(tooltips);
addMouseListener(this);
addMouseMotionListener(this);
this.defaultDirectoryForSaveAs = null;
this.enforceFileExtensions = true;
// initialize ChartPanel-specific tool tip delays with
// values the from ToolTipManager.sharedInstance()
ToolTipManager ttm = ToolTipManager.sharedInstance();
this.ownToolTipInitialDelay = ttm.getInitialDelay();
this.ownToolTipDismissDelay = ttm.getDismissDelay();
this.ownToolTipReshowDelay = ttm.getReshowDelay();
this.zoomAroundAnchor = false;
this.zoomOutlinePaint = Color.BLUE;
this.zoomFillPaint = new Color(0, 0, 255, 63);
this.overlays = new ArrayList<Overlay>();
this.availableLiveMouseHandlers = new ArrayList<AbstractMouseHandler>();
this.zoomHandler = new ZoomHandler();
this.availableLiveMouseHandlers.add(zoomHandler);
PanHandler panHandler = new PanHandler();
int panMask = InputEvent.CTRL_MASK;
// for MacOSX we can't use the CTRL key for mouse drags, see:
// http://developer.apple.com/qa/qa2004/qa1362.html
String osName = System.getProperty("os.name").toLowerCase();
if (osName.startsWith("mac os x")) {
panMask = InputEvent.ALT_MASK;
}
panHandler.setModifier(panMask);
this.availableLiveMouseHandlers.add(panHandler);
this.auxiliaryMouseHandlers = new ArrayList<AbstractMouseHandler>();
}
/**
* Returns the chart contained in the panel.
*
* @return The chart (possibly <code>null</code>).
*/
public JFreeChart getChart() {
return this.chart;
}
/**
* Sets the chart that is displayed in the panel.
*
* @param chart the chart (<code>null</code> permitted).
*/
public void setChart(JFreeChart chart) {
// stop listening for changes to the existing chart
if (this.chart != null) {
this.chart.removeChangeListener(this);
this.chart.removeProgressListener(this);
}
// add the new chart
this.chart = chart;
if (chart != null) {
this.chart.addChangeListener(this);
this.chart.addProgressListener(this);
Plot plot = chart.getPlot();
this.domainZoomable = false;
this.rangeZoomable = false;
if (plot instanceof Zoomable) {
Zoomable z = (Zoomable) plot;
this.domainZoomable = z.isDomainZoomable();
this.rangeZoomable = z.isRangeZoomable();
this.orientation = z.getOrientation();
}
}
else {
this.domainZoomable = false;
this.rangeZoomable = false;
}
if (this.useBuffer) {
this.refreshBuffer = true;
}
repaint();
}
/**
* Returns the minimum drawing width for charts.
* <P>
* If the width available on the panel is less than this, then the chart is
* drawn at the minimum width then scaled down to fit.
*
* @return The minimum drawing width.
*/
public int getMinimumDrawWidth() {
return this.minimumDrawWidth;
}
/**
* Sets the minimum drawing width for the chart on this panel.
* <P>
* At the time the chart is drawn on the panel, if the available width is
* less than this amount, the chart will be drawn using the minimum width
* then scaled down to fit the available space.
*
* @param width The width.
*/
public void setMinimumDrawWidth(int width) {
this.minimumDrawWidth = width;
}
/**
* Returns the maximum drawing width for charts.
* <P>
* If the width available on the panel is greater than this, then the chart
* is drawn at the maximum width then scaled up to fit.
*
* @return The maximum drawing width.
*/
public int getMaximumDrawWidth() {
return this.maximumDrawWidth;
}
/**
* Sets the maximum drawing width for the chart on this panel.
* <P>
* At the time the chart is drawn on the panel, if the available width is
* greater than this amount, the chart will be drawn using the maximum
* width then scaled up to fit the available space.
*
* @param width The width.
*/
public void setMaximumDrawWidth(int width) {
this.maximumDrawWidth = width;
}
/**
* Returns the minimum drawing height for charts.
* <P>
* If the height available on the panel is less than this, then the chart
* is drawn at the minimum height then scaled down to fit.
*
* @return The minimum drawing height.
*/
public int getMinimumDrawHeight() {
return this.minimumDrawHeight;
}
/**
* Sets the minimum drawing height for the chart on this panel.
* <P>
* At the time the chart is drawn on the panel, if the available height is
* less than this amount, the chart will be drawn using the minimum height
* then scaled down to fit the available space.
*
* @param height The height.
*/
public void setMinimumDrawHeight(int height) {
this.minimumDrawHeight = height;
}
/**
* Returns the maximum drawing height for charts.
* <P>
* If the height available on the panel is greater than this, then the
* chart is drawn at the maximum height then scaled up to fit.
*
* @return The maximum drawing height.
*/
public int getMaximumDrawHeight() {
return this.maximumDrawHeight;
}
/**
* Sets the maximum drawing height for the chart on this panel.
* <P>
* At the time the chart is drawn on the panel, if the available height is
* greater than this amount, the chart will be drawn using the maximum
* height then scaled up to fit the available space.
*
* @param height The height.
*/
public void setMaximumDrawHeight(int height) {
this.maximumDrawHeight = height;
}
/**
* Returns the X scale factor for the chart. This will be 1.0 if no
* scaling has been used.
*
* @return The scale factor.
*/
public double getScaleX() {
return this.scaleX;
}
/**
* Returns the Y scale factory for the chart. This will be 1.0 if no
* scaling has been used.
*
* @return The scale factor.
*/
public double getScaleY() {
return this.scaleY;
}
/**
* Returns the anchor point.
*
* @return The anchor point (possibly <code>null</code>).
*/
public Point2D getAnchor() {
return this.anchor;
}
/**
* Sets the anchor point. This method is provided for the use of
* subclasses, not end users.
*
* @param anchor the anchor point (<code>null</code> permitted).
*/
protected void setAnchor(Point2D anchor) {
this.anchor = anchor;
}
/**
* Returns the popup menu.
*
* @return The popup menu.
*/
public JPopupMenu getPopupMenu() {
return this.popup;
}
/**
* Sets the popup menu for the panel.
*
* @param popup the popup menu (<code>null</code> permitted).
*/
public void setPopupMenu(JPopupMenu popup) {
this.popup = popup;
}
/**
* Returns the chart rendering info from the most recent chart redraw.
*
* @return The chart rendering info.
*/
public ChartRenderingInfo getChartRenderingInfo() {
return this.info;
}
/**
* A convenience method that switches on mouse-based zooming.
*
* @param flag <code>true</code> enables zooming and rectangle fill on
* zoom.
*/
public void setMouseZoomable(boolean flag) {
setMouseZoomable(flag, true);
}
/**
* A convenience method that switches on mouse-based zooming.
*
* @param flag <code>true</code> if zooming enabled
* @param fillRectangle <code>true</code> if zoom rectangle is filled,
* false if rectangle is shown as outline only.
*/
public void setMouseZoomable(boolean flag, boolean fillRectangle) {
setDomainZoomable(flag);
setRangeZoomable(flag);
setFillZoomRectangle(fillRectangle);
}
/**
* Returns the flag that determines whether or not zooming is enabled for
* the domain axis.
*
* @return A boolean.
*/
public boolean isDomainZoomable() {
return this.domainZoomable;
}
/**
* Sets the flag that controls whether or not zooming is enable for the
* domain axis. A check is made to ensure that the current plot supports
* zooming for the domain values.
*
* @param flag <code>true</code> enables zooming if possible.
*/
public void setDomainZoomable(boolean flag) {
if (flag) {
Plot plot = this.chart.getPlot();
if (plot instanceof Zoomable) {
Zoomable z = (Zoomable) plot;
this.domainZoomable = z.isDomainZoomable();
}
}
else {
this.domainZoomable = false;
}
}
/**
* Returns the flag that determines whether or not zooming is enabled for
* the range axis.
*
* @return A boolean.
*/
public boolean isRangeZoomable() {
return this.rangeZoomable;
}
/**
* A flag that controls mouse-based zooming on the vertical axis.
*
* @param flag <code>true</code> enables zooming.
*/
public void setRangeZoomable(boolean flag) {
if (flag) {
Plot plot = this.chart.getPlot();
if (plot instanceof Zoomable) {
Zoomable z = (Zoomable) plot;
this.rangeZoomable = z.isRangeZoomable();
}
}
else {
this.rangeZoomable = false;
}
}
/**
* Returns the flag that controls whether or not the zoom rectangle is
* filled when drawn.
*
* @return A boolean.
*/
public boolean getFillZoomRectangle() {
return this.fillZoomRectangle;
}
/**
* A flag that controls how the zoom rectangle is drawn.
*
* @param flag <code>true</code> instructs to fill the rectangle on
* zoom, otherwise it will be outlined.
*/
public void setFillZoomRectangle(boolean flag) {
this.fillZoomRectangle = flag;
}
/**
* Returns the zoom trigger distance. This controls how far the mouse must
* move before a zoom action is triggered.
*
* @return The distance (in Java2D units).
*/
public int getZoomTriggerDistance() {
return this.zoomTriggerDistance;
}
/**
* Sets the zoom trigger distance. This controls how far the mouse must
* move before a zoom action is triggered.
*
* @param distance the distance (in Java2D units).
*/
public void setZoomTriggerDistance(int distance) {
this.zoomTriggerDistance = distance;
}
/**
* Returns the flag that controls whether or not a horizontal axis trace
* line is drawn over the plot area at the current mouse location.
*
* @return A boolean.
*/
public boolean getHorizontalAxisTrace() {
return this.horizontalAxisTrace;
}
/**
* A flag that controls trace lines on the horizontal axis.
*
* @param flag <code>true</code> enables trace lines for the mouse
* pointer on the horizontal axis.
*/
public void setHorizontalAxisTrace(boolean flag) {
this.horizontalAxisTrace = flag;
}
/**
* Returns the horizontal trace line.
*
* @return The horizontal trace line (possibly <code>null</code>).
*/
protected Line2D getHorizontalTraceLine() {
return this.horizontalTraceLine;
}
/**
* Sets the horizontal trace line.
*
* @param line the line (<code>null</code> permitted).
*/
protected void setHorizontalTraceLine(Line2D line) {
this.horizontalTraceLine = line;
}
/**
* Returns the flag that controls whether or not a vertical axis trace
* line is drawn over the plot area at the current mouse location.
*
* @return A boolean.
*/
public boolean getVerticalAxisTrace() {
return this.verticalAxisTrace;
}
/**
* A flag that controls trace lines on the vertical axis.
*
* @param flag <code>true</code> enables trace lines for the mouse
* pointer on the vertical axis.
*/
public void setVerticalAxisTrace(boolean flag) {
this.verticalAxisTrace = flag;
}
/**
* Returns the vertical trace line.
*
* @return The vertical trace line (possibly <code>null</code>).
*/
protected Line2D getVerticalTraceLine() {
return this.verticalTraceLine;
}
/**
* Sets the vertical trace line.
*
* @param line the line (<code>null</code> permitted).
*/
protected void setVerticalTraceLine(Line2D line) {
this.verticalTraceLine = line;
}
/**
* Returns the default directory for the "save as" option.
*
* @return The default directory (possibly <code>null</code>).
*
* @since 1.0.7
*/
public File getDefaultDirectoryForSaveAs() {
return this.defaultDirectoryForSaveAs;
}
/**
* Sets the default directory for the "save as" option. If you set this
* to <code>null</code>, the user's default directory will be used.
*
* @param directory the directory (<code>null</code> permitted).
*
* @since 1.0.7
*/
public void setDefaultDirectoryForSaveAs(File directory) {
if (directory != null) {
if (!directory.isDirectory()) {
throw new IllegalArgumentException(
"The 'directory' argument is not a directory.");
}
}
this.defaultDirectoryForSaveAs = directory;
}
/**
* Returns <code>true</code> if file extensions should be enforced, and
* <code>false</code> otherwise.
*
* @return The flag.
*
* @see #setEnforceFileExtensions(boolean)
*/
public boolean isEnforceFileExtensions() {
return this.enforceFileExtensions;
}
/**
* Sets a flag that controls whether or not file extensions are enforced.
*
* @param enforce the new flag value.
*
* @see #isEnforceFileExtensions()
*/
public void setEnforceFileExtensions(boolean enforce) {
this.enforceFileExtensions = enforce;
}
/**
* Returns the flag that controls whether or not zoom operations are
* centered around the current anchor point.
*
* @return A boolean.
*
* @since 1.0.7
*
* @see #setZoomAroundAnchor(boolean)
*/
public boolean getZoomAroundAnchor() {
return this.zoomAroundAnchor;
}
/**
* Sets the flag that controls whether or not zoom operations are
* centered around the current anchor point.
*
* @param zoomAroundAnchor the new flag value.
*
* @since 1.0.7
*
* @see #getZoomAroundAnchor()
*/
public void setZoomAroundAnchor(boolean zoomAroundAnchor) {
this.zoomAroundAnchor = zoomAroundAnchor;
}
/**
* Returns the zoom rectangle fill paint.
*
* @return The zoom rectangle fill paint (never <code>null</code>).
*
* @see #setZoomFillPaint(java.awt.Paint)
* @see #setFillZoomRectangle(boolean)
*
* @since 1.0.13
*/
public Paint getZoomFillPaint() {
return this.zoomFillPaint;
}
/**
* Sets the zoom rectangle fill paint.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getZoomFillPaint()
* @see #getFillZoomRectangle()
*
* @since 1.0.13
*/
public void setZoomFillPaint(Paint paint) {
ParamChecks.nullNotPermitted(paint, "paint");
this.zoomFillPaint = paint;
}
/**
* Returns the zoom rectangle outline paint.
*
* @return The zoom rectangle outline paint (never <code>null</code>).
*
* @see #setZoomOutlinePaint(java.awt.Paint)
* @see #setFillZoomRectangle(boolean)
*
* @since 1.0.13
*/
public Paint getZoomOutlinePaint() {
return this.zoomOutlinePaint;
}
/**
* Sets the zoom rectangle outline paint.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getZoomOutlinePaint()
* @see #getFillZoomRectangle()
*
* @since 1.0.13
*/
public void setZoomOutlinePaint(Paint paint) {
this.zoomOutlinePaint = paint;
}
/**
* The mouse wheel handler.
*/
private MouseWheelHandler mouseWheelHandler;
/**
* Returns <code>true</code> if the mouse wheel handler is enabled, and
* <code>false</code> otherwise.
*
* @return A boolean.
*
* @since 1.0.13
*/
public boolean isMouseWheelEnabled() {
return this.mouseWheelHandler != null;
}
/**
* Enables or disables mouse wheel support for the panel.
* Note that this method does nothing when running JFreeChart on JRE 1.3.1,
* because that older version of the Java runtime does not support
* mouse wheel events.
*
* @param flag a boolean.
*
* @since 1.0.13
*/
public void setMouseWheelEnabled(boolean flag) {
if (flag && this.mouseWheelHandler == null) {
this.mouseWheelHandler = new MouseWheelHandler(this);
}
else if (!flag && this.mouseWheelHandler != null) {
this.removeMouseWheelListener(this.mouseWheelHandler);
this.mouseWheelHandler = null;
}
}
/**
* Add an overlay to the panel.
*
* @param overlay the overlay (<code>null</code> not permitted).
*
* @since 1.0.13
*/
public void addOverlay(Overlay overlay) {
ParamChecks.nullNotPermitted(overlay, "overlay");
this.overlays.add(overlay);
overlay.addChangeListener(this);
repaint();
}
/**
* Removes an overlay from the panel.
*
* @param overlay the overlay to remove (<code>null</code> not permitted).
*
* @since 1.0.13
*/
public void removeOverlay(Overlay overlay) {
ParamChecks.nullNotPermitted(overlay, "overlay");
boolean removed = this.overlays.remove(overlay);
if (removed) {
overlay.removeChangeListener(this);
repaint();
}
}
/**
* Handles a change to an overlay by repainting the panel.
*
* @param event the event.
*
* @since 1.0.13
*/
@Override
public void overlayChanged(OverlayChangeEvent event) {
repaint();
}
/**
* Switches the display of tooltips for the panel on or off. Note that
* tooltips can only be displayed if the chart has been configured to
* generate tooltip items.
*
* @param flag <code>true</code> to enable tooltips, <code>false</code> to
* disable tooltips.
*/
public void setDisplayToolTips(boolean flag) {
if (flag) {
ToolTipManager.sharedInstance().registerComponent(this);
}
else {
ToolTipManager.sharedInstance().unregisterComponent(this);
}
}
/**
* Returns a string for the tooltip.
*
* @param e the mouse event.
*
* @return A tool tip or <code>null</code> if no tooltip is available.
*/
@Override
public String getToolTipText(MouseEvent e) {
String result = null;
if (this.info != null) {
EntityCollection entities = this.info.getEntityCollection();
if (entities != null) {
Insets insets = getInsets();
ChartEntity entity = entities.getEntity(
(int) ((e.getX() - insets.left) / this.scaleX),
(int) ((e.getY() - insets.top) / this.scaleY));
if (entity != null) {
result = entity.getToolTipText();
}
}
}
return result;
}
/**
* Translates a Java2D point on the chart to a screen location.
*
* @param java2DPoint the Java2D point.
*
* @return The screen location.
*/
public Point translateJava2DToScreen(Point2D java2DPoint) {
Insets insets = getInsets();
int x = (int) (java2DPoint.getX() * this.scaleX + insets.left);
int y = (int) (java2DPoint.getY() * this.scaleY + insets.top);
return new Point(x, y);
}
/**
* Translates a panel (component) location to a Java2D point.
*
* @param screenPoint the screen location (<code>null</code> not
* permitted).
*
* @return The Java2D coordinates.
*/
public Point2D translateScreenToJava2D(Point screenPoint) {
Insets insets = getInsets();
double x = (screenPoint.getX() - insets.left) / this.scaleX;
double y = (screenPoint.getY() - insets.top) / this.scaleY;
return new Point2D.Double(x, y);
}
/**
* Applies any scaling that is in effect for the chart drawing to the
* given rectangle.
*
* @param rect the rectangle (<code>null</code> not permitted).
*
* @return A new scaled rectangle.
*/
public Rectangle2D scale(Rectangle2D rect) {
Insets insets = getInsets();
double x = rect.getX() * getScaleX() + insets.left;
double y = rect.getY() * getScaleY() + insets.top;
double w = rect.getWidth() * getScaleX();
double h = rect.getHeight() * getScaleY();
return new Rectangle2D.Double(x, y, w, h);
}
/**
* Returns the chart entity at a given point.
* <P>
* This method will return null if there is (a) no entity at the given
* point, or (b) no entity collection has been generated.
*
* @param viewX the x-coordinate.
* @param viewY the y-coordinate.
*
* @return The chart entity (possibly <code>null</code>).
*/
public ChartEntity getEntityForPoint(int viewX, int viewY) {
ChartEntity result = null;
if (this.info != null) {
Insets insets = getInsets();
double x = (viewX - insets.left) / this.scaleX;
double y = (viewY - insets.top) / this.scaleY;
EntityCollection entities = this.info.getEntityCollection();
result = entities != null ? entities.getEntity(x, y) : null;
}
return result;
}
/**
* Returns the flag that controls whether or not the offscreen buffer
* needs to be refreshed.
*
* @return A boolean.
*/
public boolean getRefreshBuffer() {
return this.refreshBuffer;
}
/**
* Sets the refresh buffer flag. This flag is used to avoid unnecessary
* redrawing of the chart when the offscreen image buffer is used.
*
* @param flag <code>true</code> indicates that the buffer should be
* refreshed.
*/
public void setRefreshBuffer(boolean flag) {
this.refreshBuffer = flag;
}
/**
* Paints the component by drawing the chart to fill the entire component,
* but allowing for the insets (which will be non-zero if a border has been
* set for this component). To increase performance (at the expense of
* memory), an off-screen buffer image can be used.
*
* @param g the graphics device for drawing on.
*/
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (this.chart == null) {
return;
}
Graphics2D g2 = (Graphics2D) g.create();
// first determine the size of the chart rendering area...
Dimension size = getSize();
Insets insets = getInsets();
Rectangle2D available = new Rectangle2D.Double(insets.left, insets.top,
size.getWidth() - insets.left - insets.right,
size.getHeight() - insets.top - insets.bottom);
// work out if scaling is required...
boolean scale = false;
double drawWidth = available.getWidth();
double drawHeight = available.getHeight();
this.scaleX = 1.0;
this.scaleY = 1.0;
if (drawWidth < this.minimumDrawWidth) {
this.scaleX = drawWidth / this.minimumDrawWidth;
drawWidth = this.minimumDrawWidth;
scale = true;
}
else if (drawWidth > this.maximumDrawWidth) {
this.scaleX = drawWidth / this.maximumDrawWidth;
drawWidth = this.maximumDrawWidth;
scale = true;
}
if (drawHeight < this.minimumDrawHeight) {
this.scaleY = drawHeight / this.minimumDrawHeight;
drawHeight = this.minimumDrawHeight;
scale = true;
}
else if (drawHeight > this.maximumDrawHeight) {
this.scaleY = drawHeight / this.maximumDrawHeight;
drawHeight = this.maximumDrawHeight;
scale = true;
}
Rectangle2D chartArea = new Rectangle2D.Double(0.0, 0.0, drawWidth,
drawHeight);
// are we using the chart buffer?
if (this.useBuffer) {
// do we need to resize the buffer?
if ((this.chartBuffer == null)
|| (this.chartBufferWidth != available.getWidth())
|| (this.chartBufferHeight != available.getHeight())) {
this.chartBufferWidth = (int) available.getWidth();
this.chartBufferHeight = (int) available.getHeight();
GraphicsConfiguration gc = g2.getDeviceConfiguration();
this.chartBuffer = gc.createCompatibleImage(
this.chartBufferWidth, this.chartBufferHeight,
Transparency.TRANSLUCENT);
this.refreshBuffer = true;
}
// do we need to redraw the buffer?
if (this.refreshBuffer) {
this.refreshBuffer = false; // clear the flag
Rectangle2D bufferArea = new Rectangle2D.Double(
0, 0, this.chartBufferWidth, this.chartBufferHeight);
// make the background of the buffer clear and transparent
Graphics2D bufferG2 = (Graphics2D)
this.chartBuffer.getGraphics();
Composite savedComposite = bufferG2.getComposite();
bufferG2.setComposite(AlphaComposite.getInstance(
AlphaComposite.CLEAR, 0.0f));
Rectangle r = new Rectangle(0, 0, this.chartBufferWidth,
this.chartBufferHeight);
bufferG2.fill(r);
bufferG2.setComposite(savedComposite);
if (scale) {
AffineTransform saved = bufferG2.getTransform();
AffineTransform st = AffineTransform.getScaleInstance(
this.scaleX, this.scaleY);
bufferG2.transform(st);
/*** IndexOutOfBoundsException here! @akardapolov ***/
try {
this.chart.draw(bufferG2, chartArea, this.anchor,
this.info);
} catch (IndexOutOfBoundsException e) {
System.out.println("IndexOutOfBoundsException in ChartPanel:paintComponent " + e.getMessage());
}
/*** IndexOutOfBoundsException here! @akardapolov ***/
bufferG2.setTransform(saved);
}
else {
this.chart.draw(bufferG2, bufferArea, this.anchor,
this.info);
}
}
// zap the buffer onto the panel...
g2.drawImage(this.chartBuffer, insets.left, insets.top, this);
}
// or redrawing the chart every time...
else {
AffineTransform saved = g2.getTransform();
g2.translate(insets.left, insets.top);
if (scale) {
AffineTransform st = AffineTransform.getScaleInstance(
this.scaleX, this.scaleY);
g2.transform(st);
}
this.chart.draw(g2, chartArea, this.anchor, this.info);
g2.setTransform(saved);
}
for (Overlay overlay : this.overlays) {
overlay.paintOverlay(g2, this);
}
// redraw the zoom rectangle (if present) - if useBuffer is false,
// we use XOR so we can XOR the rectangle away again without redrawing
// the chart
drawZoomRectangle(g2, !this.useBuffer);
drawSelectionShape(g2, !this.useBuffer);
g2.dispose();
this.anchor = null;
this.verticalTraceLine = null;
this.horizontalTraceLine = null;
}
/**
* Receives notification of changes to the chart, and redraws the chart.
*
* @param event details of the chart change event.
*/
@Override
public void chartChanged(ChartChangeEvent event) {
this.refreshBuffer = true;
Plot plot = this.chart.getPlot();
if (plot instanceof Zoomable) {
Zoomable z = (Zoomable) plot;
this.orientation = z.getOrientation();
}
repaint();
}
/**
* Receives notification of a chart progress event.
*
* @param event the event.
*/
@Override
public void chartProgress(ChartProgressEvent event) {
// does nothing - override if necessary
}
/**
* Handles action events generated by the popup menu.
*
* @param event the event.
*/
@Override
public void actionPerformed(ActionEvent event) {
String command = event.getActionCommand();
// many of the zoom methods need a screen location - all we have is
// the zoomPoint, but it might be null. Here we grab the x and y
// coordinates, or use defaults...
double screenX = -1.0;
double screenY = -1.0;
if (this.zoomPoint != null) {
screenX = this.zoomPoint.getX();
screenY = this.zoomPoint.getY();
}
if (command.equals(PROPERTIES_COMMAND)) {
doEditChartProperties();
}
else if (command.equals(COPY_COMMAND)) {
doCopy();
}
else if (command.equals(SAVE_AS_PNG_COMMAND)) {
try {
doSaveAs();
}
catch (IOException e) {
JOptionPane.showMessageDialog(this, "I/O error occurred.",
"Save As PNG", JOptionPane.WARNING_MESSAGE);
}
}
else if (command.equals(SAVE_AS_SVG_COMMAND)) {
try {
saveAsSVG(null);
} catch (IOException e) {
JOptionPane.showMessageDialog(this, "I/O error occurred.",
"Save As SVG", JOptionPane.WARNING_MESSAGE);
}
}
else if (command.equals(SAVE_AS_PDF_COMMAND)) {
saveAsPDF(null);
}
else if (command.equals(PRINT_COMMAND)) {
createChartPrintJob();
}
else if (command.equals(ZOOM_IN_BOTH_COMMAND)) {
zoomInBoth(screenX, screenY);
}
else if (command.equals(ZOOM_IN_DOMAIN_COMMAND)) {
zoomInDomain(screenX, screenY);
}
else if (command.equals(ZOOM_IN_RANGE_COMMAND)) {
zoomInRange(screenX, screenY);
}
else if (command.equals(ZOOM_OUT_BOTH_COMMAND)) {
zoomOutBoth(screenX, screenY);
}
else if (command.equals(ZOOM_OUT_DOMAIN_COMMAND)) {
zoomOutDomain(screenX, screenY);
}
else if (command.equals(ZOOM_OUT_RANGE_COMMAND)) {
zoomOutRange(screenX, screenY);
}
else if (command.equals(ZOOM_RESET_BOTH_COMMAND)) {
restoreAutoBounds();
}
else if (command.equals(ZOOM_RESET_DOMAIN_COMMAND)) {
restoreAutoDomainBounds();
}
else if (command.equals(ZOOM_RESET_RANGE_COMMAND)) {
restoreAutoRangeBounds();
}
}
/**
* Handles a 'mouse entered' event. This method changes the tooltip delays
* of ToolTipManager.sharedInstance() to the possibly different values set
* for this chart panel.
*
* @param e the mouse event.
*/
@Override
public void mouseEntered(MouseEvent e) {
if (!this.ownToolTipDelaysActive) {
ToolTipManager ttm = ToolTipManager.sharedInstance();
this.originalToolTipInitialDelay = ttm.getInitialDelay();
ttm.setInitialDelay(this.ownToolTipInitialDelay);
this.originalToolTipReshowDelay = ttm.getReshowDelay();
ttm.setReshowDelay(this.ownToolTipReshowDelay);
this.originalToolTipDismissDelay = ttm.getDismissDelay();
ttm.setDismissDelay(this.ownToolTipDismissDelay);
this.ownToolTipDelaysActive = true;
}
if (this.liveMouseHandler != null) {
this.liveMouseHandler.mouseEntered(e);
}
//handle auxiliary handlers
int mods = e.getModifiers();
for (AbstractMouseHandler handler : auxiliaryMouseHandlers) {
if (handler.getModifier() == 0 ||
(mods & handler.getModifier()) == handler.getModifier()) {
handler.mouseEntered(e);
}
}
}
/**
* Handles a 'mouse exited' event. This method resets the tooltip delays of
* ToolTipManager.sharedInstance() to their
* original values in effect before mouseEntered()
*
* @param e the mouse event.
*/
@Override
public void mouseExited(MouseEvent e) {
if (this.ownToolTipDelaysActive) {
// restore original tooltip dealys
ToolTipManager ttm = ToolTipManager.sharedInstance();
ttm.setInitialDelay(this.originalToolTipInitialDelay);
ttm.setReshowDelay(this.originalToolTipReshowDelay);
ttm.setDismissDelay(this.originalToolTipDismissDelay);
this.ownToolTipDelaysActive = false;
}
if (this.liveMouseHandler != null) {
this.liveMouseHandler.mouseExited(e);
}
//handle auxiliary handlers
int mods = e.getModifiers();
for (AbstractMouseHandler handler : auxiliaryMouseHandlers) {
if (handler.getModifier() == 0 ||
(mods & handler.getModifier()) == handler.getModifier()) {
handler.mouseExited(e);
}
}
}
/**
* Handles a 'mouse pressed' event.
* <P>
* This event is the popup trigger on Unix/Linux. For Windows, the popup
* trigger is the 'mouse released' event.
*
* @param e The mouse event.
*/
@Override
public void mousePressed(MouseEvent e) {
int mods = e.getModifiers();
if (e.isPopupTrigger()) {
if (this.popup != null) {
displayPopupMenu(e.getX(), e.getY());
}
return;
}
if (this.liveMouseHandler != null) {
this.liveMouseHandler.mousePressed(e);
} else {
AbstractMouseHandler h = null;
boolean found = false;
Iterator<AbstractMouseHandler> iterator
= this.availableLiveMouseHandlers.iterator();
AbstractMouseHandler nomod = null;
while (iterator.hasNext() && !found) {
h = (AbstractMouseHandler) iterator.next();
if (h.getModifier() == 0 && nomod == null) {
nomod = h;
} else {
found = (mods & h.getModifier()) == h.getModifier();
}
}
if (!found && nomod != null) {
h = nomod;
found = true;
}
if (found) {
this.liveMouseHandler = h;
this.liveMouseHandler.mousePressed(e);
}
}
// handle auxiliary handlers
for (AbstractMouseHandler handler : auxiliaryMouseHandlers) {
if (handler.getModifier() == 0 ||
(mods & handler.getModifier()) == handler.getModifier()) {
handler.mousePressed(e);
}
}
}
/**
* Handles a 'mouse dragged' event.
*
* @param e the mouse event.
*/
@Override
public void mouseDragged(MouseEvent e) {
// if the popup menu has already been triggered, then ignore dragging...
if (this.popup != null && this.popup.isShowing()) {
return;
}
if (this.liveMouseHandler != null) {
this.liveMouseHandler.mouseDragged(e);
}
//handle auxiliary handlers
int mods = e.getModifiers();
for (AbstractMouseHandler handler : auxiliaryMouseHandlers) {
if (handler.getModifier() == 0 ||
(mods & handler.getModifier()) == handler.getModifier()) {
handler.mouseDragged(e);
}
}
}
/**
* Handles a 'mouse released' event. On Windows, we need to check if this
* is a popup trigger, but only if we haven't already been tracking a zoom
* rectangle.
*
* @param e information about the event.
*/
@Override
public void mouseReleased(MouseEvent e) {
if (e.isPopupTrigger()) {
if (this.popup != null) {
displayPopupMenu(e.getX(), e.getY());
}
return;
}
if (this.liveMouseHandler != null) {
this.liveMouseHandler.mouseReleased(e);
}
//handle auxiliary handlers
int mods = e.getModifiers();
for (AbstractMouseHandler handler : auxiliaryMouseHandlers) {
if (handler.getModifier() == 0 ||
(mods & handler.getModifier()) == handler.getModifier()) {
handler.mouseReleased(e);
}
}
/*akardapolov*/
fireReleaseMouse();
/*akardapolov*/
}
public void zoomMReleased(Rectangle2D selection) {
// get the origin of the zoom selection in the Java2D space used for
// drawing the chart (that is, before any scaling to fit the panel)
PlotRenderingInfo plotInfo = this.info.getPlotInfo();
Rectangle2D scaledDataArea = getScreenDataArea();
plotInfo.setDataArea(scaledDataArea);
if ((selection.getHeight() > 0) && (selection.getWidth() > 0)) {
Plot p = this.chart.getPlot();
if (p instanceof XYPlot) {
XYPlot z = (XYPlot) p;
this.dLeft = z.getJava2dToValue(selection, plotInfo, 0);
this.dRight = z.getJava2dToValue(selection, plotInfo, 1);
}
}
}
/**
* Receives notification of mouse clicks on the panel. These are
* translated and passed on to any registered {@link ChartMouseListener}s.
*
* @param event Information about the mouse event.
*/
@Override
public void mouseClicked(MouseEvent event) {
Insets insets = getInsets();
int x = (int) ((event.getX() - insets.left) / this.scaleX);
int y = (int) ((event.getY() - insets.top) / this.scaleY);
this.anchor = new Point2D.Double(x, y);
if (this.chart == null) {
return;
}
this.chart.setNotify(true); // force a redraw
// new entity code...
Object[] listeners = this.chartMouseListeners.getListeners(
ChartMouseListener.class);
if (listeners.length > 0) {
// handle old listeners
ChartEntity entity = null;
if (this.info != null) {
EntityCollection entities = this.info.getEntityCollection();
if (entities != null) {
entity = entities.getEntity(x, y);
}
}
ChartMouseEvent chartEvent = new ChartMouseEvent(getChart(), event,
entity);
for (int i = listeners.length - 1; i >= 0; i -= 1) {
((ChartMouseListener) listeners[i]).chartMouseClicked(chartEvent);
}
}
// handle new mouse handler based listeners
if (this.liveMouseHandler != null) {
this.liveMouseHandler.mouseClicked(event);
}
// handle auxiliary handlers
int mods = event.getModifiers();
for (AbstractMouseHandler handler : auxiliaryMouseHandlers) {
if (handler.getModifier() == 0 ||
(mods & handler.getModifier()) == handler.getModifier()) {
handler.mouseClicked(event);
}
}
}
/**
* Implementation of the MouseMotionListener's method.
*
* @param e the event.
*/
@Override
public void mouseMoved(MouseEvent e) {
Graphics2D g2 = (Graphics2D) getGraphics();
if (this.horizontalAxisTrace) {
drawHorizontalAxisTrace(g2, e.getX());
}
if (this.verticalAxisTrace) {
drawVerticalAxisTrace(g2, e.getY());
}
g2.dispose();
Object[] listeners = this.chartMouseListeners.getListeners(
ChartMouseListener.class);
if (listeners.length > 0) {
Insets insets = getInsets();
int x = (int) ((e.getX() - insets.left) / this.scaleX);
int y = (int) ((e.getY() - insets.top) / this.scaleY);
ChartEntity entity = null;
if (this.info != null) {
EntityCollection entities = this.info.getEntityCollection();
if (entities != null) {
entity = entities.getEntity(x, y);
}
}
// we can only generate events if the panel's chart is not null
// (see bug report 1556951)
if (this.chart != null) {
ChartMouseEvent event = new ChartMouseEvent(getChart(), e, entity);
for (int i = listeners.length - 1; i >= 0; i -= 1) {
((ChartMouseListener) listeners[i]).chartMouseMoved(event);
}
}
}
// handle new mouse handler based listeners
if (this.chart != null) {
if (this.liveMouseHandler != null) {
this.liveMouseHandler.mouseMoved(e);
}
//handle auxiliary handlers
int mods = e.getModifiers();
for (AbstractMouseHandler handler : auxiliaryMouseHandlers) {
if (handler.getModifier() == 0 ||
(mods & handler.getModifier()) == handler.getModifier()) {
handler.mouseMoved(e);
}
}
}
}
/**
* Zooms in on an anchor point (specified in screen coordinate space).
*
* @param x the x value (in screen coordinates).
* @param y the y value (in screen coordinates).
*/
public void zoomInBoth(double x, double y) {
Plot plot = this.chart.getPlot();
if (plot == null) {
return;
}
// here we tweak the notify flag on the plot so that only
// one notification happens even though we update multiple
// axes...
boolean savedNotify = plot.isNotify();
plot.setNotify(false);
zoomInDomain(x, y);
zoomInRange(x, y);
plot.setNotify(savedNotify);
}
/**
* Decreases the length of the domain axis, centered about the given
* coordinate on the screen. The length of the domain axis is reduced
* by the value of {@link #getZoomInFactor()}.
*
* @param x the x coordinate (in screen coordinates).
* @param y the y-coordinate (in screen coordinates).
*/
public void zoomInDomain(double x, double y) {
Plot plot = this.chart.getPlot();
if (plot instanceof Zoomable) {
// here we tweak the notify flag on the plot so that only
// one notification happens even though we update multiple
// axes...
boolean savedNotify = plot.isNotify();
plot.setNotify(false);
Zoomable z = (Zoomable) plot;
z.zoomDomainAxes(this.zoomInFactor, this.info.getPlotInfo(),
translateScreenToJava2D(new Point((int) x, (int) y)),
this.zoomAroundAnchor);
plot.setNotify(savedNotify);
}
}
/**
* Decreases the length of the range axis, centered about the given
* coordinate on the screen. The length of the range axis is reduced by
* the value of {@link #getZoomInFactor()}.
*
* @param x the x-coordinate (in screen coordinates).
* @param y the y coordinate (in screen coordinates).
*/
public void zoomInRange(double x, double y) {
Plot plot = this.chart.getPlot();
if (plot instanceof Zoomable) {
// here we tweak the notify flag on the plot so that only
// one notification happens even though we update multiple
// axes...
boolean savedNotify = plot.isNotify();
plot.setNotify(false);
Zoomable z = (Zoomable) plot;
z.zoomRangeAxes(this.zoomInFactor, this.info.getPlotInfo(),
translateScreenToJava2D(new Point((int) x, (int) y)),
this.zoomAroundAnchor);
plot.setNotify(savedNotify);
}
}
/**
* Zooms out on an anchor point (specified in screen coordinate space).
*
* @param x the x value (in screen coordinates).
* @param y the y value (in screen coordinates).
*/
public void zoomOutBoth(double x, double y) {
Plot plot = this.chart.getPlot();
if (plot == null) {
return;
}
// here we tweak the notify flag on the plot so that only
// one notification happens even though we update multiple
// axes...
boolean savedNotify = plot.isNotify();
plot.setNotify(false);
zoomOutDomain(x, y);
zoomOutRange(x, y);
plot.setNotify(savedNotify);
}
/**
* Increases the length of the domain axis, centered about the given
* coordinate on the screen. The length of the domain axis is increased
* by the value of {@link #getZoomOutFactor()}.
*
* @param x the x coordinate (in screen coordinates).
* @param y the y-coordinate (in screen coordinates).
*/
public void zoomOutDomain(double x, double y) {
Plot plot = this.chart.getPlot();
if (plot instanceof Zoomable) {
// here we tweak the notify flag on the plot so that only
// one notification happens even though we update multiple
// axes...
boolean savedNotify = plot.isNotify();
plot.setNotify(false);
Zoomable z = (Zoomable) plot;
z.zoomDomainAxes(this.zoomOutFactor, this.info.getPlotInfo(),
translateScreenToJava2D(new Point((int) x, (int) y)),
this.zoomAroundAnchor);
plot.setNotify(savedNotify);
}
}
/**
* Increases the length the range axis, centered about the given
* coordinate on the screen. The length of the range axis is increased
* by the value of {@link #getZoomOutFactor()}.
*
* @param x the x coordinate (in screen coordinates).
* @param y the y-coordinate (in screen coordinates).
*/
public void zoomOutRange(double x, double y) {
Plot plot = this.chart.getPlot();
if (plot instanceof Zoomable) {
// here we tweak the notify flag on the plot so that only
// one notification happens even though we update multiple
// axes...
boolean savedNotify = plot.isNotify();
plot.setNotify(false);
Zoomable z = (Zoomable) plot;
z.zoomRangeAxes(this.zoomOutFactor, this.info.getPlotInfo(),
translateScreenToJava2D(new Point((int) x, (int) y)),
this.zoomAroundAnchor);
plot.setNotify(savedNotify);
}
}
/**
* Zooms in on a selected region.
*
* @param selection the selected region.
*/
public void zoom(Rectangle2D selection) {
// get the origin of the zoom selection in the Java2D space used for
// drawing the chart (that is, before any scaling to fit the panel)
Point2D selectOrigin = translateScreenToJava2D(new Point(
(int) Math.ceil(selection.getX()),
(int) Math.ceil(selection.getY())));
PlotRenderingInfo plotInfo = this.info.getPlotInfo();
Rectangle2D scaledDataArea = getScreenDataArea(
(int) selection.getCenterX(), (int) selection.getCenterY());
if ((selection.getHeight() > 0) && (selection.getWidth() > 0)) {
double hLower = (selection.getMinX() - scaledDataArea.getMinX())
/ scaledDataArea.getWidth();
double hUpper = (selection.getMaxX() - scaledDataArea.getMinX())
/ scaledDataArea.getWidth();
double vLower = (scaledDataArea.getMaxY() - selection.getMaxY())
/ scaledDataArea.getHeight();
double vUpper = (scaledDataArea.getMaxY() - selection.getMinY())
/ scaledDataArea.getHeight();
Plot p = this.chart.getPlot();
if (p instanceof Zoomable) {
// here we tweak the notify flag on the plot so that only
// one notification happens even though we update multiple
// axes...
boolean savedNotify = p.isNotify();
p.setNotify(false);
Zoomable z = (Zoomable) p;
if (z.getOrientation() == PlotOrientation.HORIZONTAL) {
z.zoomDomainAxes(vLower, vUpper, plotInfo, selectOrigin);
z.zoomRangeAxes(hLower, hUpper, plotInfo, selectOrigin);
}
else {
z.zoomDomainAxes(hLower, hUpper, plotInfo, selectOrigin);
z.zoomRangeAxes(vLower, vUpper, plotInfo, selectOrigin);
}
p.setNotify(savedNotify);
}
}
}
/**
* Restores the auto-range calculation on both axes.
*/
public void restoreAutoBounds() {
Plot plot = this.chart.getPlot();
if (plot == null) {
return;
}
// here we tweak the notify flag on the plot so that only
// one notification happens even though we update multiple
// axes...
boolean savedNotify = plot.isNotify();
plot.setNotify(false);
restoreAutoDomainBounds();
restoreAutoRangeBounds();
plot.setNotify(savedNotify);
}
/**
* Restores the auto-range calculation on the domain axis.
*/
public void restoreAutoDomainBounds() {
Plot plot = this.chart.getPlot();
if (plot instanceof Zoomable) {
Zoomable z = (Zoomable) plot;
// here we tweak the notify flag on the plot so that only
// one notification happens even though we update multiple
// axes...
boolean savedNotify = plot.isNotify();
plot.setNotify(false);
// we need to guard against this.zoomPoint being null
Point2D zp = (this.zoomPoint != null
? this.zoomPoint : new Point());
z.zoomDomainAxes(0.0, this.info.getPlotInfo(), zp);
plot.setNotify(savedNotify);
}
}
/**
* Restores the auto-range calculation on the range axis.
*/
public void restoreAutoRangeBounds() {
Plot plot = this.chart.getPlot();
if (plot instanceof Zoomable) {
Zoomable z = (Zoomable) plot;
// here we tweak the notify flag on the plot so that only
// one notification happens even though we update multiple
// axes...
boolean savedNotify = plot.isNotify();
plot.setNotify(false);
// we need to guard against this.zoomPoint being null
Point2D zp = (this.zoomPoint != null
? this.zoomPoint : new Point());
z.zoomRangeAxes(0.0, this.info.getPlotInfo(), zp);
plot.setNotify(savedNotify);
}
}
/**
* Returns the data area for the chart (the area inside the axes) with the
* current scaling applied (that is, the area as it appears on screen).
*
* @return The scaled data area.
*/
public Rectangle2D getScreenDataArea() {
Rectangle2D dataArea = this.info.getPlotInfo().getDataArea();
Insets insets = getInsets();
double x = dataArea.getX() * this.scaleX + insets.left;
double y = dataArea.getY() * this.scaleY + insets.top;
double w = dataArea.getWidth() * this.scaleX;
double h = dataArea.getHeight() * this.scaleY;
return new Rectangle2D.Double(x, y, w, h);
}
/**
* Returns the data area (the area inside the axes) for the plot or subplot,
* with the current scaling applied.
*
* @param x the x-coordinate (for subplot selection).
* @param y the y-coordinate (for subplot selection).
*
* @return The scaled data area.
*/
public Rectangle2D getScreenDataArea(int x, int y) {
PlotRenderingInfo plotInfo = this.info.getPlotInfo();
Rectangle2D result;
if (plotInfo.getSubplotCount() == 0) {
result = getScreenDataArea();
}
else {
// get the origin of the zoom selection in the Java2D space used for
// drawing the chart (that is, before any scaling to fit the panel)
Point2D selectOrigin = translateScreenToJava2D(new Point(x, y));
int subplotIndex = plotInfo.getSubplotIndex(selectOrigin);
if (subplotIndex == -1) {
return null;
}
result = scale(plotInfo.getSubplotInfo(subplotIndex).getDataArea());
}
return result;
}
/**
* Returns the initial tooltip delay value used inside this chart panel.
*
* @return An integer representing the initial delay value, in milliseconds.
*
* @see javax.swing.ToolTipManager#getInitialDelay()
*/
public int getInitialDelay() {
return this.ownToolTipInitialDelay;
}
/**
* Returns the reshow tooltip delay value used inside this chart panel.
*
* @return An integer representing the reshow delay value, in milliseconds.
*
* @see javax.swing.ToolTipManager#getReshowDelay()
*/
public int getReshowDelay() {
return this.ownToolTipReshowDelay;
}
/**
* Returns the dismissal tooltip delay value used inside this chart panel.
*
* @return An integer representing the dismissal delay value, in
* milliseconds.
*
* @see javax.swing.ToolTipManager#getDismissDelay()
*/
public int getDismissDelay() {
return this.ownToolTipDismissDelay;
}
/**
* Specifies the initial delay value for this chart panel.
*
* @param delay the number of milliseconds to delay (after the cursor has
* paused) before displaying.
*
* @see javax.swing.ToolTipManager#setInitialDelay(int)
*/
public void setInitialDelay(int delay) {
this.ownToolTipInitialDelay = delay;
}
/**
* Specifies the amount of time before the user has to wait initialDelay
* milliseconds before a tooltip will be shown.
*
* @param delay time in milliseconds
*
* @see javax.swing.ToolTipManager#setReshowDelay(int)
*/
public void setReshowDelay(int delay) {
this.ownToolTipReshowDelay = delay;
}
/**
* Specifies the dismissal delay value for this chart panel.
*
* @param delay the number of milliseconds to delay before taking away the
* tooltip
*
* @see javax.swing.ToolTipManager#setDismissDelay(int)
*/
public void setDismissDelay(int delay) {
this.ownToolTipDismissDelay = delay;
}
/**
* Returns the zoom in factor.
*
* @return The zoom in factor.
*
* @see #setZoomInFactor(double)
*/
public double getZoomInFactor() {
return this.zoomInFactor;
}
/**
* Sets the zoom in factor.
*
* @param factor the factor.
*
* @see #getZoomInFactor()
*/
public void setZoomInFactor(double factor) {
this.zoomInFactor = factor;
}
/**
* Returns the zoom out factor.
*
* @return The zoom out factor.
*
* @see #setZoomOutFactor(double)
*/
public double getZoomOutFactor() {
return this.zoomOutFactor;
}
/**
* Sets the zoom out factor.
*
* @param factor the factor.
*
* @see #getZoomOutFactor()
*/
public void setZoomOutFactor(double factor) {
this.zoomOutFactor = factor;
}
/**
* Draws zoom rectangle (if present).
* The drawing is performed in XOR mode, therefore
* when this method is called twice in a row,
* the second call will completely restore the state
* of the canvas.
*
* @param g2 the graphics device.
* @param xor use XOR for drawing?
*/
private void drawZoomRectangle(Graphics2D g2, boolean xor) {
if (this.zoomRectangle != null) {
if (xor) {
// Set XOR mode to draw the zoom rectangle
g2.setXORMode(Color.GRAY);
}
if (this.fillZoomRectangle) {
g2.setPaint(this.zoomFillPaint);
g2.fill(this.zoomRectangle);
}
else {
g2.setPaint(this.zoomOutlinePaint);
g2.draw(this.zoomRectangle);
}
if (xor) {
// Reset to the default 'overwrite' mode
g2.setPaintMode();
}
}
}
/**
* Draws zoom rectangle (if present). The drawing is performed in XOR mode,
* therefore when this method is called twice in a row, the second call will
* completely restore the state of the canvas.
*
* @param g2
* the graphics device.
* @param xor
* use XOR for drawing?
*/
private void drawSelectionShape(Graphics2D g2, boolean xor) {
if (this.selectionShape != null) {
if (xor) {
// Set XOR mode to draw the zoom rectangle
g2.setXORMode(Color.gray);
}
if (this.selectionFillPaint != null) {
g2.setPaint(this.selectionFillPaint);
g2.fill(this.selectionShape);
}
if (this.selectionOutlinePaint != null
&& this.selectionOutlineStroke != null) {
g2.setPaint(this.selectionOutlinePaint);
g2.setStroke(this.selectionOutlineStroke);
GeneralPath pp = new GeneralPath(this.selectionShape);
pp.closePath();
g2.draw(pp);
}
if (xor) {
// Reset to the default 'overwrite' mode
g2.setPaintMode();
}
}
}
/**
* Draws a vertical line used to trace the mouse position to the horizontal
* axis.
*
* @param g2 the graphics device.
* @param x the x-coordinate of the trace line.
*/
private void drawHorizontalAxisTrace(Graphics2D g2, int x) {
Rectangle2D dataArea = getScreenDataArea();
g2.setXORMode(Color.ORANGE);
if (((int) dataArea.getMinX() < x) && (x < (int) dataArea.getMaxX())) {
if (this.verticalTraceLine != null) {
g2.draw(this.verticalTraceLine);
this.verticalTraceLine.setLine(x, (int) dataArea.getMinY(), x,
(int) dataArea.getMaxY());
}
else {
this.verticalTraceLine = new Line2D.Float(x,
(int) dataArea.getMinY(), x, (int) dataArea.getMaxY());
}
g2.draw(this.verticalTraceLine);
}
// Reset to the default 'overwrite' mode
g2.setPaintMode();
}
/**
* Draws a horizontal line used to trace the mouse position to the vertical
* axis.
*
* @param g2 the graphics device.
* @param y the y-coordinate of the trace line.
*/
private void drawVerticalAxisTrace(Graphics2D g2, int y) {
Rectangle2D dataArea = getScreenDataArea();
g2.setXORMode(Color.ORANGE);
if (((int) dataArea.getMinY() < y) && (y < (int) dataArea.getMaxY())) {
if (this.horizontalTraceLine != null) {
g2.draw(this.horizontalTraceLine);
this.horizontalTraceLine.setLine((int) dataArea.getMinX(), y,
(int) dataArea.getMaxX(), y);
}
else {
this.horizontalTraceLine = new Line2D.Float(
(int) dataArea.getMinX(), y, (int) dataArea.getMaxX(),
y);
}
g2.draw(this.horizontalTraceLine);
}
// Reset to the default 'overwrite' mode
g2.setPaintMode();
}
/**
* Displays a dialog that allows the user to edit the properties for the
* current chart.
*
* @since 1.0.3
*/
public void doEditChartProperties() {
ChartEditor editor = ChartEditorManager.getChartEditor(this.chart);
int result = JOptionPane.showConfirmDialog(this, editor,
localizationResources.getString("Chart_Properties"),
JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
if (result == JOptionPane.OK_OPTION) {
editor.updateChart(this.chart);
}
}
/**
* Copies the current chart to the system clipboard.
*
* @since 1.0.13
*/
public void doCopy() {
Clipboard systemClipboard
= Toolkit.getDefaultToolkit().getSystemClipboard();
Insets insets = getInsets();
int w = getWidth() - insets.left - insets.right;
int h = getHeight() - insets.top - insets.bottom;
ChartTransferable selection = new ChartTransferable(this.chart, w, h,
getMinimumDrawWidth(), getMinimumDrawHeight(),
getMaximumDrawWidth(), getMaximumDrawHeight(), true);
systemClipboard.setContents(selection, null);
}
/**
* Opens a file chooser and gives the user an opportunity to save the chart
* in PNG format.
*
* @throws IOException if there is an I/O error.
*/
public void doSaveAs() throws IOException {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setCurrentDirectory(this.defaultDirectoryForSaveAs);
FileNameExtensionFilter filter = new FileNameExtensionFilter(
localizationResources.getString("PNG_Image_Files"), "png");
fileChooser.addChoosableFileFilter(filter);
fileChooser.setFileFilter(filter);
int option = fileChooser.showSaveDialog(this);
if (option == JFileChooser.APPROVE_OPTION) {
String filename = fileChooser.getSelectedFile().getPath();
if (isEnforceFileExtensions()) {
if (!filename.endsWith(".png")) {
filename = filename + ".png";
}
}
ChartUtilities.saveChartAsPNG(new File(filename), this.chart,
getWidth(), getHeight());
}
}
/**
* Saves the chart in SVG format (a filechooser will be displayed so that
* the user can specify the filename). Note that this method only works
* if the JFreeSVG library is on the classpath...if this library is not
* present, the method will fail.
*/
private void saveAsSVG(File f) throws IOException {
File file = f;
if (file == null) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setCurrentDirectory(this.defaultDirectoryForSaveAs);
FileNameExtensionFilter filter = new FileNameExtensionFilter(
localizationResources.getString("SVG_Files"), "svg");
fileChooser.addChoosableFileFilter(filter);
fileChooser.setFileFilter(filter);
int option = fileChooser.showSaveDialog(this);
if (option == JFileChooser.APPROVE_OPTION) {
String filename = fileChooser.getSelectedFile().getPath();
if (isEnforceFileExtensions()) {
if (!filename.endsWith(".svg")) {
filename = filename + ".svg";
}
}
file = new File(filename);
if (file.exists()) {
String fileExists = localizationResources.getString(
"FILE_EXISTS_CONFIRM_OVERWRITE");
int response = JOptionPane.showConfirmDialog(this,
fileExists, "Save As SVG",
JOptionPane.OK_CANCEL_OPTION);
if (response == JOptionPane.CANCEL_OPTION) {
file = null;
}
}
}
}
if (file != null) {
// use reflection to get the SVG string
String svg = generateSVG(getWidth(), getHeight());
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter(file));
writer.write("<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n");
writer.write(svg + "\n");
writer.flush();
} finally {
try {
if (writer != null) {
writer.close();
}
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
}
}
/**
* Generates a string containing a rendering of the chart in SVG format.
* This feature is only supported if the JFreeSVG library is included on
* the classpath.
*
* @return A string containing an SVG element for the current chart, or
* <code>null</code> if there is a problem with the method invocation
* by reflection.
*/
private String generateSVG(int width, int height) {
Graphics2D g2 = createSVGGraphics2D(width, height);
if (g2 == null) {
throw new IllegalStateException("JFreeSVG library is not present.");
}
// we suppress shadow generation, because SVG is a vector format and
// the shadow effect is applied via bitmap effects...
g2.setRenderingHint(JFreeChart.KEY_SUPPRESS_SHADOW_GENERATION, true);
String svg = null;
Rectangle2D drawArea = new Rectangle2D.Double(0, 0, width, height);
this.chart.draw(g2, drawArea);
try {
Method m = g2.getClass().getMethod("getSVGElement");
svg = (String) m.invoke(g2);
} catch (NoSuchMethodException e) {
// null will be returned
} catch (SecurityException e) {
// null will be returned
} catch (IllegalAccessException e) {
// null will be returned
} catch (IllegalArgumentException e) {
// null will be returned
} catch (InvocationTargetException e) {
// null will be returned
}
return svg;
}
private Graphics2D createSVGGraphics2D(int w, int h) {
try {
Class svgGraphics2d = Class.forName("org.jfree.graphics2d.svg.SVGGraphics2D");
Constructor ctor = svgGraphics2d.getConstructor(int.class, int.class);
return (Graphics2D) ctor.newInstance(w, h);
} catch (ClassNotFoundException ex) {
return null;
} catch (NoSuchMethodException ex) {
return null;
} catch (SecurityException ex) {
return null;
} catch (InstantiationException ex) {
return null;
} catch (IllegalAccessException ex) {
return null;
} catch (IllegalArgumentException ex) {
return null;
} catch (InvocationTargetException ex) {
return null;
}
}
/**
* Saves the chart in PDF format (a filechooser will be displayed so that
* the user can specify the filename). Note that this method only works
* if the OrsonPDF library is on the classpath...if this library is not
* present, the method will fail.
*/
private void saveAsPDF(File f) {
File file = f;
if (file == null) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setCurrentDirectory(this.defaultDirectoryForSaveAs);
FileNameExtensionFilter filter = new FileNameExtensionFilter(
localizationResources.getString("PDF_Files"), "pdf");
fileChooser.addChoosableFileFilter(filter);
fileChooser.setFileFilter(filter);
int option = fileChooser.showSaveDialog(this);
if (option == JFileChooser.APPROVE_OPTION) {
String filename = fileChooser.getSelectedFile().getPath();
if (isEnforceFileExtensions()) {
if (!filename.endsWith(".pdf")) {
filename = filename + ".pdf";
}
}
file = new File(filename);
if (file.exists()) {
String fileExists = localizationResources.getString(
"FILE_EXISTS_CONFIRM_OVERWRITE");
int response = JOptionPane.showConfirmDialog(this,
fileExists, "Save As PDF",
JOptionPane.OK_CANCEL_OPTION);
if (response == JOptionPane.CANCEL_OPTION) {
file = null;
}
}
}
}
if (file != null) {
writeAsPDF(file, getWidth(), getHeight());
}
}
/**
* Returns <code>true</code> if OrsonPDF is on the classpath, and
* <code>false</code> otherwise. The OrsonPDF library can be found at
* http://www.object-refinery.com/pdf/
*
* @return A boolean.
*/
private boolean isOrsonPDFAvailable() {
Class pdfDocumentClass = null;
try {
pdfDocumentClass = Class.forName("com.orsonpdf.PDFDocument");
} catch (ClassNotFoundException e) {
// pdfDocument class will be null so the function will return false
}
return (pdfDocumentClass != null);
}
/**
* Writes the current chart to the specified file in PDF format. This
* will only work when the OrsonPDF library is found on the classpath.
* Reflection is used to ensure there is no compile-time dependency on
* OrsonPDF (which is non-free software).
*
* @param file the output file (<code>null</code> not permitted).
* @param w the chart width.
* @param h the chart height.
*/
private void writeAsPDF(File file, int w, int h) {
if (!isOrsonPDFAvailable()) {
throw new IllegalStateException(
"OrsonPDF is not present on the classpath.");
}
ParamChecks.nullNotPermitted(file, "file");
try {
Class pdfDocClass = Class.forName("com.orsonpdf.PDFDocument");
Object pdfDoc = pdfDocClass.newInstance();
Method m = pdfDocClass.getMethod("createPage", Rectangle2D.class);
Rectangle2D rect = new Rectangle(w, h);
Object page = m.invoke(pdfDoc, rect);
Method m2 = page.getClass().getMethod("getGraphics2D");
Graphics2D g2 = (Graphics2D) m2.invoke(page);
// we suppress shadow generation, because PDF is a vector format and
// the shadow effect is applied via bitmap effects...
g2.setRenderingHint(JFreeChart.KEY_SUPPRESS_SHADOW_GENERATION, true);
Rectangle2D drawArea = new Rectangle2D.Double(0, 0, w, h);
this.chart.draw(g2, drawArea);
Method m3 = pdfDocClass.getMethod("writeToFile", File.class);
m3.invoke(pdfDoc, file);
} catch (ClassNotFoundException ex) {
throw new RuntimeException(ex);
} catch (InstantiationException ex) {
throw new RuntimeException(ex);
} catch (IllegalAccessException ex) {
throw new RuntimeException(ex);
} catch (NoSuchMethodException ex) {
throw new RuntimeException(ex);
} catch (SecurityException ex) {
throw new RuntimeException(ex);
} catch (IllegalArgumentException ex) {
throw new RuntimeException(ex);
} catch (InvocationTargetException ex) {
throw new RuntimeException(ex);
}
}
/**
* Creates a print job for the chart.
*/
public void createChartPrintJob() {
PrinterJob job = PrinterJob.getPrinterJob();
PageFormat pf = job.defaultPage();
PageFormat pf2 = job.pageDialog(pf);
if (pf2 != pf) {
job.setPrintable(this, pf2);
if (job.printDialog()) {
try {
job.print();
}
catch (PrinterException e) {
JOptionPane.showMessageDialog(this, e);
}
}
}
}
/**
* Prints the chart on a single page.
*
* @param g the graphics context.
* @param pf the page format to use.
* @param pageIndex the index of the page. If not <code>0</code>, nothing
* gets print.
*
* @return The result of printing.
*/
@Override
public int print(Graphics g, PageFormat pf, int pageIndex) {
if (pageIndex != 0) {
return NO_SUCH_PAGE;
}
Graphics2D g2 = (Graphics2D) g;
double x = pf.getImageableX();
double y = pf.getImageableY();
double w = pf.getImageableWidth();
double h = pf.getImageableHeight();
this.chart.draw(g2, new Rectangle2D.Double(x, y, w, h), this.anchor,
null);
return PAGE_EXISTS;
}
/**
* Adds a listener to the list of objects listening for chart mouse events.
*
* @param listener the listener (<code>null</code> not permitted).
*/
public void addChartMouseListener(ChartMouseListener listener) {
ParamChecks.nullNotPermitted(listener, "listener");
this.chartMouseListeners.add(ChartMouseListener.class, listener);
}
/**
* Removes a listener from the list of objects listening for chart mouse
* events.
*
* @param listener the listener.
*/
public void removeChartMouseListener(ChartMouseListener listener) {
this.chartMouseListeners.remove(ChartMouseListener.class, listener);
}
/**
* Returns an array of the listeners of the given type registered with the
* panel.
*
* @param listenerType the listener type.
*
* @return An array of listeners.
*/
@Override
public <T extends EventListener> T[] getListeners(Class<T> listenerType) {
if (listenerType == ChartMouseListener.class) {
// fetch listeners from local storage
return this.chartMouseListeners.getListeners(listenerType);
}
return super.getListeners(listenerType);
}
/**
* Creates a popup menu for the panel.
*
* @param properties include a menu item for the chart property editor.
* @param save include a menu item for saving the chart.
* @param print include a menu item for printing the chart.
* @param zoom include menu items for zooming.
*
* @return The popup menu.
*/
protected JPopupMenu createPopupMenu(boolean properties, boolean save,
boolean print, boolean zoom) {
return createPopupMenu(properties, false, save, print, zoom);
}
/**
* Creates a popup menu for the panel.
*
* @param properties include a menu item for the chart property editor.
* @param copy include a menu item for copying to the clipboard.
* @param save include a menu item for saving the chart.
* @param print include a menu item for printing the chart.
* @param zoom include menu items for zooming.
*
* @return The popup menu.
*
* @since 1.0.13
*/
protected JPopupMenu createPopupMenu(boolean properties,
boolean copy, boolean save, boolean print, boolean zoom) {
JPopupMenu result = new JPopupMenu(localizationResources.getString("Chart") + ":");
boolean separator = false;
if (properties) {
JMenuItem propertiesItem = new JMenuItem(
localizationResources.getString("Properties..."));
propertiesItem.setActionCommand(PROPERTIES_COMMAND);
propertiesItem.addActionListener(this);
result.add(propertiesItem);
separator = true;
}
if (copy) {
if (separator) {
result.addSeparator();
}
JMenuItem copyItem = new JMenuItem(
localizationResources.getString("Copy"));
copyItem.setActionCommand(COPY_COMMAND);
copyItem.addActionListener(this);
result.add(copyItem);
separator = !save;
}
if (save) {
if (separator) {
result.addSeparator();
}
JMenu saveSubMenu = new JMenu(localizationResources.getString(
"Save_as"));
JMenuItem pngItem = new JMenuItem(localizationResources.getString(
"PNG..."));
pngItem.setActionCommand("SAVE_AS_PNG");
pngItem.addActionListener(this);
saveSubMenu.add(pngItem);
if (createSVGGraphics2D(10, 10) != null) {
JMenuItem svgItem = new JMenuItem(localizationResources.getString(
"SVG..."));
svgItem.setActionCommand("SAVE_AS_SVG");
svgItem.addActionListener(this);
saveSubMenu.add(svgItem);
}
if (isOrsonPDFAvailable()) {
JMenuItem pdfItem = new JMenuItem(
localizationResources.getString("PDF..."));
pdfItem.setActionCommand("SAVE_AS_PDF");
pdfItem.addActionListener(this);
saveSubMenu.add(pdfItem);
}
result.add(saveSubMenu);
separator = true;
}
if (print) {
if (separator) {
result.addSeparator();
}
JMenuItem printItem = new JMenuItem(
localizationResources.getString("Print..."));
printItem.setActionCommand(PRINT_COMMAND);
printItem.addActionListener(this);
result.add(printItem);
separator = true;
}
if (zoom) {
if (separator) {
result.addSeparator();
}
JMenu zoomInMenu = new JMenu(
localizationResources.getString("Zoom_In"));
this.zoomInBothMenuItem = new JMenuItem(
localizationResources.getString("All_Axes"));
this.zoomInBothMenuItem.setActionCommand(ZOOM_IN_BOTH_COMMAND);
this.zoomInBothMenuItem.addActionListener(this);
zoomInMenu.add(this.zoomInBothMenuItem);
zoomInMenu.addSeparator();
this.zoomInDomainMenuItem = new JMenuItem(
localizationResources.getString("Domain_Axis"));
this.zoomInDomainMenuItem.setActionCommand(ZOOM_IN_DOMAIN_COMMAND);
this.zoomInDomainMenuItem.addActionListener(this);
zoomInMenu.add(this.zoomInDomainMenuItem);
this.zoomInRangeMenuItem = new JMenuItem(
localizationResources.getString("Range_Axis"));
this.zoomInRangeMenuItem.setActionCommand(ZOOM_IN_RANGE_COMMAND);
this.zoomInRangeMenuItem.addActionListener(this);
zoomInMenu.add(this.zoomInRangeMenuItem);
result.add(zoomInMenu);
JMenu zoomOutMenu = new JMenu(
localizationResources.getString("Zoom_Out"));
this.zoomOutBothMenuItem = new JMenuItem(
localizationResources.getString("All_Axes"));
this.zoomOutBothMenuItem.setActionCommand(ZOOM_OUT_BOTH_COMMAND);
this.zoomOutBothMenuItem.addActionListener(this);
zoomOutMenu.add(this.zoomOutBothMenuItem);
zoomOutMenu.addSeparator();
this.zoomOutDomainMenuItem = new JMenuItem(
localizationResources.getString("Domain_Axis"));
this.zoomOutDomainMenuItem.setActionCommand(
ZOOM_OUT_DOMAIN_COMMAND);
this.zoomOutDomainMenuItem.addActionListener(this);
zoomOutMenu.add(this.zoomOutDomainMenuItem);
this.zoomOutRangeMenuItem = new JMenuItem(
localizationResources.getString("Range_Axis"));
this.zoomOutRangeMenuItem.setActionCommand(ZOOM_OUT_RANGE_COMMAND);
this.zoomOutRangeMenuItem.addActionListener(this);
zoomOutMenu.add(this.zoomOutRangeMenuItem);
result.add(zoomOutMenu);
JMenu autoRangeMenu = new JMenu(
localizationResources.getString("Auto_Range"));
this.zoomResetBothMenuItem = new JMenuItem(
localizationResources.getString("All_Axes"));
this.zoomResetBothMenuItem.setActionCommand(
ZOOM_RESET_BOTH_COMMAND);
this.zoomResetBothMenuItem.addActionListener(this);
autoRangeMenu.add(this.zoomResetBothMenuItem);
autoRangeMenu.addSeparator();
this.zoomResetDomainMenuItem = new JMenuItem(
localizationResources.getString("Domain_Axis"));
this.zoomResetDomainMenuItem.setActionCommand(
ZOOM_RESET_DOMAIN_COMMAND);
this.zoomResetDomainMenuItem.addActionListener(this);
autoRangeMenu.add(this.zoomResetDomainMenuItem);
this.zoomResetRangeMenuItem = new JMenuItem(
localizationResources.getString("Range_Axis"));
this.zoomResetRangeMenuItem.setActionCommand(
ZOOM_RESET_RANGE_COMMAND);
this.zoomResetRangeMenuItem.addActionListener(this);
autoRangeMenu.add(this.zoomResetRangeMenuItem);
result.addSeparator();
result.add(autoRangeMenu);
}
return result;
}
/**
* The idea is to modify the zooming options depending on the type of chart
* being displayed by the panel.
*
* @param x horizontal position of the popup.
* @param y vertical position of the popup.
*/
protected void displayPopupMenu(int x, int y) {
if (this.popup == null) {
return;
}
// go through each zoom menu item and decide whether or not to
// enable it...
boolean isDomainZoomable = false;
boolean isRangeZoomable = false;
Plot plot = (this.chart != null ? this.chart.getPlot() : null);
if (plot instanceof Zoomable) {
Zoomable z = (Zoomable) plot;
isDomainZoomable = z.isDomainZoomable();
isRangeZoomable = z.isRangeZoomable();
}
if (this.zoomInDomainMenuItem != null) {
this.zoomInDomainMenuItem.setEnabled(isDomainZoomable);
}
if (this.zoomOutDomainMenuItem != null) {
this.zoomOutDomainMenuItem.setEnabled(isDomainZoomable);
}
if (this.zoomResetDomainMenuItem != null) {
this.zoomResetDomainMenuItem.setEnabled(isDomainZoomable);
}
if (this.zoomInRangeMenuItem != null) {
this.zoomInRangeMenuItem.setEnabled(isRangeZoomable);
}
if (this.zoomOutRangeMenuItem != null) {
this.zoomOutRangeMenuItem.setEnabled(isRangeZoomable);
}
if (this.zoomResetRangeMenuItem != null) {
this.zoomResetRangeMenuItem.setEnabled(isRangeZoomable);
}
if (this.zoomInBothMenuItem != null) {
this.zoomInBothMenuItem.setEnabled(isDomainZoomable
&& isRangeZoomable);
}
if (this.zoomOutBothMenuItem != null) {
this.zoomOutBothMenuItem.setEnabled(isDomainZoomable
&& isRangeZoomable);
}
if (this.zoomResetBothMenuItem != null) {
this.zoomResetBothMenuItem.setEnabled(isDomainZoomable
&& isRangeZoomable);
}
this.popup.show(this, x, y);
}
/**
* Updates the UI for a LookAndFeel change.
*/
@Override
public void updateUI() {
// here we need to update the UI for the popup menu, if the panel
// has one...
if (this.popup != null) {
SwingUtilities.updateComponentTreeUI(this.popup);
}
super.updateUI();
}
/**
* 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.zoomFillPaint, stream);
SerialUtilities.writePaint(this.zoomOutlinePaint, stream);
SerialUtilities.writeStroke(this.selectionOutlineStroke, 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.zoomFillPaint = SerialUtilities.readPaint(stream);
this.zoomOutlinePaint = SerialUtilities.readPaint(stream);
this.selectionOutlineStroke = SerialUtilities.readStroke(stream);
// we create a new but empty chartMouseListeners list
this.chartMouseListeners = new EventListenerList();
// register as a listener with sub-components...
if (this.chart != null) {
this.chart.addChangeListener(this);
}
}
/**
* Returns the value of the <code>useBuffer</code> flag as set in the
* constructor.
*
* @return A boolean.
*
* @since 1.0.14
*/
public boolean getUseBuffer() {
return this.useBuffer;
}
public PlotOrientation getOrientation() {
return this.orientation;
}
/**
* Adds a mouse handler.
*
* @param handler the handler (<code>null</code> not permitted).
*
* @see #removeMouseHandler(org.jfree.chart.panel.AbstractMouseHandler)
*/
public void addMouseHandler(AbstractMouseHandler handler) {
if (handler.isLiveHandler()) {
this.availableLiveMouseHandlers.add(handler);
} else {
this.auxiliaryMouseHandlers.add(handler);
}
}
/**
* Removes a mouse handler.
*
* @param handler the handler (<code>null</code> not permitted).
*
* @return A boolean.
*
* @see #addMouseHandler(org.jfree.chart.panel.AbstractMouseHandler)
*/
public boolean removeMouseHandler(AbstractMouseHandler handler) {
if (handler.isLiveHandler()) {
return this.availableLiveMouseHandlers.remove(handler);
} else {
return this.auxiliaryMouseHandlers.remove(handler);
}
}
/**
* Clears the 'liveMouseHandler' field. Each handler is responsible for
* calling this method when they have finished handling mouse events.
*/
public void clearLiveMouseHandler() {
this.liveMouseHandler = null;
}
/**
* Returns the selection shape.
*
* @return The selection shape (possibly <code>null</code>).
*
* @see #setSelectionShape(java.awt.Shape)
*/
public Shape getSelectionShape() {
return this.selectionShape;
}
/**
* Sets the selection shape.
*
* @param shape the selection shape (<code>null</code> permitted).
*
* @see #getSelectionShape()
*/
public void setSelectionShape(Shape shape) {
this.selectionShape = shape;
}
/**
* Returns the selection fill paint.
*
* @return The selection fill paint (possibly <code>null</code>).
*
* @see #setSelectionFillPaint(java.awt.Paint)
*/
public Paint getSelectionFillPaint() {
return this.selectionFillPaint;
}
/**
* Sets the selection fill paint.
*
* @param paint the paint (<code>null</code> permitted).
*
* @see #getSelectionFillPaint()
*/
public void setSelectionFillPaint(Paint paint) {
this.selectionFillPaint = paint;
}
/**
* Sets the selection outline paint.
*
* @param paint the paint (<code>null</code> permitted).
*
* @see
*/
public void setSelectionOutlinePaint(Paint paint) {
this.selectionOutlinePaint = paint;
}
/**
* Sets the selection outline stroke
*
* @param stroke the paint (<code>null</code> permitted).
*
* @see
*/
public void setSelectionOutlineStroke(Stroke stroke) {
this.selectionOutlineStroke = stroke;
}
/**
* Returns the zoom rectangle.
*
* @return The zoom rectangle (possibly <code>null</code>).
*
* @since 1.0.14
*/
public Rectangle2D getZoomRectangle() {
return this.zoomRectangle;
}
/**
* Sets the zoom rectangle for the panel.
*
* @param rect the rectangle (<code>null</code> permitted).
*
* @since 1.0.14
*/
public void setZoomRectangle(Rectangle2D rect) {
this.zoomRectangle = rect;
}
/**
* @return the zoom handler that is installed per default on each chart
* panel
*/
public ZoomHandler getZoomHandler() {
return this.zoomHandler;
}
/**
* Returns a selection manager that can be used for point or area selection.
* (e.g.
* {@link org.jfree.chart.panel.selectionhandler.RegionSelectionHandler
* RegionSelectionHandlers})
*
* @return the selection manager that has been set via setSelectionManager
* or null
*/
public SelectionManager getSelectionManager() {
return this.selectionManager;
}
/**
* Sets the selection manager of the ChartPanel. The manager can be
* retrieved via the getSelectionManager method to be used for point or
* area selection.
*
* (e.g.
* {@link org.jfree.chart.panel.selectionhandler.RegionSelectionHandler
* RegionSelectionHandlers})
*
* @param manager
*/
public void setSelectionManager(SelectionManager manager) {
this.selectionManager = manager;
}
/**
* Remove listener from ArrayList on ReleaseMouse
* @param l
* @return boolean
*/
public boolean removeListenerReleaseMouse(IDetailPanel l) {
return listenersStart.remove(l);
}
/**
* Add listener to ArrayList on ReleaseMouse
* @param l
*/
public void addListenerReleaseMouse(IDetailPanel l) {
listenersStart.add(l);
}
/**
* Send dLeft&dRight(timestamp) when mouse released
*/
protected void fireReleaseMouse() {
PlotRenderingInfo plotInfo = this.info.getPlotInfo();
Rectangle2D scaledDataArea = getScreenDataArea();
plotInfo.setDataArea(scaledDataArea);
Rectangle2D selection = getSelectionShape().getBounds2D();
/**
* Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at org.jfree.chart.ChartPanel.fireReleaseMouse(ChartPanel.java:3515)
at org.jfree.chart.ChartPanel.mouseReleased(ChartPanel.java:1966)
at java.awt.AWTEventMulticaster.mouseReleased(AWTEventMulticaster.java:290)
at java.awt.Component.processMouseEvent(Component.java:6535)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
at java.awt.Component.processEvent(Component.java:6300)
at java.awt.Container.processEvent(Container.java:2236)
at java.awt.Component.dispatchEventImpl(Component.java:4891)
at java.awt.Container.dispatchEventImpl(Container.java:2294)
at java.awt.Component.dispatchEvent(Component.java:4713)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4888)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4525)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4466)
at java.awt.Container.dispatchEventImpl(Container.java:2280)
at java.awt.Window.dispatchEventImpl(Window.java:2750)
at java.awt.Component.dispatchEvent(Component.java:4713)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)
at java.awt.EventQueue.access$500(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:709)
at java.awt.EventQueue$3.run(EventQueue.java:703)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:86)
at java.awt.EventQueue$4.run(EventQueue.java:731)
at java.awt.EventQueue$4.run(EventQueue.java:729)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
* */
Plot p = this.chart.getPlot();
if (p instanceof XYPlot) {
XYPlot z = (XYPlot) p;
this.dLeft = z.getJava2dToValue(selection, plotInfo, 0);
this.dRight = z.getJava2dToValue(selection, plotInfo, 1);
}
listenersStart.forEach(currListener ->
currListener.LoadDataToDetail(new GanttParam.Builder(this.dLeft, this.dRight).build()));
}
private List<IDetailPanel> listenersStart = Collections.synchronizedList(new ArrayList());
}
| 126,176 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
ChartMouseEvent.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/ChartMouseEvent.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.]
*
* --------------------
* ChartMouseEvent.java
* --------------------
* (C) Copyright 2002-2008, by Object Refinery Limited and Contributors.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): Alex Weber;
*
* Changes
* -------
* 27-May-2002 : Version 1, incorporating code and ideas by Alex Weber (DG);
* 13-Jun-2002 : Added Javadoc comments (DG);
* 26-Sep-2002 : Fixed errors reported by Checkstyle (DG);
* 05-Nov-2002 : Added a reference to the source chart (DG);
* 13-Jul-2004 : Now extends EventObject and implements Serializable (DG);
* ------------- JFREECHART 1.0.x ---------------------------------------------
* 24-May-2007 : Updated API docs (DG);
*
*/
package org.jfree.chart;
import java.awt.event.MouseEvent;
import java.io.Serializable;
import java.util.EventObject;
import org.jfree.chart.entity.ChartEntity;
/**
* A mouse event for a chart that is displayed in a {@link ChartPanel}.
*
* @see ChartMouseListener
*/
public class ChartMouseEvent extends EventObject implements Serializable {
/** For serialization. */
private static final long serialVersionUID = -682393837314562149L;
/** The chart that the mouse event relates to. */
private JFreeChart chart;
/** The Java mouse event that triggered this event. */
private MouseEvent trigger;
/** The chart entity (if any). */
private ChartEntity entity;
/**
* Constructs a new event.
*
* @param chart the source chart (<code>null</code> not permitted).
* @param trigger the mouse event that triggered this event
* (<code>null</code> not permitted).
* @param entity the chart entity (if any) under the mouse point
* (<code>null</code> permitted).
*/
public ChartMouseEvent(JFreeChart chart, MouseEvent trigger,
ChartEntity entity) {
super(chart);
this.chart = chart;
this.trigger = trigger;
this.entity = entity;
}
/**
* Returns the chart that the mouse event relates to.
*
* @return The chart (never <code>null</code>).
*/
public JFreeChart getChart() {
return this.chart;
}
/**
* Returns the mouse event that triggered this event.
*
* @return The event (never <code>null</code>).
*/
public MouseEvent getTrigger() {
return this.trigger;
}
/**
* Returns the chart entity (if any) under the mouse point.
*
* @return The chart entity (possibly <code>null</code>).
*/
public ChartEntity getEntity() {
return this.entity;
}
}
| 3,879 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
ChartColor.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/ChartColor.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.]
*
* ---------------
* ChartColor.java
* ---------------
* (C) Copyright 2003-2012, by Cameron Riley and Contributors.
*
* Original Author: Cameron Riley;
* Contributor(s): David Gilbert (for Object Refinery Limited);
*
* Changes
* -------
* 23-Jan-2003 : Version 1, contributed by Cameron Riley (DG);
* 25-Nov-2004 : Changed first 7 colors to softer shades (DG);
* 03-Nov-2005 : Removed orange color, too close to yellow - see bug
* report 1328408 (DG);
* ------------- JFREECHART 1.0.x ---------------------------------------------
* 02-Feb-2007 : Removed author tags all over JFreeChart sources (DG);
*
*/
package org.jfree.chart;
import java.awt.Color;
import java.awt.Paint;
/**
* Class to extend the number of Colors available to the charts. This
* extends the java.awt.Color object and extends the number of final
* Colors publically accessible.
*/
public class ChartColor extends Color {
/** A very dark red color. */
public static final Color VERY_DARK_RED = new Color(0x80, 0x00, 0x00);
/** A dark red color. */
public static final Color DARK_RED = new Color(0xc0, 0x00, 0x00);
/** A light red color. */
public static final Color LIGHT_RED = new Color(0xFF, 0x40, 0x40);
/** A very light red color. */
public static final Color VERY_LIGHT_RED = new Color(0xFF, 0x80, 0x80);
/** A very dark yellow color. */
public static final Color VERY_DARK_YELLOW = new Color(0x80, 0x80, 0x00);
/** A dark yellow color. */
public static final Color DARK_YELLOW = new Color(0xC0, 0xC0, 0x00);
/** A light yellow color. */
public static final Color LIGHT_YELLOW = new Color(0xFF, 0xFF, 0x40);
/** A very light yellow color. */
public static final Color VERY_LIGHT_YELLOW = new Color(0xFF, 0xFF, 0x80);
/** A very dark green color. */
public static final Color VERY_DARK_GREEN = new Color(0x00, 0x80, 0x00);
/** A dark green color. */
public static final Color DARK_GREEN = new Color(0x00, 0xC0, 0x00);
/** A light green color. */
public static final Color LIGHT_GREEN = new Color(0x40, 0xFF, 0x40);
/** A very light green color. */
public static final Color VERY_LIGHT_GREEN = new Color(0x80, 0xFF, 0x80);
/** A very dark cyan color. */
public static final Color VERY_DARK_CYAN = new Color(0x00, 0x80, 0x80);
/** A dark cyan color. */
public static final Color DARK_CYAN = new Color(0x00, 0xC0, 0xC0);
/** A light cyan color. */
public static final Color LIGHT_CYAN = new Color(0x40, 0xFF, 0xFF);
/** Aa very light cyan color. */
public static final Color VERY_LIGHT_CYAN = new Color(0x80, 0xFF, 0xFF);
/** A very dark blue color. */
public static final Color VERY_DARK_BLUE = new Color(0x00, 0x00, 0x80);
/** A dark blue color. */
public static final Color DARK_BLUE = new Color(0x00, 0x00, 0xC0);
/** A light blue color. */
public static final Color LIGHT_BLUE = new Color(0x40, 0x40, 0xFF);
/** A very light blue color. */
public static final Color VERY_LIGHT_BLUE = new Color(0x80, 0x80, 0xFF);
/** A very dark magenta/purple color. */
public static final Color VERY_DARK_MAGENTA = new Color(0x80, 0x00, 0x80);
/** A dark magenta color. */
public static final Color DARK_MAGENTA = new Color(0xC0, 0x00, 0xC0);
/** A light magenta color. */
public static final Color LIGHT_MAGENTA = new Color(0xFF, 0x40, 0xFF);
/** A very light magenta color. */
public static final Color VERY_LIGHT_MAGENTA = new Color(0xFF, 0x80, 0xFF);
/**
* Creates a Color with an opaque sRGB with red, green and blue values in
* range 0-255.
*
* @param r the red component in range 0x00-0xFF.
* @param g the green component in range 0x00-0xFF.
* @param b the blue component in range 0x00-0xFF.
*/
public ChartColor(int r, int g, int b) {
super(r, g, b);
}
/**
* Convenience method to return an array of <code>Paint</code> objects that
* represent the pre-defined colors in the <code>Color</code> and
* <code>ChartColor</code> objects.
*
* @return An array of objects with the <code>Paint</code> interface.
*/
public static Paint[] createDefaultPaintArray() {
return new Paint[] {
new Color(0xFF, 0x55, 0x55),
new Color(0x55, 0x55, 0xFF),
new Color(0x55, 0xFF, 0x55),
new Color(0xFF, 0xFF, 0x55),
new Color(0xFF, 0x55, 0xFF),
new Color(0x55, 0xFF, 0xFF),
Color.PINK,
Color.GRAY,
ChartColor.DARK_RED,
ChartColor.DARK_BLUE,
ChartColor.DARK_GREEN,
ChartColor.DARK_YELLOW,
ChartColor.DARK_MAGENTA,
ChartColor.DARK_CYAN,
Color.DARK_GRAY,
ChartColor.LIGHT_RED,
ChartColor.LIGHT_BLUE,
ChartColor.LIGHT_GREEN,
ChartColor.LIGHT_YELLOW,
ChartColor.LIGHT_MAGENTA,
ChartColor.LIGHT_CYAN,
Color.LIGHT_GRAY,
ChartColor.VERY_DARK_RED,
ChartColor.VERY_DARK_BLUE,
ChartColor.VERY_DARK_GREEN,
ChartColor.VERY_DARK_YELLOW,
ChartColor.VERY_DARK_MAGENTA,
ChartColor.VERY_DARK_CYAN,
ChartColor.VERY_LIGHT_RED,
ChartColor.VERY_LIGHT_BLUE,
ChartColor.VERY_LIGHT_GREEN,
ChartColor.VERY_LIGHT_YELLOW,
ChartColor.VERY_LIGHT_MAGENTA,
ChartColor.VERY_LIGHT_CYAN
};
}
}
| 6,816 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
ChartUtilities.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/ChartUtilities.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.]
*
* -------------------
* ChartUtilities.java
* -------------------
* (C) Copyright 2001-2008, by Object Refinery Limited and Contributors.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): Wolfgang Irler;
* Richard Atkinson;
* Xavier Poinsard;
*
* Changes
* -------
* 11-Dec-2001 : Version 1. The JPEG method comes from Wolfgang Irler's
* JFreeChartServletDemo class (DG);
* 23-Jan-2002 : Changed saveChartAsXXX() methods to pass IOExceptions back to
* caller (DG);
* 26-Jun-2002 : Added image map methods (DG);
* 05-Aug-2002 : Added writeBufferedImage methods
* Modified writeImageMap method to support flexible image
* maps (RA);
* 26-Aug-2002 : Added saveChartAsJPEG and writeChartAsJPEG methods with info
* objects (RA);
* 05-Sep-2002 : Added writeImageMap() method to support OverLIB
* - http://www.bosrup.com/web/overlib (RA);
* 26-Sep-2002 : Fixed errors reported by Checkstyle (DG);
* 17-Oct-2002 : Exposed JPEG quality setting and PNG compression level as
* parameters (DG);
* 25-Oct-2002 : Fixed writeChartAsJPEG() empty method bug (DG);
* 13-Mar-2003 : Updated writeImageMap method as suggested by Xavier Poinsard
* (see Feature Request 688079) (DG);
* 12-Aug-2003 : Added support for custom image maps using
* ToolTipTagFragmentGenerator and URLTagFragmentGenerator (RA);
* 02-Sep-2003 : Separated PNG encoding from writing chart to an
* OutputStream (RA);
* 04-Dec-2003 : Chart draw() method modified to include anchor point (DG);
* 20-Feb-2004 : Edited Javadocs and added argument checking (DG);
* 05-Apr-2004 : Fixed problem with buffered image type (DG);
* 01-Aug-2004 : Modified to use EncoderUtil for all image encoding (RA);
* 02-Aug-2004 : Delegated image map related functionality to ImageMapUtil (RA);
* 13-Jan-2005 : Renamed ImageMapUtil --> ImageMapUtilities, removed method
* writeImageMap(PrintWriter, String, ChartRenderingInfo) which
* exists in ImageMapUtilities (DG);
* ------------- JFREECHART 1.0.x ---------------------------------------------
* 06-Feb-2006 : API doc update (DG);
* 19-Mar-2007 : Use try-finally to close output stream in saveChartAsXXX()
* methods (DG);
* 10-Jan-2008 : Fix bug 1868251 - don't create image with transparency when
* saving to JPEG format (DG);
*
*/
package org.jfree.chart;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import org.jfree.chart.encoders.EncoderUtil;
import org.jfree.chart.encoders.ImageFormat;
import org.jfree.chart.imagemap.ImageMapUtilities;
import org.jfree.chart.imagemap.OverLIBToolTipTagFragmentGenerator;
import org.jfree.chart.imagemap.StandardToolTipTagFragmentGenerator;
import org.jfree.chart.imagemap.StandardURLTagFragmentGenerator;
import org.jfree.chart.imagemap.ToolTipTagFragmentGenerator;
import org.jfree.chart.imagemap.URLTagFragmentGenerator;
import org.jfree.chart.util.ParamChecks;
/**
* A collection of utility methods for JFreeChart. Includes methods for
* converting charts to image formats (PNG and JPEG) plus creating simple HTML
* image maps.
*
* @see ImageMapUtilities
*/
public abstract class ChartUtilities {
/**
* Applies the current theme to the specified chart. This method is
* provided for convenience, the theme itself is stored in the
* {@link ChartFactory} class.
*
* @param chart the chart (<code>null</code> not permitted).
*
* @since 1.0.11
*/
public static void applyCurrentTheme(JFreeChart chart) {
ChartFactory.getChartTheme().apply(chart);
}
/**
* Writes a chart to an output stream in PNG format.
*
* @param out the output stream (<code>null</code> not permitted).
* @param chart the chart (<code>null</code> not permitted).
* @param width the image width.
* @param height the image height.
*
* @throws IOException if there are any I/O errors.
*/
public static void writeChartAsPNG(OutputStream out, JFreeChart chart,
int width, int height) throws IOException {
// defer argument checking...
writeChartAsPNG(out, chart, width, height, null);
}
/**
* Writes a chart to an output stream in PNG format.
*
* @param out the output stream (<code>null</code> not permitted).
* @param chart the chart (<code>null</code> not permitted).
* @param width the image width.
* @param height the image height.
* @param encodeAlpha encode alpha?
* @param compression the compression level (0-9).
*
* @throws IOException if there are any I/O errors.
*/
public static void writeChartAsPNG(OutputStream out, JFreeChart chart,
int width, int height, boolean encodeAlpha, int compression)
throws IOException {
// defer argument checking...
ChartUtilities.writeChartAsPNG(out, chart, width, height, null,
encodeAlpha, compression);
}
/**
* Writes a chart to an output stream in PNG format. This method allows
* you to pass in a {@link ChartRenderingInfo} object, to collect
* information about the chart dimensions/entities. You will need this
* info if you want to create an HTML image map.
*
* @param out the output stream (<code>null</code> not permitted).
* @param chart the chart (<code>null</code> not permitted).
* @param width the image width.
* @param height the image height.
* @param info the chart rendering info (<code>null</code> permitted).
*
* @throws IOException if there are any I/O errors.
*/
public static void writeChartAsPNG(OutputStream out, JFreeChart chart,
int width, int height, ChartRenderingInfo info)
throws IOException {
ParamChecks.nullNotPermitted(chart, "chart");
BufferedImage bufferedImage
= chart.createBufferedImage(width, height, info);
EncoderUtil.writeBufferedImage(bufferedImage, ImageFormat.PNG, out);
}
/**
* Writes a chart to an output stream in PNG format. This method allows
* you to pass in a {@link ChartRenderingInfo} object, to collect
* information about the chart dimensions/entities. You will need this
* info if you want to create an HTML image map.
*
* @param out the output stream (<code>null</code> not permitted).
* @param chart the chart (<code>null</code> not permitted).
* @param width the image width.
* @param height the image height.
* @param info carries back chart rendering info (<code>null</code>
* permitted).
* @param encodeAlpha encode alpha?
* @param compression the PNG compression level (0-9).
*
* @throws IOException if there are any I/O errors.
*/
public static void writeChartAsPNG(OutputStream out, JFreeChart chart,
int width, int height, ChartRenderingInfo info,
boolean encodeAlpha, int compression) throws IOException {
ParamChecks.nullNotPermitted(out, "out");
ParamChecks.nullNotPermitted(chart, "chart");
BufferedImage chartImage = chart.createBufferedImage(width, height,
BufferedImage.TYPE_INT_ARGB, info);
ChartUtilities.writeBufferedImageAsPNG(out, chartImage, encodeAlpha,
compression);
}
/**
* Writes a scaled version of a chart to an output stream in PNG format.
*
* @param out the output stream (<code>null</code> not permitted).
* @param chart the chart (<code>null</code> not permitted).
* @param width the unscaled chart width.
* @param height the unscaled chart height.
* @param widthScaleFactor the horizontal scale factor.
* @param heightScaleFactor the vertical scale factor.
*
* @throws IOException if there are any I/O problems.
*/
public static void writeScaledChartAsPNG(OutputStream out,
JFreeChart chart, int width, int height, int widthScaleFactor,
int heightScaleFactor) throws IOException {
ParamChecks.nullNotPermitted(out, "out");
ParamChecks.nullNotPermitted(chart, "chart");
double desiredWidth = width * widthScaleFactor;
double desiredHeight = height * heightScaleFactor;
double defaultWidth = width;
double defaultHeight = height;
boolean scale = false;
// get desired width and height from somewhere then...
if ((widthScaleFactor != 1) || (heightScaleFactor != 1)) {
scale = true;
}
double scaleX = desiredWidth / defaultWidth;
double scaleY = desiredHeight / defaultHeight;
BufferedImage image = new BufferedImage((int) desiredWidth,
(int) desiredHeight, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = image.createGraphics();
if (scale) {
AffineTransform saved = g2.getTransform();
g2.transform(AffineTransform.getScaleInstance(scaleX, scaleY));
chart.draw(g2, new Rectangle2D.Double(0, 0, defaultWidth,
defaultHeight), null, null);
g2.setTransform(saved);
g2.dispose();
}
else {
chart.draw(g2, new Rectangle2D.Double(0, 0, defaultWidth,
defaultHeight), null, null);
}
out.write(encodeAsPNG(image));
}
/**
* Saves a chart to the specified file in PNG format.
*
* @param file the file name (<code>null</code> not permitted).
* @param chart the chart (<code>null</code> not permitted).
* @param width the image width.
* @param height the image height.
*
* @throws IOException if there are any I/O errors.
*/
public static void saveChartAsPNG(File file, JFreeChart chart,
int width, int height) throws IOException {
// defer argument checking...
saveChartAsPNG(file, chart, width, height, null);
}
/**
* Saves a chart to a file in PNG format. This method allows you to pass
* in a {@link ChartRenderingInfo} object, to collect information about the
* chart dimensions/entities. You will need this info if you want to
* create an HTML image map.
*
* @param file the file (<code>null</code> not permitted).
* @param chart the chart (<code>null</code> not permitted).
* @param width the image width.
* @param height the image height.
* @param info the chart rendering info (<code>null</code> permitted).
*
* @throws IOException if there are any I/O errors.
*/
public static void saveChartAsPNG(File file, JFreeChart chart,
int width, int height, ChartRenderingInfo info)
throws IOException {
ParamChecks.nullNotPermitted(file, "file");
OutputStream out = new BufferedOutputStream(new FileOutputStream(file));
try {
ChartUtilities.writeChartAsPNG(out, chart, width, height, info);
}
finally {
out.close();
}
}
/**
* Saves a chart to a file in PNG format. This method allows you to pass
* in a {@link ChartRenderingInfo} object, to collect information about the
* chart dimensions/entities. You will need this info if you want to
* create an HTML image map.
*
* @param file the file (<code>null</code> not permitted).
* @param chart the chart (<code>null</code> not permitted).
* @param width the image width.
* @param height the image height.
* @param info the chart rendering info (<code>null</code> permitted).
* @param encodeAlpha encode alpha?
* @param compression the PNG compression level (0-9).
*
* @throws IOException if there are any I/O errors.
*/
public static void saveChartAsPNG(File file, JFreeChart chart,
int width, int height, ChartRenderingInfo info, boolean encodeAlpha,
int compression) throws IOException {
ParamChecks.nullNotPermitted(file, "file");
ParamChecks.nullNotPermitted(chart, "chart");
OutputStream out = new BufferedOutputStream(new FileOutputStream(file));
try {
writeChartAsPNG(out, chart, width, height, info, encodeAlpha,
compression);
}
finally {
out.close();
}
}
/**
* Writes a chart to an output stream in JPEG format. Please note that
* JPEG is a poor format for chart images, use PNG if possible.
*
* @param out the output stream (<code>null</code> not permitted).
* @param chart the chart (<code>null</code> not permitted).
* @param width the image width.
* @param height the image height.
*
* @throws IOException if there are any I/O errors.
*/
public static void writeChartAsJPEG(OutputStream out,
JFreeChart chart, int width, int height) throws IOException {
// defer argument checking...
writeChartAsJPEG(out, chart, width, height, null);
}
/**
* Writes a chart to an output stream in JPEG format. Please note that
* JPEG is a poor format for chart images, use PNG if possible.
*
* @param out the output stream (<code>null</code> not permitted).
* @param quality the quality setting.
* @param chart the chart (<code>null</code> not permitted).
* @param width the image width.
* @param height the image height.
*
* @throws IOException if there are any I/O errors.
*/
public static void writeChartAsJPEG(OutputStream out, float quality,
JFreeChart chart, int width, int height) throws IOException {
// defer argument checking...
ChartUtilities.writeChartAsJPEG(out, quality, chart, width, height,
null);
}
/**
* Writes a chart to an output stream in JPEG format. This method allows
* you to pass in a {@link ChartRenderingInfo} object, to collect
* information about the chart dimensions/entities. You will need this
* info if you want to create an HTML image map.
*
* @param out the output stream (<code>null</code> not permitted).
* @param chart the chart (<code>null</code> not permitted).
* @param width the image width.
* @param height the image height.
* @param info the chart rendering info (<code>null</code> permitted).
*
* @throws IOException if there are any I/O errors.
*/
public static void writeChartAsJPEG(OutputStream out, JFreeChart chart,
int width, int height, ChartRenderingInfo info)
throws IOException {
ParamChecks.nullNotPermitted(chart, "chart");
BufferedImage image = chart.createBufferedImage(width, height,
BufferedImage.TYPE_INT_RGB, info);
EncoderUtil.writeBufferedImage(image, ImageFormat.JPEG, out);
}
/**
* Writes a chart to an output stream in JPEG format. This method allows
* you to pass in a {@link ChartRenderingInfo} object, to collect
* information about the chart dimensions/entities. You will need this
* info if you want to create an HTML image map.
*
* @param out the output stream (<code>null</code> not permitted).
* @param quality the output quality (0.0f to 1.0f).
* @param chart the chart (<code>null</code> not permitted).
* @param width the image width.
* @param height the image height.
* @param info the chart rendering info (<code>null</code> permitted).
*
* @throws IOException if there are any I/O errors.
*/
public static void writeChartAsJPEG(OutputStream out, float quality,
JFreeChart chart, int width, int height, ChartRenderingInfo info)
throws IOException {
ParamChecks.nullNotPermitted(chart, "chart");
BufferedImage image = chart.createBufferedImage(width, height,
BufferedImage.TYPE_INT_RGB, info);
EncoderUtil.writeBufferedImage(image, ImageFormat.JPEG, out, quality);
}
/**
* Saves a chart to a file in JPEG format.
*
* @param file the file (<code>null</code> not permitted).
* @param chart the chart (<code>null</code> not permitted).
* @param width the image width.
* @param height the image height.
*
* @throws IOException if there are any I/O errors.
*/
public static void saveChartAsJPEG(File file, JFreeChart chart,
int width, int height) throws IOException {
// defer argument checking...
saveChartAsJPEG(file, chart, width, height, null);
}
/**
* Saves a chart to a file in JPEG format.
*
* @param file the file (<code>null</code> not permitted).
* @param quality the JPEG quality setting.
* @param chart the chart (<code>null</code> not permitted).
* @param width the image width.
* @param height the image height.
*
* @throws IOException if there are any I/O errors.
*/
public static void saveChartAsJPEG(File file, float quality,
JFreeChart chart, int width, int height) throws IOException {
// defer argument checking...
saveChartAsJPEG(file, quality, chart, width, height, null);
}
/**
* Saves a chart to a file in JPEG format. This method allows you to pass
* in a {@link ChartRenderingInfo} object, to collect information about the
* chart dimensions/entities. You will need this info if you want to
* create an HTML image map.
*
* @param file the file name (<code>null</code> not permitted).
* @param chart the chart (<code>null</code> not permitted).
* @param width the image width.
* @param height the image height.
* @param info the chart rendering info (<code>null</code> permitted).
*
* @throws IOException if there are any I/O errors.
*/
public static void saveChartAsJPEG(File file, JFreeChart chart,
int width, int height, ChartRenderingInfo info) throws IOException {
ParamChecks.nullNotPermitted(file, "file");
ParamChecks.nullNotPermitted(chart, "chart");
OutputStream out = new BufferedOutputStream(new FileOutputStream(file));
try {
writeChartAsJPEG(out, chart, width, height, info);
}
finally {
out.close();
}
}
/**
* Saves a chart to a file in JPEG format. This method allows you to pass
* in a {@link ChartRenderingInfo} object, to collect information about the
* chart dimensions/entities. You will need this info if you want to
* create an HTML image map.
*
* @param file the file name (<code>null</code> not permitted).
* @param quality the quality setting.
* @param chart the chart (<code>null</code> not permitted).
* @param width the image width.
* @param height the image height.
* @param info the chart rendering info (<code>null</code> permitted).
*
* @throws IOException if there are any I/O errors.
*/
public static void saveChartAsJPEG(File file, float quality,
JFreeChart chart, int width, int height,
ChartRenderingInfo info) throws IOException {
ParamChecks.nullNotPermitted(file, "file");
ParamChecks.nullNotPermitted(chart, "chart");
OutputStream out = new BufferedOutputStream(new FileOutputStream(
file));
try {
writeChartAsJPEG(out, quality, chart, width, height, info);
}
finally {
out.close();
}
}
/**
* Writes a {@link BufferedImage} to an output stream in JPEG format.
*
* @param out the output stream (<code>null</code> not permitted).
* @param image the image (<code>null</code> not permitted).
*
* @throws IOException if there are any I/O errors.
*/
public static void writeBufferedImageAsJPEG(OutputStream out,
BufferedImage image) throws IOException {
// defer argument checking...
writeBufferedImageAsJPEG(out, 0.75f, image);
}
/**
* Writes a {@link BufferedImage} to an output stream in JPEG format.
*
* @param out the output stream (<code>null</code> not permitted).
* @param quality the image quality (0.0f to 1.0f).
* @param image the image (<code>null</code> not permitted).
*
* @throws IOException if there are any I/O errors.
*/
public static void writeBufferedImageAsJPEG(OutputStream out, float quality,
BufferedImage image) throws IOException {
EncoderUtil.writeBufferedImage(image, ImageFormat.JPEG, out, quality);
}
/**
* Writes a {@link BufferedImage} to an output stream in PNG format.
*
* @param out the output stream (<code>null</code> not permitted).
* @param image the image (<code>null</code> not permitted).
*
* @throws IOException if there are any I/O errors.
*/
public static void writeBufferedImageAsPNG(OutputStream out,
BufferedImage image) throws IOException {
EncoderUtil.writeBufferedImage(image, ImageFormat.PNG, out);
}
/**
* Writes a {@link BufferedImage} to an output stream in PNG format.
*
* @param out the output stream (<code>null</code> not permitted).
* @param image the image (<code>null</code> not permitted).
* @param encodeAlpha encode alpha?
* @param compression the compression level (0-9).
*
* @throws IOException if there are any I/O errors.
*/
public static void writeBufferedImageAsPNG(OutputStream out,
BufferedImage image, boolean encodeAlpha, int compression)
throws IOException {
EncoderUtil.writeBufferedImage(image, ImageFormat.PNG, out,
compression, encodeAlpha);
}
/**
* Encodes a {@link BufferedImage} to PNG format.
*
* @param image the image (<code>null</code> not permitted).
*
* @return A byte array in PNG format.
*
* @throws IOException if there is an I/O problem.
*/
public static byte[] encodeAsPNG(BufferedImage image) throws IOException {
return EncoderUtil.encode(image, ImageFormat.PNG);
}
/**
* Encodes a {@link BufferedImage} to PNG format.
*
* @param image the image (<code>null</code> not permitted).
* @param encodeAlpha encode alpha?
* @param compression the PNG compression level (0-9).
*
* @return The byte array in PNG format.
*
* @throws IOException if there is an I/O problem.
*/
public static byte[] encodeAsPNG(BufferedImage image, boolean encodeAlpha,
int compression) throws IOException {
return EncoderUtil.encode(image, ImageFormat.PNG, compression,
encodeAlpha);
}
/**
* Writes an image map to an output stream.
*
* @param writer the writer (<code>null</code> not permitted).
* @param name the map name (<code>null</code> not permitted).
* @param info the chart rendering info (<code>null</code> not permitted).
* @param useOverLibForToolTips whether to use OverLIB for tooltips
* (http://www.bosrup.com/web/overlib/).
*
* @throws IOException if there are any I/O errors.
*/
public static void writeImageMap(PrintWriter writer, String name,
ChartRenderingInfo info, boolean useOverLibForToolTips)
throws IOException {
ToolTipTagFragmentGenerator toolTipTagFragmentGenerator = null;
if (useOverLibForToolTips) {
toolTipTagFragmentGenerator
= new OverLIBToolTipTagFragmentGenerator();
}
else {
toolTipTagFragmentGenerator
= new StandardToolTipTagFragmentGenerator();
}
ImageMapUtilities.writeImageMap(writer, name, info,
toolTipTagFragmentGenerator,
new StandardURLTagFragmentGenerator());
}
/**
* Writes an image map to the specified writer.
*
* @param writer the writer (<code>null</code> not permitted).
* @param name the map name (<code>null</code> not permitted).
* @param info the chart rendering info (<code>null</code> not permitted).
* @param toolTipTagFragmentGenerator a generator for the HTML fragment
* that will contain the tooltip text (<code>null</code> not permitted
* if <code>info</code> contains tooltip information).
* @param urlTagFragmentGenerator a generator for the HTML fragment that
* will contain the URL reference (<code>null</code> not permitted if
* <code>info</code> contains URLs).
*
* @throws IOException if there are any I/O errors.
*/
public static void writeImageMap(PrintWriter writer, String name,
ChartRenderingInfo info,
ToolTipTagFragmentGenerator toolTipTagFragmentGenerator,
URLTagFragmentGenerator urlTagFragmentGenerator)
throws IOException {
writer.println(ImageMapUtilities.getImageMap(name, info,
toolTipTagFragmentGenerator, urlTagFragmentGenerator));
}
/**
* Creates an HTML image map. This method maps to
* {@link ImageMapUtilities#getImageMap(String, ChartRenderingInfo,
* ToolTipTagFragmentGenerator, URLTagFragmentGenerator)}, using default
* generators.
*
* @param name the map name (<code>null</code> not permitted).
* @param info the chart rendering info (<code>null</code> not permitted).
*
* @return The map tag.
*/
public static String getImageMap(String name, ChartRenderingInfo info) {
return ImageMapUtilities.getImageMap(name, info,
new StandardToolTipTagFragmentGenerator(),
new StandardURLTagFragmentGenerator());
}
/**
* Creates an HTML image map. This method maps directly to
* {@link ImageMapUtilities#getImageMap(String, ChartRenderingInfo,
* ToolTipTagFragmentGenerator, URLTagFragmentGenerator)}.
*
* @param name the map name (<code>null</code> not permitted).
* @param info the chart rendering info (<code>null</code> not permitted).
* @param toolTipTagFragmentGenerator a generator for the HTML fragment
* that will contain the tooltip text (<code>null</code> not permitted
* if <code>info</code> contains tooltip information).
* @param urlTagFragmentGenerator a generator for the HTML fragment that
* will contain the URL reference (<code>null</code> not permitted if
* <code>info</code> contains URLs).
*
* @return The map tag.
*/
public static String getImageMap(String name, ChartRenderingInfo info,
ToolTipTagFragmentGenerator toolTipTagFragmentGenerator,
URLTagFragmentGenerator urlTagFragmentGenerator) {
return ImageMapUtilities.getImageMap(name, info,
toolTipTagFragmentGenerator, urlTagFragmentGenerator);
}
}
| 28,849 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
StrokeMap.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/StrokeMap.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.]
*
* --------------
* StrokeMap.java
* --------------
* (C) Copyright 2006-2012, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes:
* --------
* 27-Sep-2006 : Version 1 (DG);
* 17-Jun-2012 : Removed JCommon dependencies (DG);
*
*/
package org.jfree.chart;
import java.awt.Stroke;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import org.jfree.chart.util.ObjectUtilities;
import org.jfree.chart.util.ParamChecks;
import org.jfree.chart.util.SerialUtilities;
/**
* A storage structure that maps <code>Comparable</code> instances with
* <code>Stroke</code> instances.
* <br><br>
* To support cloning and serialization, you should only use keys that are
* cloneable and serializable. Special handling for the <code>Stroke</code>
* instances is included in this class.
*
* @since 1.0.3
*/
public class StrokeMap implements Cloneable, Serializable {
/** For serialization. */
static final long serialVersionUID = -8148916785963525169L;
/** Storage for the keys and values. */
private transient Map<Comparable, Stroke> store;
/**
* Creates a new (empty) map.
*/
public StrokeMap() {
this.store = new TreeMap<Comparable, Stroke>();
}
/**
* Returns the stroke associated with the specified key, or
* <code>null</code>.
*
* @param key the key (<code>null</code> not permitted).
*
* @return The stroke, or <code>null</code>.
*
* @throws IllegalArgumentException if <code>key</code> is
* <code>null</code>.
*/
public Stroke getStroke(Comparable key) {
ParamChecks.nullNotPermitted(key, "key");
return this.store.get(key);
}
/**
* Returns <code>true</code> if the map contains the specified key, and
* <code>false</code> otherwise.
*
* @param key the key.
*
* @return <code>true</code> if the map contains the specified key, and
* <code>false</code> otherwise.
*/
public boolean containsKey(Comparable key) {
return this.store.containsKey(key);
}
/**
* Adds a mapping between the specified <code>key</code> and
* <code>stroke</code> values.
*
* @param key the key (<code>null</code> not permitted).
* @param stroke the stroke.
*/
public void put(Comparable key, Stroke stroke) {
ParamChecks.nullNotPermitted(key, "key");
this.store.put(key, stroke);
}
/**
* Resets the map to empty.
*/
public void clear() {
this.store.clear();
}
/**
* Tests this map 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 StrokeMap)) {
return false;
}
StrokeMap that = (StrokeMap) obj;
if (this.store.size() != that.store.size()) {
return false;
}
Set<Comparable> keys = this.store.keySet();
for (Comparable key : keys) {
Stroke s1 = getStroke(key);
Stroke s2 = that.getStroke(key);
if (!ObjectUtilities.equal(s1, s2)) {
return false;
}
}
return true;
}
/**
* Returns a clone of this <code>StrokeMap</code>.
*
* @return A clone of this instance.
*
* @throws CloneNotSupportedException if any key is not cloneable.
*/
@Override
public Object clone() throws CloneNotSupportedException {
// TODO: I think we need to make sure the keys are actually cloned,
// whereas the stroke instances are always immutable so they're OK
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();
stream.writeInt(this.store.size());
Set<Comparable> keys = this.store.keySet();
for (Comparable key : keys) {
stream.writeObject(key);
Stroke stroke = getStroke(key);
SerialUtilities.writeStroke(stroke, 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.store = new TreeMap<Comparable, Stroke>();
int keyCount = stream.readInt();
for (int i = 0; i < keyCount; i++) {
Comparable key = (Comparable) stream.readObject();
Stroke stroke = SerialUtilities.readStroke(stream);
this.store.put(key, stroke);
}
}
}
| 6,534 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
ChartFactory.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/ChartFactory.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.]
*
* -----------------
* ChartFactory.java
* -----------------
* (C) Copyright 2001-2013, by Object Refinery Limited and Contributors.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): Serge V. Grachov;
* Joao Guilherme Del Valle;
* Bill Kelemen;
* Jon Iles;
* Jelai Wang;
* Richard Atkinson;
* David Browning (for Australian Institute of Marine
* Science);
* Benoit Xhenseval;
*
* Changes
* -------
* 19-Oct-2001 : Version 1, most methods transferred from JFreeChart.java (DG);
* 22-Oct-2001 : Added methods to create stacked bar charts (DG);
* Renamed DataSource.java --> Dataset.java etc. (DG);
* 31-Oct-2001 : Added 3D-effect vertical bar and stacked-bar charts,
* contributed by Serge V. Grachov (DG);
* 07-Nov-2001 : Added a flag to control whether or not a legend is added to
* the chart (DG);
* 17-Nov-2001 : For pie chart, changed dataset from CategoryDataset to
* PieDataset (DG);
* 30-Nov-2001 : Removed try/catch handlers from chart creation, as the
* exception are now RuntimeExceptions, as suggested by Joao
* Guilherme Del Valle (DG);
* 06-Dec-2001 : Added createCombinableXXXXXCharts methods (BK);
* 12-Dec-2001 : Added createCandlestickChart() method (DG);
* 13-Dec-2001 : Updated methods for charts with new renderers (DG);
* 08-Jan-2002 : Added import for
* com.jrefinery.chart.combination.CombinedChart (DG);
* 31-Jan-2002 : Changed the createCombinableVerticalXYBarChart() method to use
* renderer (DG);
* 06-Feb-2002 : Added new method createWindPlot() (DG);
* 23-Apr-2002 : Updates to the chart and plot constructor API (DG);
* 21-May-2002 : Added new method createAreaChart() (JI);
* 06-Jun-2002 : Added new method createGanttChart() (DG);
* 11-Jun-2002 : Renamed createHorizontalStackedBarChart()
* --> createStackedHorizontalBarChart() for consistency (DG);
* 06-Aug-2002 : Updated Javadoc comments (DG);
* 21-Aug-2002 : Added createPieChart(CategoryDataset) method (DG);
* 02-Oct-2002 : Fixed errors reported by Checkstyle (DG);
* 09-Oct-2002 : Added methods including tooltips and URL flags (DG);
* 06-Nov-2002 : Moved renderers into a separate package (DG);
* 18-Nov-2002 : Changed CategoryDataset to TableDataset (DG);
* 21-Mar-2003 : Incorporated HorizontalCategoryAxis3D, see bug id 685501 (DG);
* 13-May-2003 : Merged some horizontal and vertical methods (DG);
* 24-May-2003 : Added support for timeline in createHighLowChart (BK);
* 07-Jul-2003 : Added createHistogram() method contributed by Jelai Wang (DG);
* 27-Jul-2003 : Added createStackedAreaXYChart() method (RA);
* 05-Aug-2003 : added new method createBoxAndWhiskerChart (DB);
* 08-Sep-2003 : Changed ValueAxis API (DG);
* 07-Oct-2003 : Added stepped area XY chart contributed by Matthias Rose (DG);
* 06-Nov-2003 : Added createWaterfallChart() method (DG);
* 20-Nov-2003 : Set rendering order for 3D bar charts to fix overlapping
* problems (DG);
* 25-Nov-2003 : Added createWaferMapChart() method (DG);
* 23-Dec-2003 : Renamed createPie3DChart() --> createPieChart3D for
* consistency (DG);
* 20-Jan-2004 : Added createPolarChart() method (DG);
* 28-Jan-2004 : Fixed bug (882890) with axis range in
* createStackedXYAreaChart() method (DG);
* 25-Feb-2004 : Renamed XYToolTipGenerator --> XYItemLabelGenerator (DG);
* 11-Mar-2004 : Updated for pie chart changes (DG);
* 27-Apr-2004 : Added new createPieChart() method contributed by Benoit
* Xhenseval (see RFE 942195) (DG);
* 11-May-2004 : Split StandardCategoryItemLabelGenerator
* --> StandardCategoryToolTipGenerator and
* StandardCategoryLabelGenerator (DG);
* 06-Jan-2005 : Removed deprecated methods (DG);
* 27-Jan-2005 : Added new constructor to LineAndShapeRenderer (DG);
* 28-Feb-2005 : Added docs to createBubbleChart() method (DG);
* 17-Mar-2005 : Added createRingPlot() method (DG);
* 21-Apr-2005 : Replaced Insets with RectangleInsets (DG);
* 29-Nov-2005 : Removed signal chart (DG);
* ------------- JFREECHART 1.0.x ---------------------------------------------
* 26-Jan-2006 : Corrected API docs for createScatterPlot() (DG);
* 23-Aug-2006 : Modified createStackedXYAreaChart() to use
* StackedXYAreaRenderer2, because StackedXYAreaRenderer doesn't
* handle negative values (DG);
* 27-Sep-2006 : Update createPieChart() method for deprecated code (DG);
* 29-Nov-2006 : Update createXYBarChart() to use a time based tool tip
* generator is a DateAxis is requested (DG);
* 17-Jan-2007 : Added createBoxAndWhiskerChart() method from patch 1603937
* submitted by Darren Jung (DG);
* 10-Jul-2007 : Added new methods to create pie charts with locale for
* section label and tool tip formatting (DG);
* 14-Aug-2008 : Added ChartTheme facility (DG);
* 23-Oct-2008 : Check for legacy theme in setChartTheme() and reset default
* bar painters (DG);
* 20-Dec-2008 : In createStackedAreaChart(), set category margin to 0.0 (DG);
* 15-Jun-2012 : Removed JCommon dependencies (DG);
*
*/
package org.jfree.chart;
import org.jfree.chart.axis.*;
import org.jfree.chart.labels.*;
import org.jfree.chart.plot.*;
import org.jfree.chart.renderer.DefaultPolarItemRenderer;
import org.jfree.chart.renderer.WaferMapRenderer;
import org.jfree.chart.renderer.category.*;
import org.jfree.chart.renderer.xy.*;
import org.jfree.chart.title.TextTitle;
import org.jfree.chart.ui.Layer;
import org.jfree.chart.ui.RectangleEdge;
import org.jfree.chart.ui.RectangleInsets;
import org.jfree.chart.ui.TextAnchor;
import org.jfree.chart.urls.StandardXYURLGenerator;
import org.jfree.chart.urls.XYURLGenerator;
import org.jfree.chart.util.ParamChecks;
import org.jfree.chart.util.TableOrder;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.category.IntervalCategoryDataset;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.data.general.PieDataset;
import org.jfree.data.general.WaferMapDataset;
import org.jfree.data.statistics.BoxAndWhiskerCategoryDataset;
import org.jfree.data.statistics.BoxAndWhiskerXYDataset;
import org.jfree.data.xy.*;
import java.awt.*;
import java.text.DateFormat;
import java.text.NumberFormat;
import java.util.List;
import java.util.Locale;
/**
* A collection of utility methods for creating some standard charts with
* JFreeChart.
*/
public abstract class ChartFactory {
/** The chart theme. */
private static ChartTheme currentTheme = new StandardChartTheme("JFree");
/**
* Returns the current chart theme used by the factory.
*
* @return The chart theme.
*
* @see #setChartTheme(ChartTheme)
* @see ChartUtilities#applyCurrentTheme(JFreeChart)
*
* @since 1.0.11
*/
public static ChartTheme getChartTheme() {
return currentTheme;
}
/**
* Sets the current chart theme. This will be applied to all new charts
* created via methods in this class.
*
* @param theme the theme (<code>null</code> not permitted).
*
* @see #getChartTheme()
* @see ChartUtilities#applyCurrentTheme(JFreeChart)
*
* @since 1.0.11
*/
public static void setChartTheme(ChartTheme theme) {
ParamChecks.nullNotPermitted(theme, "theme");
currentTheme = theme;
// here we do a check to see if the user is installing the "Legacy"
// theme, and reset the bar painters in that case...
if (theme instanceof StandardChartTheme) {
StandardChartTheme sct = (StandardChartTheme) theme;
if (sct.getName().equals("Legacy")) {
BarRenderer.setDefaultBarPainter(new StandardBarPainter());
XYBarRenderer.setDefaultBarPainter(new StandardXYBarPainter());
}
else {
BarRenderer.setDefaultBarPainter(new GradientBarPainter());
XYBarRenderer.setDefaultBarPainter(new GradientXYBarPainter());
}
}
}
/**
* Creates a pie chart with default settings.
* <P>
* The chart object returned by this method uses a {@link PiePlot} instance
* as the plot.
*
* @param title the chart title (<code>null</code> permitted).
* @param dataset the dataset for the chart (<code>null</code> permitted).
* @param locale the locale (<code>null</code> not permitted).
*
* @return A pie chart.
*
* @since 1.0.7
*/
public static JFreeChart createPieChart(String title, PieDataset dataset,
Locale locale) {
PiePlot plot = new PiePlot(dataset);
plot.setLabelGenerator(new StandardPieSectionLabelGenerator(locale));
plot.setInsets(new RectangleInsets(0.0, 5.0, 5.0, 5.0));
plot.setToolTipGenerator(new StandardPieToolTipGenerator(locale));
JFreeChart chart = new JFreeChart(title, plot);
currentTheme.apply(chart);
return chart;
}
/**
* Creates a pie chart with default settings.
* <P>
* The chart object returned by this method uses a {@link PiePlot} instance
* as the plot.
*
* @param title the chart title (<code>null</code> permitted).
* @param dataset the dataset for the chart (<code>null</code> permitted).
*
* @return A pie chart.
*/
public static JFreeChart createPieChart(String title, PieDataset dataset) {
PiePlot plot = new PiePlot(dataset);
plot.setLabelGenerator(new StandardPieSectionLabelGenerator());
plot.setInsets(new RectangleInsets(0.0, 5.0, 5.0, 5.0));
plot.setToolTipGenerator(new StandardPieToolTipGenerator());
JFreeChart chart = new JFreeChart(title, plot);
currentTheme.apply(chart);
return chart;
}
/**
* Creates a pie chart with default settings that compares 2 datasets.
* The colour of each section will be determined by the move from the value
* for the same key in <code>previousDataset</code>. ie if value1 > value2
* then the section will be in green (unless <code>greenForIncrease</code>
* is <code>false</code>, in which case it would be <code>red</code>).
* Each section can have a shade of red or green as the difference can be
* tailored between 0% (black) and percentDiffForMaxScale% (bright
* red/green).
* <p>
* For instance if <code>percentDiffForMaxScale</code> is 10 (10%), a
* difference of 5% will have a half shade of red/green, a difference of
* 10% or more will have a maximum shade/brightness of red/green.
* <P>
* The chart object returned by this method uses a {@link PiePlot} instance
* as the plot.
* <p>
* Written by <a href="mailto:[email protected]">Benoit
* Xhenseval</a>.
*
* @param title the chart title (<code>null</code> permitted).
* @param dataset the dataset for the chart (<code>null</code> permitted).
* @param previousDataset the dataset for the last run, this will be used
* to compare each key in the dataset
* @param percentDiffForMaxScale scale goes from bright red/green to black,
* percentDiffForMaxScale indicate the change
* required to reach top scale.
* @param greenForIncrease an increase since previousDataset will be
* displayed in green (decrease red) if true.
* @param locale the locale (<code>null</code> not permitted).
* @param subTitle displays a subtitle with colour scheme if true
* @param showDifference create a new dataset that will show the %
* difference between the two datasets.
*
* @return A pie chart.
*
* @since 1.0.7
*/
public static JFreeChart createPieChart(String title, PieDataset dataset,
PieDataset previousDataset, int percentDiffForMaxScale,
boolean greenForIncrease, Locale locale, boolean subTitle,
boolean showDifference) {
PiePlot plot = new PiePlot(dataset);
plot.setLabelGenerator(new StandardPieSectionLabelGenerator(locale));
plot.setInsets(new RectangleInsets(0.0, 5.0, 5.0, 5.0));
plot.setToolTipGenerator(new StandardPieToolTipGenerator(locale));
List<Comparable> keys = dataset.getKeys();
DefaultPieDataset series = null;
if (showDifference) {
series = new DefaultPieDataset();
}
double colorPerPercent = 255.0 / percentDiffForMaxScale;
for (Comparable key : keys) {
Number newValue = dataset.getValue(key);
Number oldValue = previousDataset.getValue(key);
if (oldValue == null) {
if (greenForIncrease) {
plot.setSectionPaint(key, Color.GREEN);
} else {
plot.setSectionPaint(key, Color.RED);
}
if (showDifference) {
assert series != null; // suppress compiler warning
series.setValue(key + " (+100%)", newValue);
}
} else {
double percentChange = (newValue.doubleValue()
/ oldValue.doubleValue() - 1.0) * 100.0;
double shade
= (Math.abs(percentChange) >= percentDiffForMaxScale ? 255
: Math.abs(percentChange) * colorPerPercent);
if (greenForIncrease
&& newValue.doubleValue() > oldValue.doubleValue()
|| !greenForIncrease && newValue.doubleValue()
< oldValue.doubleValue()) {
plot.setSectionPaint(key, new Color(0, (int) shade, 0));
} else {
plot.setSectionPaint(key, new Color((int) shade, 0, 0));
}
if (showDifference) {
assert series != null; // suppress compiler warning
series.setValue(key + " (" + (percentChange >= 0 ? "+" : "")
+ NumberFormat.getPercentInstance().format(
percentChange / 100.0) + ")", newValue);
}
}
}
if (showDifference) {
plot.setDataset(series);
}
JFreeChart chart = new JFreeChart(title, plot);
if (subTitle) {
TextTitle subtitle = new TextTitle("Bright "
+ (greenForIncrease ? "red" : "green") + "=change >=-"
+ percentDiffForMaxScale
+ "%, Bright " + (!greenForIncrease ? "red" : "green")
+ "=change >=+" + percentDiffForMaxScale + "%",
new Font("SansSerif", Font.PLAIN, 10));
chart.addSubtitle(subtitle);
}
currentTheme.apply(chart);
return chart;
}
/**
* Creates a pie chart with default settings that compares 2 datasets.
* The colour of each section will be determined by the move from the value
* for the same key in <code>previousDataset</code>. ie if value1 > value2
* then the section will be in green (unless <code>greenForIncrease</code>
* is <code>false</code>, in which case it would be <code>red</code>).
* Each section can have a shade of red or green as the difference can be
* tailored between 0% (black) and percentDiffForMaxScale% (bright
* red/green).
* <p>
* For instance if <code>percentDiffForMaxScale</code> is 10 (10%), a
* difference of 5% will have a half shade of red/green, a difference of
* 10% or more will have a maximum shade/brightness of red/green.
* <P>
* The chart object returned by this method uses a {@link PiePlot} instance
* as the plot.
* <p>
* Written by <a href="mailto:[email protected]">Benoit
* Xhenseval</a>.
*
* @param title the chart title (<code>null</code> permitted).
* @param dataset the dataset for the chart (<code>null</code> permitted).
* @param previousDataset the dataset for the last run, this will be used
* to compare each key in the dataset
* @param percentDiffForMaxScale scale goes from bright red/green to black,
* percentDiffForMaxScale indicate the change
* required to reach top scale.
* @param greenForIncrease an increase since previousDataset will be
* displayed in green (decrease red) if true.
* @param subTitle displays a subtitle with colour scheme if true
* @param showDifference create a new dataset that will show the %
* difference between the two datasets.
*
* @return A pie chart.
*/
public static JFreeChart createPieChart(String title,
PieDataset dataset, PieDataset previousDataset,
int percentDiffForMaxScale, boolean greenForIncrease,
boolean subTitle, boolean showDifference) {
PiePlot plot = new PiePlot(dataset);
plot.setLabelGenerator(new StandardPieSectionLabelGenerator());
plot.setInsets(new RectangleInsets(0.0, 5.0, 5.0, 5.0));
plot.setToolTipGenerator(new StandardPieToolTipGenerator());
List<Comparable> keys = dataset.getKeys();
DefaultPieDataset series = null;
if (showDifference) {
series = new DefaultPieDataset();
}
double colorPerPercent = 255.0 / percentDiffForMaxScale;
for (Comparable key : keys) {
Number newValue = dataset.getValue(key);
Number oldValue = previousDataset.getValue(key);
if (oldValue == null) {
if (greenForIncrease) {
plot.setSectionPaint(key, Color.GREEN);
} else {
plot.setSectionPaint(key, Color.RED);
}
if (showDifference) {
assert series != null; // suppresses compiler warning
series.setValue(key + " (+100%)", newValue);
}
} else {
double percentChange = (newValue.doubleValue()
/ oldValue.doubleValue() - 1.0) * 100.0;
double shade
= (Math.abs(percentChange) >= percentDiffForMaxScale ? 255
: Math.abs(percentChange) * colorPerPercent);
if (greenForIncrease
&& newValue.doubleValue() > oldValue.doubleValue()
|| !greenForIncrease && newValue.doubleValue()
< oldValue.doubleValue()) {
plot.setSectionPaint(key, new Color(0, (int) shade, 0));
} else {
plot.setSectionPaint(key, new Color((int) shade, 0, 0));
}
if (showDifference) {
assert series != null; // suppresses compiler warning
series.setValue(key + " (" + (percentChange >= 0 ? "+" : "")
+ NumberFormat.getPercentInstance().format(
percentChange / 100.0) + ")", newValue);
}
}
}
if (showDifference) {
plot.setDataset(series);
}
JFreeChart chart = new JFreeChart(title, plot);
if (subTitle) {
TextTitle subtitle;
subtitle = new TextTitle("Bright " + (greenForIncrease ? "red"
: "green") + "=change >=-" + percentDiffForMaxScale
+ "%, Bright " + (!greenForIncrease ? "red" : "green")
+ "=change >=+" + percentDiffForMaxScale + "%",
new Font("SansSerif", Font.PLAIN, 10));
chart.addSubtitle(subtitle);
}
currentTheme.apply(chart);
return chart;
}
/**
* Creates a ring chart with default settings.
* <P>
* The chart object returned by this method uses a {@link RingPlot}
* instance as the plot.
*
* @param title the chart title (<code>null</code> permitted).
* @param dataset the dataset for the chart (<code>null</code> permitted).
* @param locale the locale (<code>null</code> not permitted).
*
* @return A ring chart.
*
* @since 1.0.7
*/
public static JFreeChart createRingChart(String title, PieDataset dataset,
Locale locale) {
RingPlot plot = new RingPlot(dataset);
plot.setLabelGenerator(new StandardPieSectionLabelGenerator(locale));
plot.setInsets(new RectangleInsets(0.0, 5.0, 5.0, 5.0));
plot.setToolTipGenerator(new StandardPieToolTipGenerator(locale));
JFreeChart chart = new JFreeChart(title, plot);
currentTheme.apply(chart);
return chart;
}
/**
* Creates a ring chart with default settings.
* <P>
* The chart object returned by this method uses a {@link RingPlot}
* instance as the plot.
*
* @param title the chart title (<code>null</code> permitted).
* @param dataset the dataset for the chart (<code>null</code> permitted).
*
* @return A ring chart.
*/
public static JFreeChart createRingChart(String title, PieDataset dataset) {
RingPlot plot = new RingPlot(dataset);
plot.setLabelGenerator(new StandardPieSectionLabelGenerator());
plot.setInsets(new RectangleInsets(0.0, 5.0, 5.0, 5.0));
plot.setToolTipGenerator(new StandardPieToolTipGenerator());
JFreeChart chart = new JFreeChart(title, plot);
currentTheme.apply(chart);
return chart;
}
/**
* Creates a chart that displays multiple pie plots. The chart object
* returned by this method uses a {@link MultiplePiePlot} instance as the
* plot.
*
* @param title the chart title (<code>null</code> permitted).
* @param dataset the dataset (<code>null</code> permitted).
* @param order the order that the data is extracted (by row or by column)
* (<code>null</code> not permitted).
*
* @return A chart.
*/
public static JFreeChart createMultiplePieChart(String title,
CategoryDataset dataset, TableOrder order) {
ParamChecks.nullNotPermitted(order, "order");
MultiplePiePlot plot = new MultiplePiePlot(dataset);
plot.setDataExtractOrder(order);
plot.setBackgroundPaint(null);
plot.setOutlineStroke(null);
PieToolTipGenerator tooltipGenerator
= new StandardPieToolTipGenerator();
PiePlot pp = (PiePlot) plot.getPieChart().getPlot();
pp.setToolTipGenerator(tooltipGenerator);
JFreeChart chart = new JFreeChart(title, plot);
currentTheme.apply(chart);
return chart;
}
/**
* Creates a 3D pie chart using the specified dataset. The chart object
* returned by this method uses a {@link PiePlot3D} instance as the
* plot.
*
* @param title the chart title (<code>null</code> permitted).
* @param dataset the dataset for the chart (<code>null</code> permitted).
* @param locale the locale (<code>null</code> not permitted).
*
* @return A pie chart.
*
* @since 1.0.7
*/
public static JFreeChart createPieChart3D(String title, PieDataset dataset,
Locale locale) {
PiePlot3D plot = new PiePlot3D(dataset);
plot.setInsets(new RectangleInsets(0.0, 5.0, 5.0, 5.0));
plot.setToolTipGenerator(new StandardPieToolTipGenerator(locale));
JFreeChart chart = new JFreeChart(title, plot);
currentTheme.apply(chart);
return chart;
}
/**
* Creates a 3D pie chart using the specified dataset. The chart object
* returned by this method uses a {@link PiePlot3D} instance as the
* plot.
*
* @param title the chart title (<code>null</code> permitted).
* @param dataset the dataset for the chart (<code>null</code> permitted).
*
* @return A pie chart.
*/
public static JFreeChart createPieChart3D(String title,
PieDataset dataset) {
PiePlot3D plot = new PiePlot3D(dataset);
plot.setInsets(new RectangleInsets(0.0, 5.0, 5.0, 5.0));
plot.setToolTipGenerator(new StandardPieToolTipGenerator());
JFreeChart chart = new JFreeChart(title, plot);
currentTheme.apply(chart);
return chart;
}
/**
* Creates a chart that displays multiple pie plots. The chart object
* returned by this method uses a {@link MultiplePiePlot} instance as the
* plot.
*
* @param title the chart title (<code>null</code> permitted).
* @param dataset the dataset (<code>null</code> permitted).
* @param order the order that the data is extracted (by row or by column)
* (<code>null</code> not permitted).
*
* @return A chart.
*/
public static JFreeChart createMultiplePieChart3D(String title,
CategoryDataset dataset, TableOrder order) {
ParamChecks.nullNotPermitted(order, "order");
MultiplePiePlot plot = new MultiplePiePlot(dataset);
plot.setDataExtractOrder(order);
plot.setBackgroundPaint(null);
plot.setOutlineStroke(null);
JFreeChart pieChart = new JFreeChart(new PiePlot3D(null));
TextTitle seriesTitle = new TextTitle("Series Title",
new Font("SansSerif", Font.BOLD, 12));
seriesTitle.setPosition(RectangleEdge.BOTTOM);
pieChart.setTitle(seriesTitle);
pieChart.removeLegend();
pieChart.setBackgroundPaint(null);
plot.setPieChart(pieChart);
PieToolTipGenerator tooltipGenerator
= new StandardPieToolTipGenerator();
PiePlot pp = (PiePlot) plot.getPieChart().getPlot();
pp.setToolTipGenerator(tooltipGenerator);
JFreeChart chart = new JFreeChart(title, plot);
currentTheme.apply(chart);
return chart;
}
/**
* Creates a bar chart with a vertical orientation. The chart object
* returned by this method uses a {@link CategoryPlot} instance as the
* plot, with a {@link CategoryAxis} for the domain axis, a
* {@link NumberAxis} as the range axis, and a {@link BarRenderer} as the
* renderer.
*
* @param title the chart title (<code>null</code> permitted).
* @param categoryAxisLabel the label for the category axis
* (<code>null</code> permitted).
* @param valueAxisLabel the label for the value axis
* (<code>null</code> permitted).
* @param dataset the dataset for the chart (<code>null</code> permitted).
*
* @return A bar chart.
*/
public static JFreeChart createBarChart(String title,
String categoryAxisLabel, String valueAxisLabel,
CategoryDataset dataset) {
CategoryAxis categoryAxis = new CategoryAxis(categoryAxisLabel);
ValueAxis valueAxis = new NumberAxis(valueAxisLabel);
BarRenderer renderer = new BarRenderer();
ItemLabelPosition position1 = new ItemLabelPosition(
ItemLabelAnchor.OUTSIDE12, TextAnchor.BOTTOM_CENTER);
renderer.setDefaultPositiveItemLabelPosition(position1);
ItemLabelPosition position2 = new ItemLabelPosition(
ItemLabelAnchor.OUTSIDE6, TextAnchor.TOP_CENTER);
renderer.setDefaultNegativeItemLabelPosition(position2);
renderer.setDefaultToolTipGenerator(
new StandardCategoryToolTipGenerator());
CategoryPlot plot = new CategoryPlot(dataset, categoryAxis, valueAxis,
renderer);
JFreeChart chart = new JFreeChart(title, plot);
currentTheme.apply(chart);
return chart;
}
/**
* Creates a stacked bar chart with default settings. The chart object
* returned by this method uses a {@link CategoryPlot} instance as the
* plot, with a {@link CategoryAxis} for the domain axis, a
* {@link NumberAxis} as the range axis, and a {@link StackedBarRenderer}
* as the renderer.
*
* @param title the chart title (<code>null</code> permitted).
* @param domainAxisLabel the label for the category axis
* (<code>null</code> permitted).
* @param rangeAxisLabel the label for the value axis
* (<code>null</code> permitted).
* @param dataset the dataset for the chart (<code>null</code> permitted).
*
* @return A stacked bar chart.
*/
public static JFreeChart createStackedBarChart(String title,
String domainAxisLabel, String rangeAxisLabel,
CategoryDataset dataset) {
CategoryAxis categoryAxis = new CategoryAxis(domainAxisLabel);
ValueAxis valueAxis = new NumberAxis(rangeAxisLabel);
StackedBarRenderer renderer = new StackedBarRenderer();
renderer.setDefaultToolTipGenerator(
new StandardCategoryToolTipGenerator());
CategoryPlot plot = new CategoryPlot(dataset, categoryAxis, valueAxis,
renderer);
JFreeChart chart = new JFreeChart(title, plot);
currentTheme.apply(chart);
return chart;
}
/**
* Creates a bar chart with a 3D effect. The chart object returned by this
* method uses a {@link CategoryPlot} instance as the plot, with a
* {@link CategoryAxis3D} for the domain axis, a {@link NumberAxis3D} as
* the range axis, and a {@link BarRenderer3D} as the renderer.
*
* @param title the chart title (<code>null</code> permitted).
* @param categoryAxisLabel the label for the category axis
* (<code>null</code> permitted).
* @param valueAxisLabel the label for the value axis (<code>null</code>
* permitted).
* @param dataset the dataset for the chart (<code>null</code> permitted).
*
* @return A bar chart with a 3D effect.
*/
public static JFreeChart createBarChart3D(String title,
String categoryAxisLabel, String valueAxisLabel,
CategoryDataset dataset) {
CategoryAxis categoryAxis = new CategoryAxis3D(categoryAxisLabel);
ValueAxis valueAxis = new NumberAxis3D(valueAxisLabel);
BarRenderer3D renderer = new BarRenderer3D();
renderer.setDefaultToolTipGenerator(
new StandardCategoryToolTipGenerator());
CategoryPlot plot = new CategoryPlot(dataset, categoryAxis, valueAxis,
renderer);
// FIXME create a new method for the horizontal version
// plot.setOrientation(orientation);
// if (orientation == PlotOrientation.HORIZONTAL) {
// // change rendering order to ensure that bar overlapping is the
// // right way around
// plot.setRowRenderingOrder(SortOrder.DESCENDING);
// plot.setColumnRenderingOrder(SortOrder.DESCENDING);
// }
plot.setForegroundAlpha(0.75f);
JFreeChart chart = new JFreeChart(title, plot);
currentTheme.apply(chart);
return chart;
}
/**
* Creates a stacked bar chart with a 3D effect and default settings. The
* chart object returned by this method uses a {@link CategoryPlot}
* instance as the plot, with a {@link CategoryAxis3D} for the domain axis,
* a {@link NumberAxis3D} as the range axis, and a
* {@link StackedBarRenderer3D} as the renderer.
*
* @param title the chart title (<code>null</code> permitted).
* @param categoryAxisLabel the label for the category axis
* (<code>null</code> permitted).
* @param valueAxisLabel the label for the value axis (<code>null</code>
* permitted).
* @param dataset the dataset for the chart (<code>null</code> permitted).
*
* @return A stacked bar chart with a 3D effect.
*/
public static JFreeChart createStackedBarChart3D(String title,
String categoryAxisLabel, String valueAxisLabel,
CategoryDataset dataset) {
CategoryAxis categoryAxis = new CategoryAxis3D(categoryAxisLabel);
ValueAxis valueAxis = new NumberAxis3D(valueAxisLabel);
// create the renderer...
CategoryItemRenderer renderer = new StackedBarRenderer3D();
renderer.setDefaultToolTipGenerator(
new StandardCategoryToolTipGenerator());
// create the plot...
CategoryPlot plot = new CategoryPlot(dataset, categoryAxis, valueAxis,
renderer);
// FIXME create a new method for the horizontal version
// plot.setOrientation(orientation);
// if (orientation == PlotOrientation.HORIZONTAL) {
// change rendering order to ensure that bar overlapping is the
// right way around
// plot.setColumnRenderingOrder(SortOrder.DESCENDING);
// }
// create the chart...
JFreeChart chart = new JFreeChart(title, plot);
currentTheme.apply(chart);
return chart;
}
/**
* Creates an area chart with default settings. The chart object returned
* by this method uses a {@link CategoryPlot} instance as the plot, with a
* {@link CategoryAxis} for the domain axis, a {@link NumberAxis} as the
* range axis, and an {@link AreaRenderer} as the renderer.
*
* @param title the chart title (<code>null</code> permitted).
* @param categoryAxisLabel the label for the category axis
* (<code>null</code> permitted).
* @param valueAxisLabel the label for the value axis (<code>null</code>
* permitted).
* @param dataset the dataset for the chart (<code>null</code> permitted).
*
* @return An area chart.
*/
public static JFreeChart createAreaChart(String title,
String categoryAxisLabel, String valueAxisLabel,
CategoryDataset dataset) {
CategoryAxis categoryAxis = new CategoryAxis(categoryAxisLabel);
categoryAxis.setCategoryMargin(0.0);
ValueAxis valueAxis = new NumberAxis(valueAxisLabel);
AreaRenderer renderer = new AreaRenderer();
renderer.setDefaultToolTipGenerator(
new StandardCategoryToolTipGenerator());
CategoryPlot plot = new CategoryPlot(dataset, categoryAxis, valueAxis,
renderer);
JFreeChart chart = new JFreeChart(title, plot);
currentTheme.apply(chart);
return chart;
}
/**
* Creates a stacked area chart with default settings. The chart object
* returned by this method uses a {@link CategoryPlot} instance as the
* plot, with a {@link CategoryAxis} for the domain axis, a
* {@link NumberAxis} as the range axis, and a {@link StackedAreaRenderer}
* as the renderer.
*
* @param title the chart title (<code>null</code> permitted).
* @param categoryAxisLabel the label for the category axis
* (<code>null</code> permitted).
* @param valueAxisLabel the label for the value axis (<code>null</code>
* permitted).
* @param dataset the dataset for the chart (<code>null</code> permitted).
*
* @return A stacked area chart.
*/
public static JFreeChart createStackedAreaChart(String title,
String categoryAxisLabel, String valueAxisLabel,
CategoryDataset dataset) {
CategoryAxis categoryAxis = new CategoryAxis(categoryAxisLabel);
categoryAxis.setCategoryMargin(0.0);
ValueAxis valueAxis = new NumberAxis(valueAxisLabel);
StackedAreaRenderer renderer = new StackedAreaRenderer();
renderer.setDefaultToolTipGenerator(
new StandardCategoryToolTipGenerator());
CategoryPlot plot = new CategoryPlot(dataset, categoryAxis, valueAxis,
renderer);
JFreeChart chart = new JFreeChart(title, plot);
currentTheme.apply(chart);
return chart;
}
/**
* Creates a stacked XY area plot. The chart object returned by this
* method uses an {@link XYPlot} instance as the plot, with a
* {@link NumberAxis} for the domain axis, a {@link NumberAxis} as the
* range axis, and a {@link StackedXYAreaRenderer2} as the renderer.
*
* @param title the chart title (<code>null</code> permitted).
* @param xAxisLabel a label for the X-axis (<code>null</code> permitted).
* @param yAxisLabel a label for the Y-axis (<code>null</code> permitted).
* @param dataset the dataset for the chart (<code>null</code> permitted).
* @param orientation the plot orientation (horizontal or vertical)
* (<code>null</code> NOT permitted).
* @param legend a flag specifying whether or not a legend is required.
* @param tooltips configure chart to generate tool tips?
* @param urls configure chart to generate URLs?
*
* @return A stacked XY area chart.
*/
public static JFreeChart createStackedXYAreaChart(String title,
String xAxisLabel,
String yAxisLabel,
TableXYDataset dataset,
PlotOrientation orientation,
DateAxis xAxis,
boolean legend,
boolean tooltips,
boolean urls) {
if (orientation == null) {
throw new IllegalArgumentException("Null 'orientation' argument.");
}
/*
NumberAxis xAxis = new NumberAxis(xAxisLabel);
xAxis.setAutoRangeIncludesZero(false);
*/
xAxis.setLabel(xAxisLabel);
xAxis.setLowerMargin(0.0);
xAxis.setUpperMargin(0.0);
NumberAxis yAxis = new NumberAxis(yAxisLabel);
XYToolTipGenerator toolTipGenerator = null;
if (tooltips) {
toolTipGenerator = new StandardXYToolTipGenerator();
}
XYURLGenerator urlGenerator = null;
if (urls) {
urlGenerator = new StandardXYURLGenerator();
}
StackedXYAreaRenderer2 renderer = new StackedXYAreaRenderer2(
toolTipGenerator, urlGenerator);
renderer.setOutline(true);
XYPlot plot = new XYPlot(dataset, xAxis, yAxis, renderer);
plot.setOrientation(orientation);
plot.setRangeAxis(yAxis); // forces recalculation of the axis range
JFreeChart chart = new JFreeChart(title, JFreeChart.DEFAULT_TITLE_FONT,
plot, legend);
currentTheme.apply(chart);
return chart;
}
/**
* Creates a stacked XY area plot. The chart object returned by this
* method uses an {@link XYPlot} instance as the plot, with a
* {@link NumberAxis} for the domain axis, a {@link NumberAxis} as the
* range axis, and a {@link StackedXYAreaRenderer2} as the renderer.
*
* @param title the chart title (<code>null</code> permitted).
* @param yAxisLabel a label for the Y-axis (<code>null</code> permitted).
* @param dataset the dataset for the chart (<code>null</code> permitted).
* @param orientation the plot orientation (horizontal or vertical)
* (<code>null</code> NOT permitted).
* @param legend a flag specifying whether or not a legend is required.
* @param tooltips configure chart to generate tool tips?
* @param urls configure chart to generate URLs?
*
* @return A stacked XY area chart.
*/
public static JFreeChart createStackedXYAreaChart(String title,
String yAxisLabel,
TableXYDataset dataset,
PlotOrientation orientation,
DateAxis xAxis,
boolean legend,
boolean tooltips,
boolean urls) {
if (orientation == null) {
throw new IllegalArgumentException("Null 'orientation' argument.");
}
xAxis.setLowerMargin(0.0);
xAxis.setUpperMargin(0.0);
NumberAxis yAxis = new NumberAxis(yAxisLabel);
XYToolTipGenerator toolTipGenerator = null;
if (tooltips) {
toolTipGenerator = new StandardXYToolTipGenerator();
}
XYURLGenerator urlGenerator = null;
if (urls) {
urlGenerator = new StandardXYURLGenerator();
}
StackedXYAreaRenderer3 renderer = new StackedXYAreaRenderer3(
toolTipGenerator, urlGenerator);
renderer.setOutline(true);
XYPlot plot = new XYPlot(dataset, xAxis, yAxis, renderer);
plot.setOrientation(orientation);
plot.setRangeAxis(yAxis); // forces recalculation of the axis range
JFreeChart chart = new JFreeChart(title, JFreeChart.DEFAULT_TITLE_FONT,
plot, legend);
currentTheme.apply(chart);
return chart;
}
/**
* Creates a line chart with default settings. The chart object returned
* by this method uses a {@link CategoryPlot} instance as the plot, with a
* {@link CategoryAxis} for the domain axis, a {@link NumberAxis} as the
* range axis, and a {@link LineAndShapeRenderer} as the renderer.
*
* @param title the chart title (<code>null</code> permitted).
* @param categoryAxisLabel the label for the category axis
* (<code>null</code> permitted).
* @param valueAxisLabel the label for the value axis (<code>null</code>
* permitted).
* @param dataset the dataset for the chart (<code>null</code> permitted).
*
* @return A line chart.
*/
public static JFreeChart createLineChart(String title,
String categoryAxisLabel, String valueAxisLabel,
CategoryDataset dataset) {
CategoryAxis categoryAxis = new CategoryAxis(categoryAxisLabel);
ValueAxis valueAxis = new NumberAxis(valueAxisLabel);
LineAndShapeRenderer renderer = new LineAndShapeRenderer(true, false);
renderer.setDefaultToolTipGenerator(
new StandardCategoryToolTipGenerator());
CategoryPlot plot = new CategoryPlot(dataset, categoryAxis, valueAxis,
renderer);
JFreeChart chart = new JFreeChart(title, plot);
currentTheme.apply(chart);
return chart;
}
/**
* Creates a line chart with default settings. The chart object returned by
* this method uses a {@link CategoryPlot} instance as the plot, with a
* {@link CategoryAxis3D} for the domain axis, a {@link NumberAxis3D} as
* the range axis, and a {@link LineRenderer3D} as the renderer.
*
* @param title the chart title (<code>null</code> permitted).
* @param categoryAxisLabel the label for the category axis
* (<code>null</code> permitted).
* @param valueAxisLabel the label for the value axis (<code>null</code>
* permitted).
* @param dataset the dataset for the chart (<code>null</code> permitted).
*
* @return A line chart.
*/
public static JFreeChart createLineChart3D(String title,
String categoryAxisLabel, String valueAxisLabel,
CategoryDataset dataset) {
CategoryAxis categoryAxis = new CategoryAxis3D(categoryAxisLabel);
ValueAxis valueAxis = new NumberAxis3D(valueAxisLabel);
LineRenderer3D renderer = new LineRenderer3D();
renderer.setDefaultToolTipGenerator(
new StandardCategoryToolTipGenerator());
CategoryPlot plot = new CategoryPlot(dataset, categoryAxis, valueAxis,
renderer);
JFreeChart chart = new JFreeChart(title, plot);
currentTheme.apply(chart);
return chart;
}
/**
* Creates a Gantt chart using the supplied attributes plus default values
* where required. The chart object returned by this method uses a
* {@link CategoryPlot} instance as the plot, with a {@link CategoryAxis}
* for the domain axis, a {@link DateAxis} as the range axis, and a
* {@link GanttRenderer} as the renderer.
*
* @param title the chart title (<code>null</code> permitted).
* @param categoryAxisLabel the label for the category axis
* (<code>null</code> permitted).
* @param dateAxisLabel the label for the date axis
* (<code>null</code> permitted).
* @param dataset the dataset for the chart (<code>null</code> permitted).
*
* @return A Gantt chart.
*/
public static JFreeChart createGanttChart(String title,
String categoryAxisLabel, String dateAxisLabel,
IntervalCategoryDataset dataset) {
CategoryAxis categoryAxis = new CategoryAxis(categoryAxisLabel);
DateAxis dateAxis = new DateAxis(dateAxisLabel);
CategoryItemRenderer renderer = new GanttRenderer();
renderer.setDefaultToolTipGenerator(
new IntervalCategoryToolTipGenerator(
"{3} - {4}", DateFormat.getDateInstance()));
CategoryPlot plot = new CategoryPlot(dataset, categoryAxis, dateAxis,
renderer);
plot.setOrientation(PlotOrientation.HORIZONTAL);
JFreeChart chart = new JFreeChart(title, plot);
currentTheme.apply(chart);
return chart;
}
/**
* Creates a waterfall chart. The chart object returned by this method
* uses a {@link CategoryPlot} instance as the plot, with a
* {@link CategoryAxis} for the domain axis, a {@link NumberAxis} as the
* range axis, and a {@link WaterfallBarRenderer} as the renderer.
*
* @param title the chart title (<code>null</code> permitted).
* @param categoryAxisLabel the label for the category axis
* (<code>null</code> permitted).
* @param valueAxisLabel the label for the value axis (<code>null</code>
* permitted).
* @param dataset the dataset for the chart (<code>null</code> permitted).
*
* @return A waterfall chart.
*/
public static JFreeChart createWaterfallChart(String title,
String categoryAxisLabel, String valueAxisLabel,
CategoryDataset dataset) {
CategoryAxis categoryAxis = new CategoryAxis(categoryAxisLabel);
categoryAxis.setCategoryMargin(0.0);
ValueAxis valueAxis = new NumberAxis(valueAxisLabel);
WaterfallBarRenderer renderer = new WaterfallBarRenderer();
// FIXME create a new method for the horizontal version
// if (orientation == PlotOrientation.HORIZONTAL) {
// ItemLabelPosition position = new ItemLabelPosition(
// ItemLabelAnchor.CENTER, TextAnchor.CENTER,
// TextAnchor.CENTER, Math.PI / 2.0);
// renderer.setBasePositiveItemLabelPosition(position);
// renderer.setBaseNegativeItemLabelPosition(position);
// }
ItemLabelPosition position = new ItemLabelPosition(
ItemLabelAnchor.CENTER, TextAnchor.CENTER,
TextAnchor.CENTER, 0.0);
renderer.setDefaultPositiveItemLabelPosition(position);
renderer.setDefaultNegativeItemLabelPosition(position);
StandardCategoryToolTipGenerator generator
= new StandardCategoryToolTipGenerator();
renderer.setDefaultToolTipGenerator(generator);
CategoryPlot plot = new CategoryPlot(dataset, categoryAxis, valueAxis,
renderer);
plot.clearRangeMarkers();
Marker baseline = new ValueMarker(0.0);
baseline.setPaint(Color.BLACK);
plot.addRangeMarker(baseline, Layer.FOREGROUND);
JFreeChart chart = new JFreeChart(title, plot);
currentTheme.apply(chart);
return chart;
}
/**
* Creates a polar plot for the specified dataset (x-values interpreted as
* angles in degrees). The chart object returned by this method uses a
* {@link PolarPlot} instance as the plot, with a {@link NumberAxis} for
* the radial axis.
*
* @param title the chart title (<code>null</code> permitted).
* @param dataset the dataset (<code>null</code> permitted).
*
* @return A chart.
*/
public static JFreeChart createPolarChart(String title, XYDataset dataset) {
PolarPlot plot = new PolarPlot();
plot.setDataset(dataset);
NumberAxis rangeAxis = new NumberAxis();
rangeAxis.setAxisLineVisible(false);
rangeAxis.setTickMarksVisible(false);
rangeAxis.setTickLabelInsets(new RectangleInsets(0.0, 0.0, 0.0, 0.0));
plot.setAxis(rangeAxis);
plot.setRenderer(new DefaultPolarItemRenderer());
JFreeChart chart = new JFreeChart(title, plot);
currentTheme.apply(chart);
return chart;
}
/**
* Creates a scatter plot with default settings. The chart object
* returned by this method uses an {@link XYPlot} instance as the plot,
* with a {@link NumberAxis} for the domain axis, a {@link NumberAxis}
* as the range axis, and an {@link XYLineAndShapeRenderer} as the
* renderer.
*
* @param title the chart title (<code>null</code> permitted).
* @param xAxisLabel a label for the X-axis (<code>null</code> permitted).
* @param yAxisLabel a label for the Y-axis (<code>null</code> permitted).
* @param dataset the dataset for the chart (<code>null</code> permitted).
*
* @return A scatter plot.
*/
public static JFreeChart createScatterPlot(String title, String xAxisLabel,
String yAxisLabel, XYDataset dataset) {
NumberAxis xAxis = new NumberAxis(xAxisLabel);
xAxis.setAutoRangeIncludesZero(false);
NumberAxis yAxis = new NumberAxis(yAxisLabel);
yAxis.setAutoRangeIncludesZero(false);
XYPlot plot = new XYPlot(dataset, xAxis, yAxis, null);
XYItemRenderer renderer = new XYLineAndShapeRenderer(false, true);
XYToolTipGenerator toolTipGenerator = new StandardXYToolTipGenerator();
renderer.setDefaultToolTipGenerator(toolTipGenerator);
plot.setRenderer(renderer);
JFreeChart chart = new JFreeChart(title, plot);
currentTheme.apply(chart);
return chart;
}
/**
* Creates and returns a default instance of an XY bar chart.
* <P>
* The chart object returned by this method uses an {@link XYPlot} instance
* as the plot, with a {@link DateAxis} for the domain axis, a
* {@link NumberAxis} as the range axis, and a {@link XYBarRenderer} as the
* renderer.
*
* @param title the chart title (<code>null</code> permitted).
* @param xAxisLabel a label for the X-axis (<code>null</code> permitted).
* @param dateAxis make the domain axis display dates?
* @param yAxisLabel a label for the Y-axis (<code>null</code> permitted).
* @param dataset the dataset for the chart (<code>null</code> permitted).
*
* @return An XY bar chart.
*/
public static JFreeChart createXYBarChart(String title, String xAxisLabel,
boolean dateAxis, String yAxisLabel, IntervalXYDataset dataset) {
ValueAxis domainAxis;
if (dateAxis) {
domainAxis = new DateAxis(xAxisLabel);
}
else {
NumberAxis axis = new NumberAxis(xAxisLabel);
axis.setAutoRangeIncludesZero(false);
domainAxis = axis;
}
ValueAxis valueAxis = new NumberAxis(yAxisLabel);
XYBarRenderer renderer = new XYBarRenderer();
XYToolTipGenerator tt;
if (dateAxis) {
tt = StandardXYToolTipGenerator.getTimeSeriesInstance();
}
else {
tt = new StandardXYToolTipGenerator();
}
renderer.setDefaultToolTipGenerator(tt);
XYPlot plot = new XYPlot(dataset, domainAxis, valueAxis, renderer);
JFreeChart chart = new JFreeChart(title, plot);
currentTheme.apply(chart);
return chart;
}
/**
* Creates an area chart using an {@link XYDataset}.
* <P>
* The chart object returned by this method uses an {@link XYPlot} instance
* as the plot, with a {@link NumberAxis} for the domain axis, a
* {@link NumberAxis} as the range axis, and a {@link XYAreaRenderer} as
* the renderer.
*
* @param title the chart title (<code>null</code> permitted).
* @param xAxisLabel a label for the X-axis (<code>null</code> permitted).
* @param yAxisLabel a label for the Y-axis (<code>null</code> permitted).
* @param dataset the dataset for the chart (<code>null</code> permitted).
*
* @return An XY area chart.
*/
public static JFreeChart createXYAreaChart(String title,String xAxisLabel,
String yAxisLabel, XYDataset dataset) {
NumberAxis xAxis = new NumberAxis(xAxisLabel);
xAxis.setAutoRangeIncludesZero(false);
NumberAxis yAxis = new NumberAxis(yAxisLabel);
XYPlot plot = new XYPlot(dataset, xAxis, yAxis, null);
plot.setForegroundAlpha(0.5f);
XYToolTipGenerator tipGenerator = new StandardXYToolTipGenerator();
plot.setRenderer(new XYAreaRenderer(XYAreaRenderer.AREA, tipGenerator,
null));
JFreeChart chart = new JFreeChart(title, plot);
currentTheme.apply(chart);
return chart;
}
/**
* Creates a stacked XY area plot. The chart object returned by this
* method uses an {@link XYPlot} instance as the plot, with a
* {@link NumberAxis} for the domain axis, a {@link NumberAxis} as the
* range axis, and a {@link StackedXYAreaRenderer2} as the renderer.
*
* @param title the chart title (<code>null</code> permitted).
* @param xAxisLabel a label for the X-axis (<code>null</code> permitted).
* @param yAxisLabel a label for the Y-axis (<code>null</code> permitted).
* @param dataset the dataset for the chart (<code>null</code> permitted).
*
* @return A stacked XY area chart.
*/
public static JFreeChart createStackedXYAreaChart(String title,
String xAxisLabel, String yAxisLabel, TableXYDataset dataset) {
NumberAxis xAxis = new NumberAxis(xAxisLabel);
xAxis.setAutoRangeIncludesZero(false);
xAxis.setLowerMargin(0.0);
xAxis.setUpperMargin(0.0);
NumberAxis yAxis = new NumberAxis(yAxisLabel);
XYToolTipGenerator toolTipGenerator = new StandardXYToolTipGenerator();
StackedXYAreaRenderer2 renderer = new StackedXYAreaRenderer2(
toolTipGenerator, null);
renderer.setOutline(true);
XYPlot plot = new XYPlot(dataset, xAxis, yAxis, renderer);
plot.setRangeAxis(yAxis); // forces recalculation of the axis range
JFreeChart chart = new JFreeChart(title, plot);
currentTheme.apply(chart);
return chart;
}
/**
* Creates a line chart (based on an {@link XYDataset}) with default
* settings.
*
* @param title the chart title (<code>null</code> permitted).
* @param xAxisLabel a label for the X-axis (<code>null</code> permitted).
* @param yAxisLabel a label for the Y-axis (<code>null</code> permitted).
* @param dataset the dataset for the chart (<code>null</code> permitted).
*
* @return The chart.
*/
public static JFreeChart createXYLineChart(String title,
String xAxisLabel, String yAxisLabel, XYDataset dataset) {
NumberAxis xAxis = new NumberAxis(xAxisLabel);
xAxis.setAutoRangeIncludesZero(false);
NumberAxis yAxis = new NumberAxis(yAxisLabel);
XYItemRenderer renderer = new XYLineAndShapeRenderer(true, false);
XYPlot plot = new XYPlot(dataset, xAxis, yAxis, renderer);
renderer.setDefaultToolTipGenerator(new StandardXYToolTipGenerator());
JFreeChart chart = new JFreeChart(title, plot);
currentTheme.apply(chart);
return chart;
}
/**
* Creates a stepped XY plot with default settings.
*
* @param title the chart title (<code>null</code> permitted).
* @param xAxisLabel a label for the X-axis (<code>null</code> permitted).
* @param yAxisLabel a label for the Y-axis (<code>null</code> permitted).
* @param dataset the dataset for the chart (<code>null</code> permitted).
*
* @return A chart.
*/
public static JFreeChart createXYStepChart(String title, String xAxisLabel,
String yAxisLabel, XYDataset dataset) {
DateAxis xAxis = new DateAxis(xAxisLabel);
NumberAxis yAxis = new NumberAxis(yAxisLabel);
yAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
XYToolTipGenerator toolTipGenerator = new StandardXYToolTipGenerator();
XYItemRenderer renderer = new XYStepRenderer(toolTipGenerator, null);
XYPlot plot = new XYPlot(dataset, xAxis, yAxis, null);
plot.setRenderer(renderer);
plot.setDomainCrosshairVisible(false);
plot.setRangeCrosshairVisible(false);
JFreeChart chart = new JFreeChart(title, plot);
currentTheme.apply(chart);
return chart;
}
/**
* Creates a filled stepped XY plot with default settings.
*
* @param title the chart title (<code>null</code> permitted).
* @param xAxisLabel a label for the X-axis (<code>null</code> permitted).
* @param yAxisLabel a label for the Y-axis (<code>null</code> permitted).
* @param dataset the dataset for the chart (<code>null</code> permitted).
*
* @return A chart.
*/
public static JFreeChart createXYStepAreaChart(String title,
String xAxisLabel, String yAxisLabel, XYDataset dataset) {
NumberAxis xAxis = new NumberAxis(xAxisLabel);
xAxis.setAutoRangeIncludesZero(false);
NumberAxis yAxis = new NumberAxis(yAxisLabel);
XYToolTipGenerator toolTipGenerator = new StandardXYToolTipGenerator();
XYItemRenderer renderer = new XYStepAreaRenderer(
XYStepAreaRenderer.AREA_AND_SHAPES, toolTipGenerator,
null);
XYPlot plot = new XYPlot(dataset, xAxis, yAxis, null);
plot.setRenderer(renderer);
plot.setDomainCrosshairVisible(false);
plot.setRangeCrosshairVisible(false);
JFreeChart chart = new JFreeChart(title, plot);
currentTheme.apply(chart);
return chart;
}
/**
* Creates and returns a time series chart. A time series chart is an
* {@link XYPlot} with a {@link DateAxis} for the x-axis and a
* {@link NumberAxis} for the y-axis. The default renderer is an
* {@link XYLineAndShapeRenderer}.
* <P>
* A convenient dataset to use with this chart is a
* {@link org.jfree.data.time.TimeSeriesCollection}.
*
* @param title the chart title (<code>null</code> permitted).
* @param timeAxisLabel a label for the time axis (<code>null</code>
* permitted).
* @param valueAxisLabel a label for the value axis (<code>null</code>
* permitted).
* @param dataset the dataset for the chart (<code>null</code> permitted).
*
* @return A time series chart.
*/
public static JFreeChart createTimeSeriesChart(String title,
String timeAxisLabel,
String valueAxisLabel,
XYDataset dataset) {
ValueAxis timeAxis = new DateAxis(timeAxisLabel);
timeAxis.setLowerMargin(0.02); // reduce the default margins
timeAxis.setUpperMargin(0.02);
NumberAxis valueAxis = new NumberAxis(valueAxisLabel);
valueAxis.setAutoRangeIncludesZero(false); // override default
XYPlot plot = new XYPlot(dataset, timeAxis, valueAxis, null);
XYToolTipGenerator toolTipGenerator
= StandardXYToolTipGenerator.getTimeSeriesInstance();
XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer(true,
false);
renderer.setDefaultToolTipGenerator(toolTipGenerator);
plot.setRenderer(renderer);
JFreeChart chart = new JFreeChart(title, plot);
currentTheme.apply(chart);
return chart;
}
/**
* Creates and returns a default instance of a candlesticks chart.
*
* @param title the chart title (<code>null</code> permitted).
* @param timeAxisLabel a label for the time axis (<code>null</code>
* permitted).
* @param valueAxisLabel a label for the value axis (<code>null</code>
* permitted).
* @param dataset the dataset for the chart (<code>null</code> permitted).
*
* @return A candlestick chart.
*/
public static JFreeChart createCandlestickChart(String title,
String timeAxisLabel, String valueAxisLabel, OHLCDataset dataset) {
ValueAxis timeAxis = new DateAxis(timeAxisLabel);
NumberAxis valueAxis = new NumberAxis(valueAxisLabel);
XYPlot plot = new XYPlot(dataset, timeAxis, valueAxis, null);
plot.setRenderer(new CandlestickRenderer());
JFreeChart chart = new JFreeChart(title, plot);
currentTheme.apply(chart);
return chart;
}
/**
* Creates and returns a default instance of a high-low-open-close chart.
*
* @param title the chart title (<code>null</code> permitted).
* @param timeAxisLabel a label for the time axis (<code>null</code>
* permitted).
* @param valueAxisLabel a label for the value axis (<code>null</code>
* permitted).
* @param dataset the dataset for the chart (<code>null</code> permitted).
*
* @return A high-low-open-close chart.
*/
public static JFreeChart createHighLowChart(String title,
String timeAxisLabel, String valueAxisLabel, OHLCDataset dataset ) {
ValueAxis timeAxis = new DateAxis(timeAxisLabel);
NumberAxis valueAxis = new NumberAxis(valueAxisLabel);
HighLowRenderer renderer = new HighLowRenderer();
renderer.setDefaultToolTipGenerator(new HighLowItemLabelGenerator());
XYPlot plot = new XYPlot(dataset, timeAxis, valueAxis, renderer);
JFreeChart chart = new JFreeChart(title, plot);
currentTheme.apply(chart);
return chart;
}
/**
* Creates and returns a default instance of a high-low-open-close chart
* with a special timeline. This timeline can be a
* {@link org.jfree.chart.axis.SegmentedTimeline} such as the Monday
* through Friday timeline that will remove Saturdays and Sundays from
* the axis.
*
* @param title the chart title (<code>null</code> permitted).
* @param timeAxisLabel a label for the time axis (<code>null</code>
* permitted).
* @param valueAxisLabel a label for the value axis (<code>null</code>
* permitted).
* @param dataset the dataset for the chart (<code>null</code> permitted).
* @param timeline the timeline.
* @param legend a flag specifying whether or not a legend is required.
*
* @return A high-low-open-close chart.
*/
public static JFreeChart createHighLowChart(String title,
String timeAxisLabel, String valueAxisLabel, OHLCDataset dataset,
Timeline timeline, boolean legend) {
DateAxis timeAxis = new DateAxis(timeAxisLabel);
timeAxis.setTimeline(timeline);
NumberAxis valueAxis = new NumberAxis(valueAxisLabel);
HighLowRenderer renderer = new HighLowRenderer();
renderer.setDefaultToolTipGenerator(new HighLowItemLabelGenerator());
XYPlot plot = new XYPlot(dataset, timeAxis, valueAxis, renderer);
JFreeChart chart = new JFreeChart(title, plot);
currentTheme.apply(chart);
return chart;
}
/**
* Creates a bubble chart with default settings. The chart is composed of
* an {@link XYPlot}, with a {@link NumberAxis} for the domain axis,
* a {@link NumberAxis} for the range axis, and an {@link XYBubbleRenderer}
* to draw the data items.
*
* @param title the chart title (<code>null</code> permitted).
* @param xAxisLabel a label for the X-axis (<code>null</code> permitted).
* @param yAxisLabel a label for the Y-axis (<code>null</code> permitted).
* @param dataset the dataset for the chart (<code>null</code> permitted).
*
* @return A bubble chart.
*/
public static JFreeChart createBubbleChart(String title, String xAxisLabel,
String yAxisLabel, XYZDataset dataset) {
NumberAxis xAxis = new NumberAxis(xAxisLabel);
xAxis.setAutoRangeIncludesZero(false);
NumberAxis yAxis = new NumberAxis(yAxisLabel);
yAxis.setAutoRangeIncludesZero(false);
XYPlot plot = new XYPlot(dataset, xAxis, yAxis, null);
XYItemRenderer renderer = new XYBubbleRenderer(
XYBubbleRenderer.SCALE_ON_RANGE_AXIS);
renderer.setDefaultToolTipGenerator(new StandardXYZToolTipGenerator());
plot.setRenderer(renderer);
JFreeChart chart = new JFreeChart(title, plot);
currentTheme.apply(chart);
return chart;
}
/**
* Creates a histogram chart. This chart is constructed with an
* {@link XYPlot} using an {@link XYBarRenderer}. The domain and range
* axes are {@link NumberAxis} instances.
*
* @param title the chart title (<code>null</code> permitted).
* @param xAxisLabel the x axis label (<code>null</code> permitted).
* @param yAxisLabel the y axis label (<code>null</code> permitted).
* @param dataset the dataset (<code>null</code> permitted).
*
* @return The chart.
*/
public static JFreeChart createHistogram(String title,
String xAxisLabel, String yAxisLabel, IntervalXYDataset dataset) {
NumberAxis xAxis = new NumberAxis(xAxisLabel);
xAxis.setAutoRangeIncludesZero(false);
ValueAxis yAxis = new NumberAxis(yAxisLabel);
XYItemRenderer renderer = new XYBarRenderer();
renderer.setDefaultToolTipGenerator(new StandardXYToolTipGenerator());
XYPlot plot = new XYPlot(dataset, xAxis, yAxis, renderer);
plot.setDomainZeroBaselineVisible(true);
plot.setRangeZeroBaselineVisible(true);
JFreeChart chart = new JFreeChart(title, plot);
currentTheme.apply(chart);
return chart;
}
/**
* Creates and returns a default instance of a box and whisker chart
* based on data from a {@link BoxAndWhiskerCategoryDataset}.
*
* @param title the chart title (<code>null</code> permitted).
* @param categoryAxisLabel a label for the category axis
* (<code>null</code> permitted).
* @param valueAxisLabel a label for the value axis (<code>null</code>
* permitted).
* @param dataset the dataset for the chart (<code>null</code> permitted).
*
* @return A box and whisker chart.
*
* @since 1.0.4
*/
public static JFreeChart createBoxAndWhiskerChart(String title,
String categoryAxisLabel, String valueAxisLabel,
BoxAndWhiskerCategoryDataset dataset) {
CategoryAxis categoryAxis = new CategoryAxis(categoryAxisLabel);
NumberAxis valueAxis = new NumberAxis(valueAxisLabel);
valueAxis.setAutoRangeIncludesZero(false);
BoxAndWhiskerRenderer renderer = new BoxAndWhiskerRenderer();
renderer.setDefaultToolTipGenerator(new BoxAndWhiskerToolTipGenerator());
CategoryPlot plot = new CategoryPlot(dataset, categoryAxis, valueAxis,
renderer);
JFreeChart chart = new JFreeChart(title, plot);
currentTheme.apply(chart);
return chart;
}
/**
* Creates and returns a default instance of a box and whisker chart.
*
* @param title the chart title (<code>null</code> permitted).
* @param timeAxisLabel a label for the time axis (<code>null</code>
* permitted).
* @param valueAxisLabel a label for the value axis (<code>null</code>
* permitted).
* @param dataset the dataset for the chart (<code>null</code> permitted).
*
* @return A box and whisker chart.
*/
public static JFreeChart createBoxAndWhiskerChart(String title,
String timeAxisLabel, String valueAxisLabel,
BoxAndWhiskerXYDataset dataset) {
ValueAxis timeAxis = new DateAxis(timeAxisLabel);
NumberAxis valueAxis = new NumberAxis(valueAxisLabel);
valueAxis.setAutoRangeIncludesZero(false);
XYBoxAndWhiskerRenderer renderer = new XYBoxAndWhiskerRenderer(10.0);
XYPlot plot = new XYPlot(dataset, timeAxis, valueAxis, renderer);
JFreeChart chart = new JFreeChart(title, plot);
currentTheme.apply(chart);
return chart;
}
/**
* Creates a wind plot with default settings.
*
* @param title the chart title (<code>null</code> permitted).
* @param xAxisLabel a label for the x-axis (<code>null</code> permitted).
* @param yAxisLabel a label for the y-axis (<code>null</code> permitted).
* @param dataset the dataset for the chart (<code>null</code> permitted).
*
* @return A wind plot.
*/
public static JFreeChart createWindPlot(String title,
String xAxisLabel, String yAxisLabel, WindDataset dataset) {
ValueAxis xAxis = new DateAxis(xAxisLabel);
ValueAxis yAxis = new NumberAxis(yAxisLabel);
yAxis.setRange(-12.0, 12.0);
WindItemRenderer renderer = new WindItemRenderer();
renderer.setDefaultToolTipGenerator(new StandardXYToolTipGenerator());
XYPlot plot = new XYPlot(dataset, xAxis, yAxis, renderer);
JFreeChart chart = new JFreeChart(title, plot);
currentTheme.apply(chart);
return chart;
}
/**
* Creates a wafer map chart.
*
* @param title the chart title (<code>null</code> permitted).
* @param dataset the dataset (<code>null</code> permitted).
*
* @return A wafer map chart.
*/
public static JFreeChart createWaferMapChart(String title,
WaferMapDataset dataset) {
WaferMapPlot plot = new WaferMapPlot(dataset);
WaferMapRenderer renderer = new WaferMapRenderer();
plot.setRenderer(renderer);
JFreeChart chart = new JFreeChart(title, plot);
currentTheme.apply(chart);
return chart;
}
}
| 73,443 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
ChartFrame.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/ChartFrame.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.]
*
* ---------------
* ChartFrame.java
* ---------------
* (C) Copyright 2001-2008, by Object Refinery Limited and Contributors.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 22-Nov-2001 : Version 1 (DG);
* 08-Jan-2001 : Added chartPanel attribute (DG);
* 24-May-2002 : Renamed JFreeChartFrame --> ChartFrame (DG);
*
*/
package org.jfree.chart;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.WindowConstants;
/**
* A frame for displaying a chart.
*/
public class ChartFrame extends JFrame {
/** The chart panel. */
private ChartPanel chartPanel;
/**
* Constructs a frame for a chart.
*
* @param title the frame title.
* @param chart the chart.
*/
public ChartFrame(String title, JFreeChart chart) {
this(title, chart, false);
}
/**
* Constructs a frame for a chart.
*
* @param title the frame title.
* @param chart the chart.
* @param scrollPane if <code>true</code>, put the Chart(Panel) into a
* JScrollPane.
*/
public ChartFrame(String title, JFreeChart chart, boolean scrollPane) {
super(title);
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
this.chartPanel = new ChartPanel(chart);
if (scrollPane) {
setContentPane(new JScrollPane(this.chartPanel));
}
else {
setContentPane(this.chartPanel);
}
}
/**
* Returns the chart panel for the frame.
*
* @return The chart panel.
*/
public ChartPanel getChartPanel() {
return this.chartPanel;
}
}
| 2,945 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
JFreeChart.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/JFreeChart.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.]
*
* ---------------
* JFreeChart.java
* ---------------
* (C) Copyright 2000-2013, by Object Refinery Limited and Contributors.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): Andrzej Porebski;
* David Li;
* Wolfgang Irler;
* Christian W. Zuckschwerdt;
* Klaus Rheinwald;
* Nicolas Brodu;
* Peter Kolb (patch 2603321);
*
* NOTE: The above list of contributors lists only the people that have
* contributed to this source file (JFreeChart.java) - for a list of ALL
* contributors to the project, please see the README.txt file.
*
* Changes (from 20-Jun-2001)
* --------------------------
* 20-Jun-2001 : Modifications submitted by Andrzej Porebski for legend
* placement;
* 21-Jun-2001 : Removed JFreeChart parameter from Plot constructors (DG);
* 22-Jun-2001 : Multiple titles added (original code by David Berry, with
* reworkings by DG);
* 18-Sep-2001 : Updated header (DG);
* 15-Oct-2001 : Moved data source classes into new package
* com.jrefinery.data.* (DG);
* 18-Oct-2001 : New factory method for creating VerticalXYBarChart (DG);
* 19-Oct-2001 : Moved series paint and stroke methods to the Plot class (DG);
* Moved static chart creation methods to new ChartFactory
* class (DG);
* 22-Oct-2001 : Renamed DataSource.java --> Dataset.java etc. (DG);
* Fixed bug where chart isn't registered with the dataset (DG);
* 07-Nov-2001 : Fixed bug where null title in constructor causes
* exception (DG);
* Tidied up event notification code (DG);
* 17-Nov-2001 : Added getLegendItemCount() method (DG);
* 21-Nov-2001 : Set clipping in draw method to ensure that nothing gets drawn
* outside the chart area (DG);
* 11-Dec-2001 : Added the createBufferedImage() method, taken from the
* JFreeChartServletDemo class (DG);
* 13-Dec-2001 : Added tooltips (DG);
* 16-Jan-2002 : Added handleClick() method (DG);
* 22-Jan-2002 : Fixed bug correlating legend labels with pie data (DG);
* 05-Feb-2002 : Removed redundant tooltips code (DG);
* 19-Feb-2002 : Added accessor methods for the backgroundImage and
* backgroundImageAlpha attributes (DG);
* 21-Feb-2002 : Added static fields for INFO, COPYRIGHT, LICENCE, CONTRIBUTORS
* and LIBRARIES. These can be used to display information about
* JFreeChart (DG);
* 06-Mar-2002 : Moved constants to JFreeChartConstants interface (DG);
* 18-Apr-2002 : PieDataset is no longer sorted (oldman);
* 23-Apr-2002 : Moved dataset to the Plot class (DG);
* 13-Jun-2002 : Added an extra draw() method (DG);
* 25-Jun-2002 : Implemented the Drawable interface and removed redundant
* imports (DG);
* 26-Jun-2002 : Added another createBufferedImage() method (DG);
* 18-Sep-2002 : Fixed issues reported by Checkstyle (DG);
* 23-Sep-2002 : Added new contributor (DG);
* 28-Oct-2002 : Created main title and subtitle list to replace existing title
* list (DG);
* 08-Jan-2003 : Added contributor (DG);
* 17-Jan-2003 : Added new constructor (DG);
* 22-Jan-2003 : Added ChartColor class by Cameron Riley, and background image
* alignment code by Christian W. Zuckschwerdt (DG);
* 11-Feb-2003 : Added flag to allow suppression of chart change events, based
* on a suggestion by Klaus Rheinwald (DG);
* 04-Mar-2003 : Added small fix for suppressed chart change events (see bug id
* 690865) (DG);
* 10-Mar-2003 : Added Benoit Xhenseval to contributors (DG);
* 26-Mar-2003 : Implemented Serializable (DG);
* 15-Jul-2003 : Added an optional border for the chart (DG);
* 11-Sep-2003 : Took care of listeners while cloning (NB);
* 16-Sep-2003 : Changed ChartRenderingInfo --> PlotRenderingInfo (DG);
* 22-Sep-2003 : Added nullpointer checks.
* 25-Sep-2003 : Added nullpointer checks too (NB).
* 03-Dec-2003 : Legends are now registered by this class instead of using the
* old constructor way (TM);
* 03-Dec-2003 : Added anchorPoint to draw() method (DG);
* 08-Jan-2004 : Reworked title code, introducing line wrapping (DG);
* 09-Feb-2004 : Created additional createBufferedImage() method (DG);
* 05-Apr-2004 : Added new createBufferedImage() method (DG);
* 27-May-2004 : Moved constants from JFreeChartConstants.java back to this
* class (DG);
* 25-Nov-2004 : Updates for changes to Title class (DG);
* 06-Jan-2005 : Change lookup for default background color (DG);
* 31-Jan-2005 : Added Don Elliott to contributors (DG);
* 02-Feb-2005 : Added clearSubtitles() method (DG);
* 03-Feb-2005 : Added Mofeed Shahin to contributors (DG);
* 08-Feb-2005 : Updated for RectangleConstraint changes (DG);
* 28-Mar-2005 : Renamed Legend --> OldLegend (DG);
* 12-Apr-2005 : Added methods to access legend(s) in subtitle list (DG);
* 13-Apr-2005 : Added removeLegend() and removeSubtitle() methods (DG);
* 20-Apr-2005 : Modified to collect chart entities from titles and
* subtitles (DG);
* 26-Apr-2005 : Removed LOGGER (DG);
* 06-Jun-2005 : Added addLegend() method and padding attribute, fixed equals()
* method (DG);
* 24-Nov-2005 : Removed OldLegend and related code - don't want to support
* this in 1.0.0 final (DG);
* ------------- JFREECHART 1.0.x ---------------------------------------------
* 27-Jan-2006 : Updated version number (DG);
* 07-Dec-2006 : Added some missing credits (DG);
* 17-Jan-2007 : Added Darren Jung to contributor list (DG);
* 05-Mar-2007 : Added Sergei Ivanov to the contributor list (DG);
* 16-Mar-2007 : Modified initial legend border (DG);
* 22-Mar-2007 : New methods for text anti-aliasing (DG);
* 16-May-2007 : Fixed argument check in getSubtitle(), copy list in
* get/setSubtitles(), and added new addSubtitle(int, Title)
* method (DG);
* 05-Jun-2007 : Add change listener to default legend (DG);
* 04-Dec-2007 : In createBufferedImage() methods, make the default image type
* BufferedImage.TYPE_INT_ARGB (thanks to Klaus Rheinwald) (DG);
* 05-Dec-2007 : Fixed bug 1749124 (not registering as listener with
* TextTitle) (DG);
* 23-Apr-2008 : Added new contributor (Diego Pierangeli) (DG);
* 16-May-2008 : Added new contributor (Michael Siemer) (DG);
* 19-Sep-2008 : Check for title visibility (DG);
* 18-Dec-2008 : Use ResourceBundleWrapper - see patch 1607918 by
* Jess Thrysoee (DG);
* 19-Mar-2009 : Added entity support - see patch 2603321 by Peter Kolb (DG);
* 19-May-2009 : Fixed FindBugs warnings, patch by Michal Wozniak (DG);
* 29-Jun-2009 : Check visibility flag in main title (DG);
*
*/
package org.jfree.chart;
import java.awt.AlphaComposite;
import java.awt.BasicStroke;
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.RenderingHints;
import java.awt.Shape;
import java.awt.Stroke;
import java.awt.geom.AffineTransform;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.swing.UIManager;
import javax.swing.event.EventListenerList;
import org.jfree.chart.block.BlockParams;
import org.jfree.chart.block.EntityBlockResult;
import org.jfree.chart.block.LengthConstraintType;
import org.jfree.chart.block.LineBorder;
import org.jfree.chart.block.RectangleConstraint;
import org.jfree.chart.ui.Align;
import org.jfree.chart.ui.Drawable;
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.entity.EntityCollection;
import org.jfree.chart.entity.JFreeChartEntity;
import org.jfree.chart.event.ChartChangeEvent;
import org.jfree.chart.event.ChartChangeListener;
import org.jfree.chart.event.ChartProgressEvent;
import org.jfree.chart.event.ChartProgressListener;
import org.jfree.chart.event.PlotChangeEvent;
import org.jfree.chart.event.PlotChangeListener;
import org.jfree.chart.event.TitleChangeEvent;
import org.jfree.chart.event.TitleChangeListener;
import org.jfree.chart.plot.Plot;
import org.jfree.chart.plot.PlotRenderingInfo;
import org.jfree.chart.title.LegendTitle;
import org.jfree.chart.title.TextTitle;
import org.jfree.chart.title.Title;
import org.jfree.chart.util.ParamChecks;
import org.jfree.chart.util.SerialUtilities;
import org.jfree.data.Range;
/**
* A chart class implemented using the Java 2D APIs. The current version
* supports bar charts, line charts, pie charts and xy plots (including time
* series data).
* <P>
* JFreeChart coordinates several objects to achieve its aim of being able to
* draw a chart on a Java 2D graphics device: a list of {@link Title} objects
* (which often includes the chart's legend), a {@link Plot} and a
* {@link org.jfree.data.general.Dataset} (the plot in turn manages a
* domain axis and a range axis).
* <P>
* You should use a {@link ChartPanel} to display a chart in a GUI.
* <P>
* The {@link ChartFactory} class contains static methods for creating
* 'ready-made' charts.
*
* @see ChartPanel
* @see ChartFactory
* @see Title
* @see Plot
*/
public class JFreeChart implements Drawable, TitleChangeListener,
PlotChangeListener, Serializable, Cloneable {
/** For serialization. */
private static final long serialVersionUID = -3470703747817429120L;
/** The default font for titles. */
public static final Font DEFAULT_TITLE_FONT
= new Font("SansSerif", Font.BOLD, 18);
/** The default background color. */
public static final Paint DEFAULT_BACKGROUND_PAINT
= UIManager.getColor("Panel.background");
/** The default background image. */
public static final Image DEFAULT_BACKGROUND_IMAGE = null;
/** The default background image alignment. */
public static final int DEFAULT_BACKGROUND_IMAGE_ALIGNMENT = Align.FIT;
/** The default background image alpha. */
public static final float DEFAULT_BACKGROUND_IMAGE_ALPHA = 0.5f;
/**
* The key for a rendering hint that can suppress the generation of a
* shadow effect when drawing the chart. The hint value must be a
* Boolean.
*
* @since 1.0.16
*/
public static final RenderingHints.Key KEY_SUPPRESS_SHADOW_GENERATION
= new RenderingHints.Key(0) {
@Override
public boolean isCompatibleValue(Object val) {
return val instanceof Boolean;
}
};
/**
* Rendering hints that will be used for chart drawing. This should never
* be <code>null</code>.
*/
private transient RenderingHints renderingHints;
/** A flag that controls whether or not the chart border is drawn. */
private boolean borderVisible;
/** The stroke used to draw the chart border (if visible). */
private transient Stroke borderStroke;
/** The paint used to draw the chart border (if visible). */
private transient Paint borderPaint;
/** The padding between the chart border and the chart drawing area. */
private RectangleInsets padding;
/** The chart title (optional). */
private TextTitle title;
/**
* The chart subtitles (zero, one or many). This field should never be
* <code>null</code>.
*/
private List<Title> subtitles;
/** Draws the visual representation of the data. */
private Plot plot;
/** Paint used to draw the background of the chart. */
private transient Paint backgroundPaint;
/** An optional background image for the chart. */
private transient Image backgroundImage; // todo: not serialized yet
/** The alignment for the background image. */
private int backgroundImageAlignment = Align.FIT;
/** The alpha transparency for the background image. */
private float backgroundImageAlpha = 0.5f;
/** Storage for registered change listeners. */
private transient EventListenerList changeListeners;
/** Storage for registered progress listeners. */
private transient EventListenerList progressListeners;
/**
* A flag that can be used to enable/disable notification of chart change
* events.
*/
private boolean notify;
/**
* Creates a new chart based on the supplied plot. The chart will have
* a legend added automatically, but no title (although you can easily add
* one later).
* <br><br>
* Note that the {@link ChartFactory} class contains a range
* of static methods that will return ready-made charts, and often this
* is a more convenient way to create charts than using this constructor.
*
* @param plot the plot (<code>null</code> not permitted).
*/
public JFreeChart(Plot plot) {
this(null, null, plot, true);
}
/**
* Creates a new chart with the given title and plot. A default font
* ({@link #DEFAULT_TITLE_FONT}) is used for the title, and the chart will
* have a legend added automatically.
* <br><br>
* Note that the {@link ChartFactory} class contains a range
* of static methods that will return ready-made charts, and often this
* is a more convenient way to create charts than using this constructor.
*
* @param title the chart title (<code>null</code> permitted).
* @param plot the plot (<code>null</code> not permitted).
*/
public JFreeChart(String title, Plot plot) {
this(title, JFreeChart.DEFAULT_TITLE_FONT, plot, true);
}
/**
* Creates a new chart with the given title and plot. The
* <code>createLegend</code> argument specifies whether or not a legend
* should be added to the chart.
* <br><br>
* Note that the {@link ChartFactory} class contains a range
* of static methods that will return ready-made charts, and often this
* is a more convenient way to create charts than using this constructor.
*
* @param title the chart title (<code>null</code> permitted).
* @param titleFont the font for displaying the chart title
* (<code>null</code> permitted).
* @param plot controller of the visual representation of the data
* (<code>null</code> not permitted).
* @param createLegend a flag indicating whether or not a legend should
* be created for the chart.
*/
public JFreeChart(String title, Font titleFont, Plot plot,
boolean createLegend) {
ParamChecks.nullNotPermitted(plot, "plot");
// create storage for listeners...
this.progressListeners = new EventListenerList();
this.changeListeners = new EventListenerList();
this.notify = true; // default is to notify listeners when the
// chart changes
this.renderingHints = new RenderingHints(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
this.borderVisible = false;
this.borderStroke = new BasicStroke(1.0f);
this.borderPaint = Color.BLACK;
this.padding = RectangleInsets.ZERO_INSETS;
this.plot = plot;
plot.addChangeListener(this);
this.subtitles = new ArrayList<Title>();
// create a legend, if requested...
if (createLegend) {
LegendTitle legend = new LegendTitle(this.plot);
legend.setMargin(new RectangleInsets(1.0, 1.0, 1.0, 1.0));
legend.setFrame(new LineBorder());
legend.setBackgroundPaint(Color.WHITE);
legend.setPosition(RectangleEdge.BOTTOM);
this.subtitles.add(legend);
legend.addChangeListener(this);
}
// add the chart title, if one has been specified...
if (title != null) {
if (titleFont == null) {
titleFont = DEFAULT_TITLE_FONT;
}
this.title = new TextTitle(title, titleFont);
this.title.addChangeListener(this);
}
this.backgroundPaint = DEFAULT_BACKGROUND_PAINT;
this.backgroundImage = DEFAULT_BACKGROUND_IMAGE;
this.backgroundImageAlignment = DEFAULT_BACKGROUND_IMAGE_ALIGNMENT;
this.backgroundImageAlpha = DEFAULT_BACKGROUND_IMAGE_ALPHA;
}
/**
* Returns the collection of rendering hints for the chart.
*
* @return The rendering hints for the chart (never <code>null</code>).
*
* @see #setRenderingHints(RenderingHints)
*/
public RenderingHints getRenderingHints() {
return this.renderingHints;
}
/**
* Sets the rendering hints for the chart. These will be added (using the
* Graphics2D.addRenderingHints() method) near the start of the
* JFreeChart.draw() method.
*
* @param hints the rendering hints (<code>null</code> not permitted).
*
* @see #getRenderingHints()
*/
public void setRenderingHints(RenderingHints hints) {
ParamChecks.nullNotPermitted(hints, "hints");
this.renderingHints = hints;
fireChartChanged();
}
/**
* Returns a flag that controls whether or not a border is drawn around the
* outside of the chart.
*
* @return A boolean.
*
* @see #setBorderVisible(boolean)
*/
public boolean isBorderVisible() {
return this.borderVisible;
}
/**
* Sets a flag that controls whether or not a border is drawn around the
* outside of the chart.
*
* @param visible the flag.
*
* @see #isBorderVisible()
*/
public void setBorderVisible(boolean visible) {
this.borderVisible = visible;
fireChartChanged();
}
/**
* Returns the stroke used to draw the chart border (if visible).
*
* @return The border stroke.
*
* @see #setBorderStroke(Stroke)
*/
public Stroke getBorderStroke() {
return this.borderStroke;
}
/**
* Sets the stroke used to draw the chart border (if visible).
*
* @param stroke the stroke.
*
* @see #getBorderStroke()
*/
public void setBorderStroke(Stroke stroke) {
this.borderStroke = stroke;
fireChartChanged();
}
/**
* Returns the paint used to draw the chart border (if visible).
*
* @return The border paint.
*
* @see #setBorderPaint(Paint)
*/
public Paint getBorderPaint() {
return this.borderPaint;
}
/**
* Sets the paint used to draw the chart border (if visible).
*
* @param paint the paint.
*
* @see #getBorderPaint()
*/
public void setBorderPaint(Paint paint) {
this.borderPaint = paint;
fireChartChanged();
}
/**
* Returns the padding between the chart border and the chart drawing area.
*
* @return The padding (never <code>null</code>).
*
* @see #setPadding(RectangleInsets)
*/
public RectangleInsets getPadding() {
return this.padding;
}
/**
* Sets the padding between the chart border and the chart drawing area,
* and sends a {@link ChartChangeEvent} to all registered listeners.
*
* @param padding the padding (<code>null</code> not permitted).
*
* @see #getPadding()
*/
public void setPadding(RectangleInsets padding) {
ParamChecks.nullNotPermitted(padding, "padding");
this.padding = padding;
notifyListeners(new ChartChangeEvent(this));
}
/**
* Returns the main chart title. Very often a chart will have just one
* title, so we make this case simple by providing accessor methods for
* the main title. However, multiple titles are supported - see the
* {@link #addSubtitle(Title)} method.
*
* @return The chart title (possibly <code>null</code>).
*
* @see #setTitle(TextTitle)
*/
public TextTitle getTitle() {
return this.title;
}
/**
* Sets the main title for the chart and sends a {@link ChartChangeEvent}
* to all registered listeners. If you do not want a title for the
* chart, set it to <code>null</code>. If you want more than one title on
* a chart, use the {@link #addSubtitle(Title)} method.
*
* @param title the title (<code>null</code> permitted).
*
* @see #getTitle()
*/
public void setTitle(TextTitle title) {
if (this.title != null) {
this.title.removeChangeListener(this);
}
this.title = title;
if (title != null) {
title.addChangeListener(this);
}
fireChartChanged();
}
/**
* Sets the chart title and sends a {@link ChartChangeEvent} to all
* registered listeners. This is a convenience method that ends up calling
* the {@link #setTitle(TextTitle)} method. If there is an existing title,
* its text is updated, otherwise a new title using the default font is
* added to the chart. If <code>text</code> is <code>null</code> the chart
* title is set to <code>null</code>.
*
* @param text the title text (<code>null</code> permitted).
*
* @see #getTitle()
*/
public void setTitle(String text) {
if (text != null) {
if (this.title == null) {
setTitle(new TextTitle(text, JFreeChart.DEFAULT_TITLE_FONT));
}
else {
this.title.setText(text);
}
}
else {
setTitle((TextTitle) null);
}
}
/**
* Adds a legend to the plot and sends a {@link ChartChangeEvent} to all
* registered listeners.
*
* @param legend the legend (<code>null</code> not permitted).
*
* @see #removeLegend()
*/
public void addLegend(LegendTitle legend) {
addSubtitle(legend);
}
/**
* Returns the legend for the chart, if there is one. Note that a chart
* can have more than one legend - this method returns the first.
*
* @return The legend (possibly <code>null</code>).
*
* @see #getLegend(int)
*/
public LegendTitle getLegend() {
return getLegend(0);
}
/**
* Returns the nth legend for a chart, or <code>null</code>.
*
* @param index the legend index (zero-based).
*
* @return The legend (possibly <code>null</code>).
*
* @see #addLegend(LegendTitle)
*/
public LegendTitle getLegend(int index) {
int seen = 0;
for (Title subtitle : this.subtitles) {
if (subtitle instanceof LegendTitle) {
if (seen == index) {
return (LegendTitle) subtitle;
} else {
seen++;
}
}
}
return null;
}
/**
* Removes the first legend in the chart and sends a
* {@link ChartChangeEvent} to all registered listeners.
*
* @see #getLegend()
*/
public void removeLegend() {
removeSubtitle(getLegend());
}
/**
* Returns the list of subtitles for the chart.
*
* @return The subtitle list (possibly empty, but never <code>null</code>).
*
* @see #setSubtitles(List)
*/
public List<Title> getSubtitles() {
return new ArrayList<Title>(this.subtitles);
}
/**
* Sets the title list for the chart (completely replaces any existing
* titles) and sends a {@link ChartChangeEvent} to all registered
* listeners.
*
* @param subtitles the new list of subtitles (<code>null</code> not
* permitted).
*
* @see #getSubtitles()
*/
public void setSubtitles(List<? extends Title> subtitles) {
if (subtitles == null) {
throw new NullPointerException("Null 'subtitles' argument.");
}
setNotify(false);
clearSubtitles();
for (Title t : subtitles) {
if (t != null) {
addSubtitle(t);
}
}
setNotify(true); // this fires a ChartChangeEvent
}
/**
* Returns the number of titles for the chart.
*
* @return The number of titles for the chart.
*
* @see #getSubtitles()
*/
public int getSubtitleCount() {
return this.subtitles.size();
}
/**
* Returns a chart subtitle.
*
* @param index the index of the chart subtitle (zero based).
*
* @return A chart subtitle.
*
* @see #addSubtitle(Title)
*/
public Title getSubtitle(int index) {
if ((index < 0) || (index >= getSubtitleCount())) {
throw new IllegalArgumentException("Index out of range.");
}
return this.subtitles.get(index);
}
/**
* Adds a chart subtitle, and notifies registered listeners that the chart
* has been modified.
*
* @param subtitle the subtitle (<code>null</code> not permitted).
*
* @see #getSubtitle(int)
*/
public void addSubtitle(Title subtitle) {
ParamChecks.nullNotPermitted(subtitle, "subtitle");
this.subtitles.add(subtitle);
subtitle.addChangeListener(this);
fireChartChanged();
}
/**
* Adds a subtitle at a particular position in the subtitle list, and sends
* a {@link ChartChangeEvent} to all registered listeners.
*
* @param index the index (in the range 0 to {@link #getSubtitleCount()}).
* @param subtitle the subtitle to add (<code>null</code> not permitted).
*
* @since 1.0.6
*/
public void addSubtitle(int index, Title subtitle) {
if (index < 0 || index > getSubtitleCount()) {
throw new IllegalArgumentException(
"The 'index' argument is out of range.");
}
ParamChecks.nullNotPermitted(subtitle, "subtitle");
this.subtitles.add(index, subtitle);
subtitle.addChangeListener(this);
fireChartChanged();
}
/**
* Clears all subtitles from the chart and sends a {@link ChartChangeEvent}
* to all registered listeners.
*
* @see #addSubtitle(Title)
*/
public void clearSubtitles() {
for (Title t : this.subtitles) {
t.removeChangeListener(this);
}
this.subtitles.clear();
fireChartChanged();
}
/**
* Removes the specified subtitle and sends a {@link ChartChangeEvent} to
* all registered listeners.
*
* @param title the title.
*
* @see #addSubtitle(Title)
*/
public void removeSubtitle(Title title) {
this.subtitles.remove(title);
fireChartChanged();
}
/**
* Returns the plot for the chart. The plot is a class responsible for
* coordinating the visual representation of the data, including the axes
* (if any). If you know the specific subclass of plot that you are
* using (e.g. PiePlot, CategoryPlot, XYPlot etc.) then you can cast this
* reference.
*
* @return The plot.
*/
public Plot getPlot() {
return this.plot;
}
/**
* Returns a flag that indicates whether or not anti-aliasing is used when
* the chart is drawn.
*
* @return The flag.
*
* @see #setAntiAlias(boolean)
*/
public boolean getAntiAlias() {
Object val = this.renderingHints.get(RenderingHints.KEY_ANTIALIASING);
return RenderingHints.VALUE_ANTIALIAS_ON.equals(val);
}
/**
* Sets a flag that indicates whether or not anti-aliasing is used when the
* chart is drawn.
* <P>
* Anti-aliasing usually improves the appearance of charts, but is slower.
*
* @param flag the new value of the flag.
*
* @see #getAntiAlias()
*/
public void setAntiAlias(boolean flag) {
Object val = this.renderingHints.get(RenderingHints.KEY_ANTIALIASING);
if (val == null) {
val = RenderingHints.VALUE_ANTIALIAS_DEFAULT;
}
if (!flag && RenderingHints.VALUE_ANTIALIAS_OFF.equals(val)
|| flag && RenderingHints.VALUE_ANTIALIAS_ON.equals(val)) {
// no change, do nothing
return;
}
if (flag) {
this.renderingHints.put(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
}
else {
this.renderingHints.put(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_OFF);
}
fireChartChanged();
}
/**
* Returns the current value stored in the rendering hints table for
* {@link RenderingHints#KEY_TEXT_ANTIALIASING}.
*
* @return The hint value (possibly <code>null</code>).
*
* @since 1.0.5
*
* @see #setTextAntiAlias(Object)
*/
public Object getTextAntiAlias() {
return this.renderingHints.get(RenderingHints.KEY_TEXT_ANTIALIASING);
}
/**
* Sets the value in the rendering hints table for
* {@link RenderingHints#KEY_TEXT_ANTIALIASING} to either
* {@link RenderingHints#VALUE_TEXT_ANTIALIAS_ON} or
* {@link RenderingHints#VALUE_TEXT_ANTIALIAS_OFF}, then sends a
* {@link ChartChangeEvent} to all registered listeners.
*
* @param flag the new value of the flag.
*
* @since 1.0.5
*
* @see #getTextAntiAlias()
* @see #setTextAntiAlias(Object)
*/
public void setTextAntiAlias(boolean flag) {
if (flag) {
setTextAntiAlias(RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
}
else {
setTextAntiAlias(RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);
}
}
/**
* Sets the value in the rendering hints table for
* {@link RenderingHints#KEY_TEXT_ANTIALIASING} and sends a
* {@link ChartChangeEvent} to all registered listeners.
*
* @param val the new value (<code>null</code> permitted).
*
* @since 1.0.5
*
* @see #getTextAntiAlias()
* @see #setTextAntiAlias(boolean)
*/
public void setTextAntiAlias(Object val) {
this.renderingHints.put(RenderingHints.KEY_TEXT_ANTIALIASING, val);
notifyListeners(new ChartChangeEvent(this));
}
/**
* Returns the paint used for the chart background.
*
* @return The paint (possibly <code>null</code>).
*
* @see #setBackgroundPaint(Paint)
*/
public Paint getBackgroundPaint() {
return this.backgroundPaint;
}
/**
* Sets the paint used to fill the chart background and sends a
* {@link ChartChangeEvent} to all registered listeners.
*
* @param paint the paint (<code>null</code> permitted).
*
* @see #getBackgroundPaint()
*/
public void setBackgroundPaint(Paint paint) {
if (this.backgroundPaint != null) {
if (!this.backgroundPaint.equals(paint)) {
this.backgroundPaint = paint;
fireChartChanged();
}
}
else {
if (paint != null) {
this.backgroundPaint = paint;
fireChartChanged();
}
}
}
/**
* Returns the background image for the chart, or <code>null</code> if
* there is no image.
*
* @return The image (possibly <code>null</code>).
*
* @see #setBackgroundImage(Image)
*/
public Image getBackgroundImage() {
return this.backgroundImage;
}
/**
* Sets the background image for the chart and sends a
* {@link ChartChangeEvent} to all registered listeners.
*
* @param image the image (<code>null</code> permitted).
*
* @see #getBackgroundImage()
*/
public void setBackgroundImage(Image image) {
if (this.backgroundImage != null) {
if (!this.backgroundImage.equals(image)) {
this.backgroundImage = image;
fireChartChanged();
}
}
else {
if (image != null) {
this.backgroundImage = image;
fireChartChanged();
}
}
}
/**
* Returns the background image alignment. Alignment constants are defined
* in the <code>org.jfree.chart.ui.Align</code> class in the JCommon class
* library.
*
* @return The alignment.
*
* @see #setBackgroundImageAlignment(int)
*/
public int getBackgroundImageAlignment() {
return this.backgroundImageAlignment;
}
/**
* Sets the background alignment. Alignment options are defined by the
* {@link org.jfree.chart.ui.Align} class.
*
* @param alignment the alignment.
*
* @see #getBackgroundImageAlignment()
*/
public void setBackgroundImageAlignment(int alignment) {
if (this.backgroundImageAlignment != alignment) {
this.backgroundImageAlignment = alignment;
fireChartChanged();
}
}
/**
* Returns the alpha-transparency for the chart's background image.
*
* @return The alpha-transparency.
*
* @see #setBackgroundImageAlpha(float)
*/
public float getBackgroundImageAlpha() {
return this.backgroundImageAlpha;
}
/**
* Sets the alpha-transparency for the chart's background image.
* Registered listeners are notified that the chart has been changed.
*
* @param alpha the alpha value.
*
* @see #getBackgroundImageAlpha()
*/
public void setBackgroundImageAlpha(float alpha) {
if (this.backgroundImageAlpha != alpha) {
this.backgroundImageAlpha = alpha;
fireChartChanged();
}
}
/**
* Returns a flag that controls whether or not change events are sent to
* registered listeners.
*
* @return A boolean.
*
* @see #setNotify(boolean)
*/
public boolean isNotify() {
return this.notify;
}
/**
* Sets a flag that controls whether or not listeners receive
* {@link ChartChangeEvent} notifications.
*
* @param notify a boolean.
*
* @see #isNotify()
*/
public void setNotify(boolean notify) {
this.notify = notify;
// if the flag is being set to true, there may be queued up changes...
if (notify) {
notifyListeners(new ChartChangeEvent(this));
}
}
/**
* Draws the chart on a Java 2D graphics device (such as the screen or a
* printer).
* <P>
* This method is the focus of the entire JFreeChart library.
*
* @param g2 the graphics device.
* @param area the area within which the chart should be drawn.
*/
@Override
public void draw(Graphics2D g2, Rectangle2D area) {
draw(g2, area, null, null);
}
/**
* Draws the chart on a Java 2D graphics device (such as the screen or a
* printer). This method is the focus of the entire JFreeChart library.
*
* @param g2 the graphics device.
* @param area the area within which the chart should be drawn.
* @param info records info about the drawing (null means collect no info).
*/
public void draw(Graphics2D g2, Rectangle2D area, ChartRenderingInfo info) {
draw(g2, area, null, info);
}
/**
* Draws the chart on a Java 2D graphics device (such as the screen or a
* printer).
* <P>
* This method is the focus of the entire JFreeChart library.
*
* @param g2 the graphics device.
* @param chartArea the area within which the chart should be drawn.
* @param anchor the anchor point (in Java2D space) for the chart
* (<code>null</code> permitted).
* @param info records info about the drawing (null means collect no info).
*/
public void draw(Graphics2D g2, Rectangle2D chartArea, Point2D anchor,
ChartRenderingInfo info) {
notifyListeners(new ChartProgressEvent(this, this,
ChartProgressEvent.DRAWING_STARTED, 0));
EntityCollection entities = null;
// record the chart area, if info is requested...
if (info != null) {
info.clear();
info.setChartArea(chartArea);
entities = info.getEntityCollection();
}
if (entities != null) {
entities.add(new JFreeChartEntity((Rectangle2D) chartArea.clone(),
this));
}
// ensure no drawing occurs outside chart area...
Shape savedClip = g2.getClip();
g2.clip(chartArea);
g2.addRenderingHints(this.renderingHints);
// draw the chart background...
if (this.backgroundPaint != null) {
g2.setPaint(this.backgroundPaint);
g2.fill(chartArea);
}
if (this.backgroundImage != null) {
Composite originalComposite = g2.getComposite();
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,
this.backgroundImageAlpha));
Rectangle2D dest = new Rectangle2D.Double(0.0, 0.0,
this.backgroundImage.getWidth(null),
this.backgroundImage.getHeight(null));
Align.align(dest, chartArea, this.backgroundImageAlignment);
g2.drawImage(this.backgroundImage, (int) dest.getX(),
(int) dest.getY(), (int) dest.getWidth(),
(int) dest.getHeight(), null);
g2.setComposite(originalComposite);
}
if (isBorderVisible()) {
Paint paint = getBorderPaint();
Stroke stroke = getBorderStroke();
if (paint != null && stroke != null) {
Rectangle2D borderArea = new Rectangle2D.Double(
chartArea.getX(), chartArea.getY(),
chartArea.getWidth() - 1.0, chartArea.getHeight()
- 1.0);
g2.setPaint(paint);
g2.setStroke(stroke);
g2.draw(borderArea);
}
}
// draw the title and subtitles...
Rectangle2D nonTitleArea = new Rectangle2D.Double();
nonTitleArea.setRect(chartArea);
this.padding.trim(nonTitleArea);
if (this.title != null && this.title.isVisible()) {
EntityCollection e = drawTitle(this.title, g2, nonTitleArea,
(entities != null));
if (e != null && entities != null) {
entities.addAll(e);
}
}
for (Title currentTitle : this.subtitles) {
if (currentTitle.isVisible()) {
EntityCollection e = drawTitle(currentTitle, g2, nonTitleArea,
(entities != null));
if (e != null && entities != null) {
entities.addAll(e);
}
}
}
Rectangle2D plotArea = nonTitleArea;
// draw the plot (axes and data visualisation)
PlotRenderingInfo plotInfo = null;
if (info != null) {
plotInfo = info.getPlotInfo();
}
this.plot.draw(g2, plotArea, anchor, null, plotInfo);
g2.setClip(savedClip);
notifyListeners(new ChartProgressEvent(this, this,
ChartProgressEvent.DRAWING_FINISHED, 100));
}
/**
* Creates a rectangle that is aligned to the frame.
*
* @param dimensions the dimensions for the rectangle.
* @param frame the frame to align to.
* @param hAlign the horizontal alignment.
* @param vAlign the vertical alignment.
*
* @return A rectangle.
*/
private Rectangle2D createAlignedRectangle2D(Size2D dimensions,
Rectangle2D frame, HorizontalAlignment hAlign,
VerticalAlignment vAlign) {
double x = Double.NaN;
double y = Double.NaN;
if (hAlign == HorizontalAlignment.LEFT) {
x = frame.getX();
}
else if (hAlign == HorizontalAlignment.CENTER) {
x = frame.getCenterX() - (dimensions.width / 2.0);
}
else if (hAlign == HorizontalAlignment.RIGHT) {
x = frame.getMaxX() - dimensions.width;
}
if (vAlign == VerticalAlignment.TOP) {
y = frame.getY();
}
else if (vAlign == VerticalAlignment.CENTER) {
y = frame.getCenterY() - (dimensions.height / 2.0);
}
else if (vAlign == VerticalAlignment.BOTTOM) {
y = frame.getMaxY() - dimensions.height;
}
return new Rectangle2D.Double(x, y, dimensions.width,
dimensions.height);
}
/**
* Draws a title. The title should be drawn at the top, bottom, left or
* right of the specified area, and the area should be updated to reflect
* the amount of space used by the title.
*
* @param t the title (<code>null</code> not permitted).
* @param g2 the graphics device (<code>null</code> not permitted).
* @param area the chart area, excluding any existing titles
* (<code>null</code> not permitted).
* @param entities a flag that controls whether or not an entity
* collection is returned for the title.
*
* @return An entity collection for the title (possibly <code>null</code>).
*/
protected EntityCollection drawTitle(Title t, Graphics2D g2,
Rectangle2D area, boolean entities) {
ParamChecks.nullNotPermitted(t, "t");
ParamChecks.nullNotPermitted(area, "area");
Rectangle2D titleArea;
RectangleEdge position = t.getPosition();
double ww = area.getWidth();
if (ww <= 0.0) {
return null;
}
double hh = area.getHeight();
if (hh <= 0.0) {
return null;
}
RectangleConstraint constraint = new RectangleConstraint(ww,
new Range(0.0, ww), LengthConstraintType.RANGE, hh,
new Range(0.0, hh), LengthConstraintType.RANGE);
Object retValue;
BlockParams p = new BlockParams();
p.setGenerateEntities(entities);
if (position == RectangleEdge.TOP) {
Size2D size = t.arrange(g2, constraint);
titleArea = createAlignedRectangle2D(size, area,
t.getHorizontalAlignment(), VerticalAlignment.TOP);
retValue = t.draw(g2, titleArea, p);
area.setRect(area.getX(), Math.min(area.getY() + size.height,
area.getMaxY()), area.getWidth(), Math.max(area.getHeight()
- size.height, 0));
}
else if (position == RectangleEdge.BOTTOM) {
Size2D size = t.arrange(g2, constraint);
titleArea = createAlignedRectangle2D(size, area,
t.getHorizontalAlignment(), VerticalAlignment.BOTTOM);
retValue = t.draw(g2, titleArea, p);
area.setRect(area.getX(), area.getY(), area.getWidth(),
area.getHeight() - size.height);
}
else if (position == RectangleEdge.RIGHT) {
Size2D size = t.arrange(g2, constraint);
titleArea = createAlignedRectangle2D(size, area,
HorizontalAlignment.RIGHT, t.getVerticalAlignment());
retValue = t.draw(g2, titleArea, p);
area.setRect(area.getX(), area.getY(), area.getWidth()
- size.width, area.getHeight());
}
else if (position == RectangleEdge.LEFT) {
Size2D size = t.arrange(g2, constraint);
titleArea = createAlignedRectangle2D(size, area,
HorizontalAlignment.LEFT, t.getVerticalAlignment());
retValue = t.draw(g2, titleArea, p);
area.setRect(area.getX() + size.width, area.getY(), area.getWidth()
- size.width, area.getHeight());
}
else {
throw new RuntimeException("Unrecognised title position.");
}
EntityCollection result = null;
if (retValue instanceof EntityBlockResult) {
EntityBlockResult ebr = (EntityBlockResult) retValue;
result = ebr.getEntityCollection();
}
return result;
}
/**
* Creates and returns a buffered image into which the chart has been drawn.
*
* @param width the width.
* @param height the height.
*
* @return A buffered image.
*/
public BufferedImage createBufferedImage(int width, int height) {
return createBufferedImage(width, height, null);
}
/**
* Creates and returns a buffered image into which the chart has been drawn.
*
* @param width the width.
* @param height the height.
* @param info carries back chart state information (<code>null</code>
* permitted).
*
* @return A buffered image.
*/
public BufferedImage createBufferedImage(int width, int height,
ChartRenderingInfo info) {
return createBufferedImage(width, height, BufferedImage.TYPE_INT_ARGB,
info);
}
/**
* Creates and returns a buffered image into which the chart has been drawn.
*
* @param width the width.
* @param height the height.
* @param imageType the image type.
* @param info carries back chart state information (<code>null</code>
* permitted).
*
* @return A buffered image.
*/
public BufferedImage createBufferedImage(int width, int height,
int imageType,
ChartRenderingInfo info) {
BufferedImage image = new BufferedImage(width, height, imageType);
Graphics2D g2 = image.createGraphics();
draw(g2, new Rectangle2D.Double(0, 0, width, height), null, info);
g2.dispose();
return image;
}
/**
* Creates and returns a buffered image into which the chart has been drawn.
*
* @param imageWidth the image width.
* @param imageHeight the image height.
* @param drawWidth the width for drawing the chart (will be scaled to
* fit image).
* @param drawHeight the height for drawing the chart (will be scaled to
* fit image).
* @param info optional object for collection chart dimension and entity
* information.
*
* @return A buffered image.
*/
public BufferedImage createBufferedImage(int imageWidth,
int imageHeight,
double drawWidth,
double drawHeight,
ChartRenderingInfo info) {
BufferedImage image = new BufferedImage(imageWidth, imageHeight,
BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = image.createGraphics();
double scaleX = imageWidth / drawWidth;
double scaleY = imageHeight / drawHeight;
AffineTransform st = AffineTransform.getScaleInstance(scaleX, scaleY);
g2.transform(st);
draw(g2, new Rectangle2D.Double(0, 0, drawWidth, drawHeight), null,
info);
g2.dispose();
return image;
}
/**
* Handles a 'click' on the chart. JFreeChart is not a UI component, so
* some other object (for example, {@link ChartPanel}) needs to capture
* the click event and pass it onto the JFreeChart object.
* If you are not using JFreeChart in a client application, then this
* method is not required.
*
* @param x x-coordinate of the click (in Java2D space).
* @param y y-coordinate of the click (in Java2D space).
* @param info contains chart dimension and entity information
* (<code>null</code> not permitted).
*/
public void handleClick(int x, int y, ChartRenderingInfo info) {
// pass the click on to the plot...
// rely on the plot to post a plot change event and redraw the chart...
this.plot.handleClick(x, y, info.getPlotInfo());
}
/**
* Registers an object for notification of changes to the chart.
*
* @param listener the listener (<code>null</code> not permitted).
*
* @see #removeChangeListener(ChartChangeListener)
*/
public void addChangeListener(ChartChangeListener listener) {
ParamChecks.nullNotPermitted(listener, "listener");
this.changeListeners.add(ChartChangeListener.class, listener);
}
/**
* Deregisters an object for notification of changes to the chart.
*
* @param listener the listener (<code>null</code> not permitted)
*
* @see #addChangeListener(ChartChangeListener)
*/
public void removeChangeListener(ChartChangeListener listener) {
ParamChecks.nullNotPermitted(listener, "listener");
this.changeListeners.remove(ChartChangeListener.class, listener);
}
/**
* Sends a default {@link ChartChangeEvent} to all registered listeners.
* <P>
* This method is for convenience only.
*/
public void fireChartChanged() {
ChartChangeEvent event = new ChartChangeEvent(this);
notifyListeners(event);
}
/**
* Sends a {@link ChartChangeEvent} to all registered listeners.
*
* @param event information about the event that triggered the
* notification.
*/
protected void notifyListeners(ChartChangeEvent event) {
if (this.notify) {
Object[] listeners = this.changeListeners.getListenerList();
for (int i = listeners.length - 2; i >= 0; i -= 2) {
if (listeners[i] == ChartChangeListener.class) {
((ChartChangeListener) listeners[i + 1]).chartChanged(
event);
}
}
}
}
/**
* Registers an object for notification of progress events relating to the
* chart.
*
* @param listener the object being registered.
*
* @see #removeProgressListener(ChartProgressListener)
*/
public void addProgressListener(ChartProgressListener listener) {
this.progressListeners.add(ChartProgressListener.class, listener);
}
/**
* Deregisters an object for notification of changes to the chart.
*
* @param listener the object being deregistered.
*
* @see #addProgressListener(ChartProgressListener)
*/
public void removeProgressListener(ChartProgressListener listener) {
this.progressListeners.remove(ChartProgressListener.class, listener);
}
/**
* Sends a {@link ChartProgressEvent} to all registered listeners.
*
* @param event information about the event that triggered the
* notification.
*/
protected void notifyListeners(ChartProgressEvent event) {
Object[] listeners = this.progressListeners.getListenerList();
for (int i = listeners.length - 2; i >= 0; i -= 2) {
if (listeners[i] == ChartProgressListener.class) {
((ChartProgressListener) listeners[i + 1]).chartProgress(event);
}
}
}
/**
* Receives notification that a chart title has changed, and passes this
* on to registered listeners.
*
* @param event information about the chart title change.
*/
@Override
public void titleChanged(TitleChangeEvent event) {
event.setChart(this);
notifyListeners(event);
}
/**
* Receives notification that the plot has changed, and passes this on to
* registered listeners.
*
* @param event information about the plot change.
*/
@Override
public void plotChanged(PlotChangeEvent event) {
event.setChart(this);
notifyListeners(event);
}
/**
* Tests this chart 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 JFreeChart)) {
return false;
}
JFreeChart that = (JFreeChart) obj;
if (!this.renderingHints.equals(that.renderingHints)) {
return false;
}
if (this.borderVisible != that.borderVisible) {
return false;
}
if (!ObjectUtilities.equal(this.borderStroke, that.borderStroke)) {
return false;
}
if (!PaintUtilities.equal(this.borderPaint, that.borderPaint)) {
return false;
}
if (!this.padding.equals(that.padding)) {
return false;
}
if (!ObjectUtilities.equal(this.title, that.title)) {
return false;
}
if (!ObjectUtilities.equal(this.subtitles, that.subtitles)) {
return false;
}
if (!ObjectUtilities.equal(this.plot, that.plot)) {
return false;
}
if (!PaintUtilities.equal(
this.backgroundPaint, that.backgroundPaint
)) {
return false;
}
if (!ObjectUtilities.equal(this.backgroundImage,
that.backgroundImage)) {
return false;
}
if (this.backgroundImageAlignment != that.backgroundImageAlignment) {
return false;
}
if (this.backgroundImageAlpha != that.backgroundImageAlpha) {
return false;
}
if (this.notify != that.notify) {
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.writeStroke(this.borderStroke, stream);
SerialUtilities.writePaint(this.borderPaint, 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.borderStroke = SerialUtilities.readStroke(stream);
this.borderPaint = SerialUtilities.readPaint(stream);
this.backgroundPaint = SerialUtilities.readPaint(stream);
this.progressListeners = new EventListenerList();
this.changeListeners = new EventListenerList();
this.renderingHints = new RenderingHints(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
// register as a listener with sub-components...
if (this.title != null) {
this.title.addChangeListener(this);
}
for (int i = 0; i < getSubtitleCount(); i++) {
getSubtitle(i).addChangeListener(this);
}
this.plot.addChangeListener(this);
}
/**
* Clones the object, and takes care of listeners.
* Note: caller shall register its own listeners on cloned graph.
*
* @return A clone.
*
* @throws CloneNotSupportedException if the chart is not cloneable.
*/
@Override
public Object clone() throws CloneNotSupportedException {
JFreeChart chart = (JFreeChart) super.clone();
chart.renderingHints = (RenderingHints) this.renderingHints.clone();
// private boolean borderVisible;
// private transient Stroke borderStroke;
// private transient Paint borderPaint;
if (this.title != null) {
chart.title = (TextTitle) this.title.clone();
chart.title.addChangeListener(chart);
}
chart.subtitles = new ArrayList<Title>();
for (int i = 0; i < getSubtitleCount(); i++) {
Title subtitle = (Title) getSubtitle(i).clone();
chart.subtitles.add(subtitle);
subtitle.addChangeListener(chart);
}
if (this.plot != null) {
chart.plot = (Plot) this.plot.clone();
chart.plot.addChangeListener(chart);
}
chart.progressListeners = new EventListenerList();
chart.changeListeners = new EventListenerList();
return chart;
}
}
| 58,771 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
LegendItem.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/LegendItem.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.]
*
* ---------------
* LegendItem.java
* ---------------
* (C) Copyright 2000-2013, by Object Refinery Limited and Contributors.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): Andrzej Porebski;
* David Li;
* Wolfgang Irler;
* Luke Quinane;
*
* Changes (from 2-Oct-2002)
* -------------------------
* 02-Oct-2002 : Fixed errors reported by Checkstyle (DG);
* 17-Jan-2003 : Dropped outlineStroke attribute (DG);
* 08-Oct-2003 : Applied patch for displaying series line style, contributed by
* Luke Quinane (DG);
* 21-Jan-2004 : Added the shapeFilled flag (DG);
* 04-Jun-2004 : Added equals() method, implemented Serializable (DG);
* 25-Nov-2004 : Changes required by new LegendTitle implementation (DG);
* 11-Jan-2005 : Removed deprecated code in preparation for the 1.0.0
* release (DG);
* 20-Apr-2005 : Added tooltip and URL text (DG);
* 28-Nov-2005 : Separated constructors for AttributedString labels (DG);
* 10-Dec-2005 : Fixed serialization bug (1377239) (DG);
* ------------- JFREECHART 1.0.x ---------------------------------------------
* 20-Jul-2006 : Added dataset and series index fields (DG);
* 13-Dec-2006 : Added fillPaintTransformer attribute (DG);
* 18-May-2007 : Added dataset and seriesKey fields (DG);
* 03-Aug-2007 : Fixed null pointer exception (DG);
* 23-Apr-2008 : Added new constructor and implemented Cloneable (DG);
* 17-Jun-2008 : Added optional labelFont and labelPaint attributes (DG);
* 15-Oct-2008 : Added new constructor (DG);
* 28-Apr-2009 : Added various setter methods (DG);
* 15-Jun-2012 : Removed JCommon dependency (DG);
*
*/
package org.jfree.chart;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
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.text.AttributedString;
import java.text.CharacterIterator;
import org.jfree.chart.ui.GradientPaintTransformer;
import org.jfree.chart.ui.StandardGradientPaintTransformer;
import org.jfree.chart.util.AttributedStringUtilities;
import org.jfree.chart.util.ObjectUtilities;
import org.jfree.chart.util.PaintUtilities;
import org.jfree.chart.util.ParamChecks;
import org.jfree.chart.util.PublicCloneable;
import org.jfree.chart.util.ShapeUtilities;
import org.jfree.chart.util.SerialUtilities;
import org.jfree.data.general.Dataset;
/**
* A temporary storage object for recording the properties of a legend item,
* without any consideration for layout issues.
*/
public class LegendItem implements Cloneable, Serializable {
/** For serialization. */
private static final long serialVersionUID = -797214582948827144L;
/**
* 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 label. */
private String label;
/**
* The label font (<code>null</code> is permitted).
*
* @since 1.0.11
*/
private Font labelFont;
/**
* The label paint (<code>null</code> is permitted).
*
* @since 1.0.11
*/
private transient Paint labelPaint;
/** The attributed label (if null, fall back to the regular label). */
private transient AttributedString attributedLabel;
/**
* The description (not currently used - could be displayed as a tool tip).
*/
private String description;
/** The tool tip text. */
private String toolTipText;
/** The url text. */
private String urlText;
/** A flag that controls whether or not the shape is visible. */
private boolean shapeVisible;
/** The shape. */
private transient Shape shape;
/** A flag that controls whether or not the shape is filled. */
private boolean shapeFilled;
/** The paint. */
private transient Paint fillPaint;
/**
* A gradient paint transformer.
*
* @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. */
private transient Paint outlinePaint;
/** The outline stroke. */
private transient Stroke outlineStroke;
/** A flag that controls whether or not the line is visible. */
private boolean lineVisible;
/** The line. */
private transient Shape line;
/** The stroke. */
private transient Stroke lineStroke;
/** The line paint. */
private transient Paint linePaint;
/**
* The shape must be non-null for a LegendItem - if no shape is required,
* use this.
*/
private static final Shape UNUSED_SHAPE = new Line2D.Float();
/**
* The stroke must be non-null for a LegendItem - if no stroke is required,
* use this.
*/
private static final Stroke UNUSED_STROKE = new BasicStroke(0.0f);
/**
* Creates a legend item with the specified label. The remaining
* attributes take default values.
*
* @param label the label (<code>null</code> not permitted).
*
* @since 1.0.10
*/
public LegendItem(String label) {
this(label, Color.BLACK);
}
/**
* Creates a legend item with the specified label and fill paint. The
* remaining attributes take default values.
*
* @param label the label (<code>null</code> not permitted).
* @param paint the paint (<code>null</code> not permitted).
*
* @since 1.0.12
*/
public LegendItem(String label, Paint paint) {
this(label, null, null, null, new Rectangle2D.Double(-4.0, -4.0, 8.0,
8.0), paint);
}
/**
* Creates a legend item with a filled shape. The shape is not outlined,
* and no line is visible.
*
* @param label the label (<code>null</code> not permitted).
* @param description the description (<code>null</code> permitted).
* @param toolTipText the tool tip text (<code>null</code> permitted).
* @param urlText the URL text (<code>null</code> permitted).
* @param shape the shape (<code>null</code> not permitted).
* @param fillPaint the paint used to fill the shape (<code>null</code>
* not permitted).
*/
public LegendItem(String label, String description,
String toolTipText, String urlText,
Shape shape, Paint fillPaint) {
this(label, description, toolTipText, urlText,
/* shape visible = */ true, shape,
/* shape filled = */ true, fillPaint,
/* shape outlined */ false, Color.BLACK, UNUSED_STROKE,
/* line visible */ false, UNUSED_SHAPE, UNUSED_STROKE,
Color.BLACK);
}
/**
* Creates a legend item with a filled and outlined shape.
*
* @param label the label (<code>null</code> not permitted).
* @param description the description (<code>null</code> permitted).
* @param toolTipText the tool tip text (<code>null</code> permitted).
* @param urlText the URL text (<code>null</code> permitted).
* @param shape the shape (<code>null</code> not permitted).
* @param fillPaint the paint used to fill the shape (<code>null</code>
* not permitted).
* @param outlineStroke the outline stroke (<code>null</code> not
* permitted).
* @param outlinePaint the outline paint (<code>null</code> not
* permitted).
*/
public LegendItem(String label, String description,
String toolTipText, String urlText,
Shape shape, Paint fillPaint,
Stroke outlineStroke, Paint outlinePaint) {
this(label, description, toolTipText, urlText,
/* shape visible = */ true, shape,
/* shape filled = */ true, fillPaint,
/* shape outlined = */ true, outlinePaint, outlineStroke,
/* line visible */ false, UNUSED_SHAPE, UNUSED_STROKE,
Color.BLACK);
}
/**
* Creates a legend item using a line.
*
* @param label the label (<code>null</code> not permitted).
* @param description the description (<code>null</code> permitted).
* @param toolTipText the tool tip text (<code>null</code> permitted).
* @param urlText the URL text (<code>null</code> permitted).
* @param line the line (<code>null</code> not permitted).
* @param lineStroke the line stroke (<code>null</code> not permitted).
* @param linePaint the line paint (<code>null</code> not permitted).
*/
public LegendItem(String label, String description,
String toolTipText, String urlText,
Shape line, Stroke lineStroke, Paint linePaint) {
this(label, description, toolTipText, urlText,
/* shape visible = */ false, UNUSED_SHAPE,
/* shape filled = */ false, Color.BLACK,
/* shape outlined = */ false, Color.BLACK, UNUSED_STROKE,
/* line visible = */ true, line, lineStroke, linePaint);
}
/**
* Creates a new legend item.
*
* @param label the label (<code>null</code> not permitted).
* @param description the description (not currently used,
* <code>null</code> permitted).
* @param toolTipText the tool tip text (<code>null</code> permitted).
* @param urlText the URL text (<code>null</code> permitted).
* @param shapeVisible a flag that controls whether or not the shape is
* displayed.
* @param shape the shape (<code>null</code> permitted).
* @param shapeFilled a flag that controls whether or not the shape is
* filled.
* @param fillPaint the fill paint (<code>null</code> not permitted).
* @param shapeOutlineVisible a flag that controls whether or not the
* shape is outlined.
* @param outlinePaint the outline paint (<code>null</code> not permitted).
* @param outlineStroke the outline stroke (<code>null</code> not
* permitted).
* @param lineVisible a flag that controls whether or not the line is
* visible.
* @param line the line.
* @param lineStroke the stroke (<code>null</code> not permitted).
* @param linePaint the line paint (<code>null</code> not permitted).
*/
public LegendItem(String label, String description,
String toolTipText, String urlText,
boolean shapeVisible, Shape shape,
boolean shapeFilled, Paint fillPaint,
boolean shapeOutlineVisible, Paint outlinePaint,
Stroke outlineStroke,
boolean lineVisible, Shape line,
Stroke lineStroke, Paint linePaint) {
ParamChecks.nullNotPermitted(label, "label");
ParamChecks.nullNotPermitted(fillPaint, "fillPaint");
ParamChecks.nullNotPermitted(lineStroke, "lineStroke");
ParamChecks.nullNotPermitted(line, "line");
ParamChecks.nullNotPermitted(linePaint, "linePaint");
ParamChecks.nullNotPermitted(outlinePaint, "outlinePaint");
ParamChecks.nullNotPermitted(outlineStroke, "outlineStroke");
this.label = label;
this.labelPaint = null;
this.attributedLabel = null;
this.description = description;
this.shapeVisible = shapeVisible;
this.shape = shape;
this.shapeFilled = shapeFilled;
this.fillPaint = fillPaint;
this.fillPaintTransformer = new StandardGradientPaintTransformer();
this.shapeOutlineVisible = shapeOutlineVisible;
this.outlinePaint = outlinePaint;
this.outlineStroke = outlineStroke;
this.lineVisible = lineVisible;
this.line = line;
this.lineStroke = lineStroke;
this.linePaint = linePaint;
this.toolTipText = toolTipText;
this.urlText = urlText;
}
/**
* Creates a legend item with a filled shape. The shape is not outlined,
* and no line is visible.
*
* @param label the label (<code>null</code> not permitted).
* @param description the description (<code>null</code> permitted).
* @param toolTipText the tool tip text (<code>null</code> permitted).
* @param urlText the URL text (<code>null</code> permitted).
* @param shape the shape (<code>null</code> not permitted).
* @param fillPaint the paint used to fill the shape (<code>null</code>
* not permitted).
*/
public LegendItem(AttributedString label, String description,
String toolTipText, String urlText,
Shape shape, Paint fillPaint) {
this(label, description, toolTipText, urlText,
/* shape visible = */ true, shape,
/* shape filled = */ true, fillPaint,
/* shape outlined = */ false, Color.BLACK, UNUSED_STROKE,
/* line visible = */ false, UNUSED_SHAPE, UNUSED_STROKE,
Color.BLACK);
}
/**
* Creates a legend item with a filled and outlined shape.
*
* @param label the label (<code>null</code> not permitted).
* @param description the description (<code>null</code> permitted).
* @param toolTipText the tool tip text (<code>null</code> permitted).
* @param urlText the URL text (<code>null</code> permitted).
* @param shape the shape (<code>null</code> not permitted).
* @param fillPaint the paint used to fill the shape (<code>null</code>
* not permitted).
* @param outlineStroke the outline stroke (<code>null</code> not
* permitted).
* @param outlinePaint the outline paint (<code>null</code> not
* permitted).
*/
public LegendItem(AttributedString label, String description,
String toolTipText, String urlText,
Shape shape, Paint fillPaint,
Stroke outlineStroke, Paint outlinePaint) {
this(label, description, toolTipText, urlText,
/* shape visible = */ true, shape,
/* shape filled = */ true, fillPaint,
/* shape outlined = */ true, outlinePaint, outlineStroke,
/* line visible = */ false, UNUSED_SHAPE, UNUSED_STROKE,
Color.BLACK);
}
/**
* Creates a legend item using a line.
*
* @param label the label (<code>null</code> not permitted).
* @param description the description (<code>null</code> permitted).
* @param toolTipText the tool tip text (<code>null</code> permitted).
* @param urlText the URL text (<code>null</code> permitted).
* @param line the line (<code>null</code> not permitted).
* @param lineStroke the line stroke (<code>null</code> not permitted).
* @param linePaint the line paint (<code>null</code> not permitted).
*/
public LegendItem(AttributedString label, String description,
String toolTipText, String urlText,
Shape line, Stroke lineStroke, Paint linePaint) {
this(label, description, toolTipText, urlText,
/* shape visible = */ false, UNUSED_SHAPE,
/* shape filled = */ false, Color.BLACK,
/* shape outlined = */ false, Color.BLACK, UNUSED_STROKE,
/* line visible = */ true, line, lineStroke, linePaint);
}
/**
* Creates a new legend item.
*
* @param label the label (<code>null</code> not permitted).
* @param description the description (not currently used,
* <code>null</code> permitted).
* @param toolTipText the tool tip text (<code>null</code> permitted).
* @param urlText the URL text (<code>null</code> permitted).
* @param shapeVisible a flag that controls whether or not the shape is
* displayed.
* @param shape the shape (<code>null</code> permitted).
* @param shapeFilled a flag that controls whether or not the shape is
* filled.
* @param fillPaint the fill paint (<code>null</code> not permitted).
* @param shapeOutlineVisible a flag that controls whether or not the
* shape is outlined.
* @param outlinePaint the outline paint (<code>null</code> not permitted).
* @param outlineStroke the outline stroke (<code>null</code> not
* permitted).
* @param lineVisible a flag that controls whether or not the line is
* visible.
* @param line the line (<code>null</code> not permitted).
* @param lineStroke the stroke (<code>null</code> not permitted).
* @param linePaint the line paint (<code>null</code> not permitted).
*/
public LegendItem(AttributedString label, String description,
String toolTipText, String urlText,
boolean shapeVisible, Shape shape,
boolean shapeFilled, Paint fillPaint,
boolean shapeOutlineVisible, Paint outlinePaint,
Stroke outlineStroke,
boolean lineVisible, Shape line, Stroke lineStroke,
Paint linePaint) {
ParamChecks.nullNotPermitted(label, "label");
ParamChecks.nullNotPermitted(fillPaint, "fillPaint");
ParamChecks.nullNotPermitted(lineStroke, "lineStroke");
ParamChecks.nullNotPermitted(line, "line");
ParamChecks.nullNotPermitted(linePaint, "linePaint");
ParamChecks.nullNotPermitted(outlinePaint, "outlinePaint");
ParamChecks.nullNotPermitted(outlineStroke, "outlineStroke");
this.label = characterIteratorToString(label.getIterator());
this.attributedLabel = label;
this.description = description;
this.shapeVisible = shapeVisible;
this.shape = shape;
this.shapeFilled = shapeFilled;
this.fillPaint = fillPaint;
this.fillPaintTransformer = new StandardGradientPaintTransformer();
this.shapeOutlineVisible = shapeOutlineVisible;
this.outlinePaint = outlinePaint;
this.outlineStroke = outlineStroke;
this.lineVisible = lineVisible;
this.line = line;
this.lineStroke = lineStroke;
this.linePaint = linePaint;
this.toolTipText = toolTipText;
this.urlText = urlText;
}
/**
* Returns a string containing the characters from the given iterator.
*
* @param iterator the iterator (<code>null</code> not permitted).
*
* @return A string.
*/
private String characterIteratorToString(CharacterIterator iterator) {
int endIndex = iterator.getEndIndex();
int beginIndex = iterator.getBeginIndex();
int count = endIndex - beginIndex;
if (count <= 0) {
return "";
}
char[] chars = new char[count];
int i = 0;
char c = iterator.first();
while (c != CharacterIterator.DONE) {
chars[i] = c;
i++;
c = iterator.next();
}
return new String(chars);
}
/**
* Returns the dataset.
*
* @return The dataset.
*
* @since 1.0.6
*
* @see #setDatasetIndex(int)
*/
public Dataset getDataset() {
return this.dataset;
}
/**
* Sets the dataset.
*
* @param dataset the dataset.
*
* @since 1.0.6
*/
public void setDataset(Dataset dataset) {
this.dataset = dataset;
}
/**
* Returns the dataset index for this legend item.
*
* @return The dataset index.
*
* @since 1.0.2
*
* @see #setDatasetIndex(int)
* @see #getDataset()
*/
public int getDatasetIndex() {
return this.datasetIndex;
}
/**
* Sets the dataset index for this legend item.
*
* @param index the index.
*
* @since 1.0.2
*
* @see #getDatasetIndex()
*/
public void setDatasetIndex(int index) {
this.datasetIndex = index;
}
/**
* Returns the series key.
*
* @return The series key.
*
* @since 1.0.6
*
* @see #setSeriesKey(Comparable)
*/
public Comparable getSeriesKey() {
return this.seriesKey;
}
/**
* Sets the series key.
*
* @param key the series key.
*
* @since 1.0.6
*/
public void setSeriesKey(Comparable key) {
this.seriesKey = key;
}
/**
* Returns the series index for this legend item.
*
* @return The series index.
*
* @since 1.0.2
*/
public int getSeriesIndex() {
return this.series;
}
/**
* Sets the series index for this legend item.
*
* @param index the index.
*
* @since 1.0.2
*/
public void setSeriesIndex(int index) {
this.series = index;
}
/**
* Returns the label.
*
* @return The label (never <code>null</code>).
*/
public String getLabel() {
return this.label;
}
/**
* Returns the label font.
*
* @return The label font (possibly <code>null</code>).
*
* @since 1.0.11
*/
public Font getLabelFont() {
return this.labelFont;
}
/**
* Sets the label font.
*
* @param font the font (<code>null</code> permitted).
*
* @since 1.0.11
*/
public void setLabelFont(Font font) {
this.labelFont = font;
}
/**
* Returns the paint used to draw the label.
*
* @return The paint (possibly <code>null</code>).
*
* @since 1.0.11
*/
public Paint getLabelPaint() {
return this.labelPaint;
}
/**
* Sets the paint used to draw the label.
*
* @param paint the paint (<code>null</code> permitted).
*
* @since 1.0.11
*/
public void setLabelPaint(Paint paint) {
this.labelPaint = paint;
}
/**
* Returns the attributed label.
*
* @return The attributed label (possibly <code>null</code>).
*/
public AttributedString getAttributedLabel() {
return this.attributedLabel;
}
/**
* Returns the description for the legend item.
*
* @return The description (possibly <code>null</code>).
*
* @see #setDescription(java.lang.String)
*/
public String getDescription() {
return this.description;
}
/**
* Sets the description for this legend item.
*
* @param text the description (<code>null</code> permitted).
*
* @see #getDescription()
* @since 1.0.14
*/
public void setDescription(String text) {
this.description = text;
}
/**
* Returns the tool tip text.
*
* @return The tool tip text (possibly <code>null</code>).
*
* @see #setToolTipText(java.lang.String)
*/
public String getToolTipText() {
return this.toolTipText;
}
/**
* Sets the tool tip text for this legend item.
*
* @param text the text (<code>null</code> permitted).
*
* @see #getToolTipText()
* @since 1.0.14
*/
public void setToolTipText(String text) {
this.toolTipText = text;
}
/**
* Returns the URL text.
*
* @return The URL text (possibly <code>null</code>).
*
* @see #setURLText(java.lang.String)
*/
public String getURLText() {
return this.urlText;
}
/**
* Sets the URL text.
*
* @param text the text (<code>null</code> permitted).
*
* @see #getURLText()
*
* @since 1.0.14
*/
public void setURLText(String text) {
this.urlText = text;
}
/**
* Returns a flag that indicates whether or not the shape is visible.
*
* @return A boolean.
*
* @see #setShapeVisible(boolean)
*/
public boolean isShapeVisible() {
return this.shapeVisible;
}
/**
* Sets the flag that controls whether or not the shape is visible.
*
* @param visible the new flag value.
*
* @see #isShapeVisible()
* @see #isLineVisible()
*
* @since 1.0.14
*/
public void setShapeVisible(boolean visible) {
this.shapeVisible = visible;
}
/**
* Returns the shape used to label the series represented by this legend
* item.
*
* @return The shape (never <code>null</code>).
*
* @see #setShape(java.awt.Shape)
*/
public Shape getShape() {
return this.shape;
}
/**
* Sets the shape for the legend item.
*
* @param shape the shape (<code>null</code> not permitted).
*
* @see #getShape()
* @since 1.0.14
*/
public void setShape(Shape shape) {
ParamChecks.nullNotPermitted(shape, "shape");
this.shape = shape;
}
/**
* Returns a flag that controls whether or not the shape is filled.
*
* @return A boolean.
*/
public boolean isShapeFilled() {
return this.shapeFilled;
}
/**
* Returns the fill paint.
*
* @return The fill paint (never <code>null</code>).
*/
public Paint getFillPaint() {
return this.fillPaint;
}
/**
* Sets the fill paint.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @since 1.0.11
*/
public void setFillPaint(Paint paint) {
ParamChecks.nullNotPermitted(paint, "paint");
this.fillPaint = paint;
}
/**
* Returns the flag that controls whether or not the shape outline
* is visible.
*
* @return A boolean.
*/
public boolean isShapeOutlineVisible() {
return this.shapeOutlineVisible;
}
/**
* Returns the line stroke for the series.
*
* @return The stroke (never <code>null</code>).
*/
public Stroke getLineStroke() {
return this.lineStroke;
}
/**
* Returns the paint used for lines.
*
* @return The paint (never <code>null</code>).
*/
public Paint getLinePaint() {
return this.linePaint;
}
/**
* Sets the line paint.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @since 1.0.11
*/
public void setLinePaint(Paint paint) {
ParamChecks.nullNotPermitted(paint, "paint");
this.linePaint = paint;
}
/**
* Returns the outline paint.
*
* @return The outline paint (never <code>null</code>).
*/
public Paint getOutlinePaint() {
return this.outlinePaint;
}
/**
* Sets the outline paint.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @since 1.0.11
*/
public void setOutlinePaint(Paint paint) {
ParamChecks.nullNotPermitted(paint, "paint");
this.outlinePaint = paint;
}
/**
* Returns the outline stroke.
*
* @return The outline stroke (never <code>null</code>).
*
* @see #setOutlineStroke(java.awt.Stroke)
*/
public Stroke getOutlineStroke() {
return this.outlineStroke;
}
/**
* Sets the outline stroke.
*
* @param stroke the stroke (<code>null</code> not permitted).
*
* @see #getOutlineStroke()
*
* @since 1.0.14
*/
public void setOutlineStroke(Stroke stroke) {
ParamChecks.nullNotPermitted(stroke, "stroke");
this.outlineStroke = stroke;
}
/**
* Returns a flag that indicates 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 shape is visible for
* this legend item.
*
* @param visible the new flag value.
*
* @see #isLineVisible()
* @since 1.0.14
*/
public void setLineVisible(boolean visible) {
this.lineVisible = visible;
}
/**
* Returns the line.
*
* @return The line (never <code>null</code>).
*
* @see #setLine(java.awt.Shape)
* @see #isLineVisible()
*/
public Shape getLine() {
return this.line;
}
/**
* Sets the line.
*
* @param line the line (<code>null</code> not permitted).
*
* @see #getLine()
* @since 1.0.14
*/
public void setLine(Shape line) {
ParamChecks.nullNotPermitted(line, "line");
this.line = line;
}
/**
* 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) {
ParamChecks.nullNotPermitted(transformer, "transformer");
this.fillPaintTransformer = transformer;
}
/**
* Tests this item 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 LegendItem)) {
return false;
}
LegendItem that = (LegendItem) obj;
if (this.datasetIndex != that.datasetIndex) {
return false;
}
if (this.series != that.series) {
return false;
}
if (!this.label.equals(that.label)) {
return false;
}
if (!AttributedStringUtilities.equal(this.attributedLabel,
that.attributedLabel)) {
return false;
}
if (!ObjectUtilities.equal(this.description, that.description)) {
return false;
}
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 (!this.outlineStroke.equals(that.outlineStroke)) {
return false;
}
if (!PaintUtilities.equal(this.outlinePaint, that.outlinePaint)) {
return false;
}
if (!this.lineVisible == that.lineVisible) {
return false;
}
if (!ShapeUtilities.equal(this.line, that.line)) {
return false;
}
if (!this.lineStroke.equals(that.lineStroke)) {
return false;
}
if (!PaintUtilities.equal(this.linePaint, that.linePaint)) {
return false;
}
if (!ObjectUtilities.equal(this.labelFont, that.labelFont)) {
return false;
}
if (!PaintUtilities.equal(this.labelPaint, that.labelPaint)) {
return false;
}
return true;
}
@Override
public int hashCode() {
int hash = 7;
hash = 47 * hash + (this.seriesKey != null ? this.seriesKey.hashCode() : 0);
hash = 47 * hash + this.datasetIndex;
return hash;
}
/**
* Returns an independent copy of this object (except that the clone will
* still reference the same dataset as the original
* <code>LegendItem</code>).
*
* @return A clone.
*
* @throws CloneNotSupportedException if the legend item cannot be cloned.
*
* @since 1.0.10
*/
@Override
public Object clone() throws CloneNotSupportedException {
LegendItem clone = (LegendItem) super.clone();
if (this.seriesKey instanceof PublicCloneable) {
PublicCloneable pc = (PublicCloneable) this.seriesKey;
clone.seriesKey = (Comparable) pc.clone();
}
// FIXME: Clone the attributed string if it is not null
clone.shape = ShapeUtilities.clone(this.shape);
if (this.fillPaintTransformer instanceof PublicCloneable) {
PublicCloneable pc = (PublicCloneable) this.fillPaintTransformer;
clone.fillPaintTransformer = (GradientPaintTransformer) pc.clone();
}
clone.line = ShapeUtilities.clone(this.line);
return clone;
}
/**
* Provides serialization support.
*
* @param stream the output stream (<code>null</code> not permitted).
*
* @throws IOException if there is an I/O error.
*/
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
SerialUtilities.writeAttributedString(this.attributedLabel, stream);
SerialUtilities.writeShape(this.shape, stream);
SerialUtilities.writePaint(this.fillPaint, stream);
SerialUtilities.writeStroke(this.outlineStroke, stream);
SerialUtilities.writePaint(this.outlinePaint, stream);
SerialUtilities.writeShape(this.line, stream);
SerialUtilities.writeStroke(this.lineStroke, stream);
SerialUtilities.writePaint(this.linePaint, stream);
SerialUtilities.writePaint(this.labelPaint, stream);
}
/**
* Provides serialization support.
*
* @param stream the input stream (<code>null</code> not permitted).
*
* @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.attributedLabel = SerialUtilities.readAttributedString(stream);
this.shape = SerialUtilities.readShape(stream);
this.fillPaint = SerialUtilities.readPaint(stream);
this.outlineStroke = SerialUtilities.readStroke(stream);
this.outlinePaint = SerialUtilities.readPaint(stream);
this.line = SerialUtilities.readShape(stream);
this.lineStroke = SerialUtilities.readStroke(stream);
this.linePaint = SerialUtilities.readPaint(stream);
this.labelPaint = SerialUtilities.readPaint(stream);
}
}
| 37,114 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
PaintMap.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/PaintMap.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.]
*
* -------------
* PaintMap.java
* -------------
* (C) Copyright 2006-2012, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes:
* --------
* 27-Sep-2006 : Version 1 (DG);
* 17-Jan-2007 : Changed TreeMap to HashMap, so that different classes that
* implement Comparable can be used as keys (DG);
* 16-Jun-2012 : Removed JCommon dependencies (DG);
*
*/
package org.jfree.chart;
import java.awt.Paint;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.jfree.chart.util.PaintUtilities;
import org.jfree.chart.util.ParamChecks;
import org.jfree.chart.util.SerialUtilities;
/**
* A storage structure that maps <code>Comparable</code> instances with
* <code>Paint</code> instances.
* <br><br>
* To support cloning and serialization, you should only use keys that are
* cloneable and serializable. Special handling for the <code>Paint</code>
* instances is included in this class.
*
* @since 1.0.3
*/
public class PaintMap implements Cloneable, Serializable {
/** For serialization. */
static final long serialVersionUID = -4639833772123069274L;
/** Storage for the keys and values. */
private transient Map<Comparable, Paint> store;
/**
* Creates a new (empty) map.
*/
public PaintMap() {
this.store = new HashMap<Comparable, Paint>();
}
/**
* Returns the paint associated with the specified key, or
* <code>null</code>.
*
* @param key the key (<code>null</code> not permitted).
*
* @return The paint, or <code>null</code>.
*
* @throws IllegalArgumentException if <code>key</code> is
* <code>null</code>.
*/
public Paint getPaint(Comparable key) {
ParamChecks.nullNotPermitted(key, "key");
return this.store.get(key);
}
/**
* Returns <code>true</code> if the map contains the specified key, and
* <code>false</code> otherwise.
*
* @param key the key.
*
* @return <code>true</code> if the map contains the specified key, and
* <code>false</code> otherwise.
*/
public boolean containsKey(Comparable key) {
return this.store.containsKey(key);
}
/**
* Adds a mapping between the specified <code>key</code> and
* <code>paint</code> values.
*
* @param key the key (<code>null</code> not permitted).
* @param paint the paint.
*
* @throws IllegalArgumentException if <code>key</code> is
* <code>null</code>.
*/
public void put(Comparable key, Paint paint) {
ParamChecks.nullNotPermitted(key, "key");
this.store.put(key, paint);
}
/**
* Resets the map to empty.
*/
public void clear() {
this.store.clear();
}
/**
* Tests this map 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 PaintMap)) {
return false;
}
PaintMap that = (PaintMap) obj;
if (this.store.size() != that.store.size()) {
return false;
}
Set<Comparable> keys = this.store.keySet();
for (Comparable key : keys) {
Paint p1 = getPaint(key);
Paint p2 = that.getPaint(key);
if (!PaintUtilities.equal(p1, p2)) {
return false;
}
}
return true;
}
/**
* Returns a clone of this <code>PaintMap</code>.
*
* @return A clone of this instance.
*
* @throws CloneNotSupportedException if any key is not cloneable.
*/
@Override
public Object clone() throws CloneNotSupportedException {
// TODO: I think we need to make sure the keys are actually cloned,
// whereas the paint instances are always immutable so they're OK
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();
stream.writeInt(this.store.size());
Set<Comparable> keys = this.store.keySet();
for (Comparable key : keys) {
stream.writeObject(key);
Paint paint = getPaint(key);
SerialUtilities.writePaint(paint, 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.store = new HashMap<Comparable, Paint>();
int keyCount = stream.readInt();
for (int i = 0; i < keyCount; i++) {
Comparable key = (Comparable) stream.readObject();
Paint paint = SerialUtilities.readPaint(stream);
this.store.put(key, paint);
}
}
}
| 6,733 | 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/package-info.java | /**
* Core support for the plug-in renderers used by the {@link org.jfree.chart.plot.CategoryPlot} and {@link org.jfree.chart.plot.XYPlot} classes.
*/
package org.jfree.chart.renderer;
| 187 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
NotOutlierException.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/renderer/NotOutlierException.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.]
*
* ------------------------
* NotOutlierException.java
* ------------------------
* (C) Copyright 2003-2008, by David Browning and Contributors.
*
* Original Author: David Browning (for Australian Institute of Marine
* Science);
* Contributor(s): -;
*
* Changes
* -------
* 05-Aug-2003 : Version 1, contributed by David Browning (DG);
* ------------- JFREECHART 1.0.x ---------------------------------------------
* 02-Feb-2007 : Removed author tags from all over JFreeChart sources (DG);
*
*/
package org.jfree.chart.renderer;
/**
* An exception that is generated by the {@link Outlier}, {@link OutlierList}
* and {@link OutlierListCollection} classes.
*/
public class NotOutlierException extends Exception {
/**
* Creates a new exception.
*
* @param message the exception message.
*/
public NotOutlierException(String message) {
super(message);
}
}
| 2,159 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
AreaRendererEndType.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/renderer/AreaRendererEndType.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.]
*
* ------------------------
* AreaRendererEndType.java
* ------------------------
* (C) Copyright 2004-2008, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes:
* --------
* 29-April-2004 : Version 1 (DG);
*
*/
package org.jfree.chart.renderer;
/**
* An enumeration of the 'end types' for an area renderer.
*/
public enum AreaRendererEndType {
/**
* The area tapers from the first or last value down to zero.
*/
TAPER("AreaRendererEndType.TAPER"),
/**
* The area is truncated at the first or last value.
*/
TRUNCATE("AreaRendererEndType.TRUNCATE"),
/**
* The area is levelled at the first or last value.
*/
LEVEL("AreaRendererEndType.LEVEL");
/** The name. */
private String name;
/**
* Private constructor.
*
* @param name the name.
*/
private AreaRendererEndType(String name) {
this.name = name;
}
/**
* Returns a string representing the object.
*
* @return The string.
*/
@Override
public String toString() {
return this.name;
}
}
| 2,407 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
GrayPaintScale.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/renderer/GrayPaintScale.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.]
*
* -------------------
* GrayPaintScale.java
* -------------------
* (C) Copyright 2006-2013, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 05-Jul-2006 : Version 1 (DG);
* 31-Jan-2007 : Renamed min and max to lowerBound and upperBound (DG);
* 26-Sep-2007 : Fixed bug 1767315, problem in getPaint() method (DG);
* 29-Jan-2009 : Added alpha transparency field and hashCode() method (DG);
* 17-Jun-2012 : Removed JCommon dependencies (DG);
*
*/
package org.jfree.chart.renderer;
import java.awt.Color;
import java.awt.Paint;
import java.io.Serializable;
import org.jfree.chart.HashUtilities;
import org.jfree.chart.util.PublicCloneable;
/**
* A paint scale that returns shades of gray.
*
* @since 1.0.4
*/
public class GrayPaintScale implements PaintScale, PublicCloneable,
Serializable {
/** The lower bound. */
private double lowerBound;
/** The upper bound. */
private double upperBound;
/**
* The alpha transparency (0-255).
*
* @since 1.0.13
*/
private int alpha;
/** Cache of shades. */
private Color[] shades = new Color[256];
/**
* Creates a new <code>GrayPaintScale</code> instance with default values.
*/
public GrayPaintScale() {
this(0.0, 1.0);
}
/**
* Creates a new paint scale for values in the specified range.
*
* @param lowerBound the lower bound.
* @param upperBound the upper bound.
*
* @throws IllegalArgumentException if <code>lowerBound</code> is not
* less than <code>upperBound</code>.
*/
public GrayPaintScale(double lowerBound, double upperBound) {
this(lowerBound, upperBound, 255);
}
/**
* Creates a new paint scale for values in the specified range.
*
* @param lowerBound the lower bound.
* @param upperBound the upper bound.
* @param alpha the alpha transparency (0-255).
*
* @throws IllegalArgumentException if <code>lowerBound</code> is not
* less than <code>upperBound</code>, or <code>alpha</code> is not in
* the range 0 to 255.
*
* @since 1.0.13
*/
public GrayPaintScale(double lowerBound, double upperBound, int alpha) {
if (lowerBound >= upperBound) {
throw new IllegalArgumentException(
"Requires lowerBound < upperBound.");
}
if (alpha < 0 || alpha > 255) {
throw new IllegalArgumentException(
"Requires alpha in the range 0 to 255.");
}
this.lowerBound = lowerBound;
this.upperBound = upperBound;
this.alpha = alpha;
}
/**
* Returns the lower bound.
*
* @return The lower bound.
*
* @see #getUpperBound()
*/
@Override
public double getLowerBound() {
return this.lowerBound;
}
/**
* Returns the upper bound.
*
* @return The upper bound.
*
* @see #getLowerBound()
*/
@Override
public double getUpperBound() {
return this.upperBound;
}
/**
* Returns the alpha transparency that was specified in the constructor.
*
* @return The alpha transparency (in the range 0 to 255).
*
* @since 1.0.13
*/
public int getAlpha() {
return this.alpha;
}
/**
* Returns a paint for the specified value.
*
* @param value the value (must be within the range specified by the
* lower and upper bounds for the scale).
*
* @return A paint for the specified value.
*/
@Override
public Paint getPaint(double value) {
double v = Math.max(value, this.lowerBound);
v = Math.min(v, this.upperBound);
int g = (int) ((v - this.lowerBound) / (this.upperBound
- this.lowerBound) * 255.0);
if (this.shades[g] == null) {
this.shades[g] = new Color(g, g, g, this.alpha);
}
return this.shades[g];
}
/**
* Tests this <code>GrayPaintScale</code> instance for equality with an
* arbitrary object. This method returns <code>true</code> if and only
* if:
* <ul>
* <li><code>obj</code> is not <code>null</code>;</li>
* <li><code>obj</code> is an instance of <code>GrayPaintScale</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 GrayPaintScale)) {
return false;
}
GrayPaintScale that = (GrayPaintScale) obj;
if (this.lowerBound != that.lowerBound) {
return false;
}
if (this.upperBound != that.upperBound) {
return false;
}
if (this.alpha != that.alpha) {
return false;
}
return true;
}
/**
* Returns a hash code for this instance.
*
* @return A hash code.
*/
@Override
public int hashCode() {
int hash = 7;
hash = HashUtilities.hashCode(hash, this.lowerBound);
hash = HashUtilities.hashCode(hash, this.upperBound);
hash = 43 * hash + this.alpha;
return hash;
}
/**
* Returns a clone of this <code>GrayPaintScale</code> instance.
*
* @return A clone.
*
* @throws CloneNotSupportedException if there is a problem cloning this
* instance.
*/
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
| 6,972 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
DefaultPolarItemRenderer.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/renderer/DefaultPolarItemRenderer.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.]
*
* -----------------------------
* DefaultPolarItemRenderer.java
* -----------------------------
* (C) Copyright 2004-2013, by Solution Engineering, Inc. and
* Contributors.
*
* Original Author: Daniel Bridenbecker, Solution Engineering, Inc.;
* Contributor(s): David Gilbert (for Object Refinery Limited);
* Martin Hoeller (patch 2850344);
*
* Changes
* -------
* 19-Jan-2004 : Version 1, contributed by DB with minor changes by DG (DG);
* 15-Jul-2004 : Switched getX() with getXValue() and getY() with
* getYValue() (DG);
* 04-Oct-2004 : Renamed BooleanUtils --> BooleanUtilities (DG);
* 20-Apr-2005 : Update for change to LegendItem class (DG);
* ------------- JFREECHART 1.0.x ---------------------------------------------
* 04-Aug-2006 : Implemented equals() and clone() (DG);
* 02-Feb-2007 : Removed author tags from all over JFreeChart sources (DG);
* 14-Mar-2007 : Fixed clone() method (DG);
* 04-May-2007 : Fixed lookup for series paint and stroke (DG);
* 18-May-2007 : Set dataset for LegendItem (DG);
* 03-Sep-2009 : Applied patch 2850344 by Martin Hoeller (DG);
* 27-Nov-2009 : Updated for modification to PolarItemRenderer interface (DG);
* 03-Oct-2011 : Fixed potential NPE in equals() (MH);
* 03-Oct-2011 : Added flag to connectFirstAndLastPoint (MH);
* 03-Oct-2011 : Added tooltip and URL generator support (MH);
* 03-Oct-2011 : Added some configuration options for the legend (MH);
* 03-Oct-2011 : Added support for PolarPlot's angleOffset and direction (MH);
* 16-Oct-2011 : Fixed serialization problems with fillComposite (MH);
* 15-Jun-2012 : Remove JCommon dependencies (DG);
*
*/
package org.jfree.chart.renderer;
import java.awt.AlphaComposite;
import java.awt.Composite;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.Point;
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.PathIterator;
import java.awt.geom.Rectangle2D;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.List;
import org.jfree.chart.LegendItem;
import org.jfree.chart.axis.NumberTick;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.axis.ValueTick;
import org.jfree.chart.util.BooleanList;
import org.jfree.chart.util.ObjectList;
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.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.DrawingSupplier;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.PlotRenderingInfo;
import org.jfree.chart.plot.PolarPlot;
import org.jfree.chart.renderer.xy.AbstractXYItemRenderer;
import org.jfree.chart.text.TextUtilities;
import org.jfree.chart.urls.XYURLGenerator;
import org.jfree.chart.util.ParamChecks;
import org.jfree.chart.util.SerialUtilities;
import org.jfree.data.xy.XYDataset;
/**
* A renderer that can be used with the {@link PolarPlot} class.
*/
public class DefaultPolarItemRenderer extends AbstractRenderer
implements PolarItemRenderer {
private static final long serialVersionUID = 1L;
/** The plot that the renderer is assigned to. */
private PolarPlot plot;
/** Flags that control whether the renderer fills each series or not. */
private BooleanList seriesFilled;
/**
* Flag that controls whether an outline is drawn for filled series or
* not.
*
* @since 1.0.14
*/
private boolean drawOutlineWhenFilled;
/**
* The composite to use when filling series.
*
* @since 1.0.14
*/
private transient Composite fillComposite;
/**
* A flag that controls whether the fill paint is used for filling
* shapes.
*
* @since 1.0.14
*/
private boolean useFillPaint;
/**
* The shape that is used to represent a line in the legend.
*
* @since 1.0.14
*/
private transient Shape legendLine;
/**
* Flag that controls whether item shapes are visible or not.
*
* @since 1.0.14
*/
private boolean shapesVisible;
/**
* Flag that controls if the first and last point of the dataset should be
* connected or not.
*
* @since 1.0.14
*/
private boolean connectFirstAndLastPoint;
/**
* A list of tool tip generators (one per series).
*
* @since 1.0.14
*/
private ObjectList<XYToolTipGenerator> toolTipGeneratorList;
/**
* The base tool tip generator.
*
* @since 1.0.14
*/
private XYToolTipGenerator baseToolTipGenerator;
/**
* The URL text generator.
*
* @since 1.0.14
*/
private XYURLGenerator urlGenerator;
/**
* The legend item tool tip generator.
*
* @since 1.0.14
*/
private XYSeriesLabelGenerator legendItemToolTipGenerator;
/**
* The legend item URL generator.
*
* @since 1.0.14
*/
private XYSeriesLabelGenerator legendItemURLGenerator;
/**
* Creates a new instance of DefaultPolarItemRenderer
*/
public DefaultPolarItemRenderer() {
this.seriesFilled = new BooleanList();
this.drawOutlineWhenFilled = true;
this.fillComposite = AlphaComposite.getInstance(
AlphaComposite.SRC_OVER, 0.3f);
this.useFillPaint = false; // use item paint for fills by default
this.legendLine = new Line2D.Double(-7.0, 0.0, 7.0, 0.0);
this.shapesVisible = true;
this.connectFirstAndLastPoint = true;
this.toolTipGeneratorList = new ObjectList<XYToolTipGenerator>();
this.urlGenerator = null;
this.legendItemToolTipGenerator = null;
this.legendItemURLGenerator = null;
}
/**
* Set the plot associated with this renderer.
*
* @param plot the plot.
*
* @see #getPlot()
*/
@Override
public void setPlot(PolarPlot plot) {
this.plot = plot;
}
/**
* Return the plot associated with this renderer.
*
* @return The plot.
*
* @see #setPlot(PolarPlot)
*/
@Override
public PolarPlot getPlot() {
return this.plot;
}
/**
* Returns <code>true</code> if the renderer will draw an outline around
* a filled polygon, <code>false</code> otherwise.
*
* @return A boolean.
*
* @since 1.0.14
*/
public boolean getDrawOutlineWhenFilled() {
return this.drawOutlineWhenFilled;
}
/**
* Set the flag that controls whether the outline around a filled
* polygon will be drawn or not and sends a {@link RendererChangeEvent}
* to all registered listeners.
*
* @param drawOutlineWhenFilled the flag.
*
* @since 1.0.14
*/
public void setDrawOutlineWhenFilled(boolean drawOutlineWhenFilled) {
this.drawOutlineWhenFilled = drawOutlineWhenFilled;
fireChangeEvent();
}
/**
* Get the composite that is used for filling.
*
* @return The composite (never <code>null</code>).
*
* @since 1.0.14
*/
public Composite getFillComposite() {
return this.fillComposite;
}
/**
* Sets the composite which will be used for filling polygons and sends a
* {@link RendererChangeEvent} to all registered listeners.
*
* @param composite the composite to use (<code>null</code> not
* permitted).
*
* @since 1.0.14
*/
public void setFillComposite(Composite composite) {
ParamChecks.nullNotPermitted(composite, "composite");
this.fillComposite = composite;
fireChangeEvent();
}
/**
* Returns <code>true</code> if a shape will be drawn for every item, or
* <code>false</code> if not.
*
* @return A boolean.
*
* @since 1.0.14
*/
public boolean getShapesVisible() {
return this.shapesVisible;
}
/**
* Set the flag that controls whether a shape will be drawn for every
* item, or not and sends a {@link RendererChangeEvent} to all registered
* listeners.
*
* @param visible the flag.
*
* @since 1.0.14
*/
public void setShapesVisible(boolean visible) {
this.shapesVisible = visible;
fireChangeEvent();
}
/**
* Returns <code>true</code> if first and last point of a series will be
* connected, <code>false</code> otherwise.
*
* @return The current status of the flag.
*
* @since 1.0.14
*/
public boolean getConnectFirstAndLastPoint() {
return this.connectFirstAndLastPoint;
}
/**
* Set the flag that controls whether the first and last point of a series
* will be connected or not and sends a {@link RendererChangeEvent} to all
* registered listeners.
*
* @param connect the flag.
*
* @since 1.0.14
*/
public void setConnectFirstAndLastPoint(boolean connect) {
this.connectFirstAndLastPoint = connect;
fireChangeEvent();
}
/**
* Returns the drawing supplier from the plot.
*
* @return The drawing supplier.
*/
@Override
public DrawingSupplier getDrawingSupplier() {
DrawingSupplier result = null;
PolarPlot p = getPlot();
if (p != null) {
result = p.getDrawingSupplier();
}
return result;
}
/**
* Returns <code>true</code> if the renderer should fill the specified
* series, and <code>false</code> otherwise.
*
* @param series the series index (zero-based).
*
* @return A boolean.
*/
public boolean isSeriesFilled(int series) {
boolean result = false;
Boolean b = this.seriesFilled.getBoolean(series);
if (b != null) {
result = b;
}
return result;
}
/**
* Sets a flag that controls whether or not a series is filled.
*
* @param series the series index.
* @param filled the flag.
*/
public void setSeriesFilled(int series, boolean filled) {
this.seriesFilled.setBoolean(series, filled);
}
/**
* 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)
* @since 1.0.14
*/
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()
* @since 1.0.14
*/
public void setUseFillPaint(boolean flag) {
this.useFillPaint = 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) {
ParamChecks.nullNotPermitted(line, "line");
this.legendLine = line;
fireChangeEvent();
}
/**
* 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);
}
/**
* Plots the data for a given series.
*
* @param g2 the drawing surface.
* @param dataArea the data area.
* @param info collects plot rendering info.
* @param plot the plot.
* @param dataset the dataset.
* @param seriesIndex the series index.
*/
@Override
public void drawSeries(Graphics2D g2, Rectangle2D dataArea,
PlotRenderingInfo info, PolarPlot plot, XYDataset dataset,
int seriesIndex) {
final int numPoints = dataset.getItemCount(seriesIndex);
if (numPoints == 0) {
return;
}
GeneralPath poly = null;
ValueAxis axis = plot.getAxisForDataset(plot.indexOf(dataset));
for (int i = 0; i < numPoints; i++) {
double theta = dataset.getXValue(seriesIndex, i);
double radius = dataset.getYValue(seriesIndex, i);
Point p = plot.translateToJava2D(theta, radius, axis, dataArea);
if (poly == null) {
poly = new GeneralPath();
poly.moveTo(p.x, p.y);
}
else {
poly.lineTo(p.x, p.y);
}
}
if (getConnectFirstAndLastPoint()) {
poly.closePath();
}
g2.setPaint(lookupSeriesPaint(seriesIndex));
g2.setStroke(lookupSeriesStroke(seriesIndex));
if (isSeriesFilled(seriesIndex)) {
Composite savedComposite = g2.getComposite();
g2.setComposite(this.fillComposite);
g2.fill(poly);
g2.setComposite(savedComposite);
if (this.drawOutlineWhenFilled) {
// draw the outline of the filled polygon
g2.setPaint(lookupSeriesOutlinePaint(seriesIndex));
g2.draw(poly);
}
}
else {
// just the lines, no filling
g2.draw(poly);
}
// draw the item shapes
if (this.shapesVisible) {
// setup for collecting optional entity info...
EntityCollection entities = null;
if (info != null) {
entities = info.getOwner().getEntityCollection();
}
PathIterator pi = poly.getPathIterator(null);
int i = 0;
while (!pi.isDone()) {
final float[] coords = new float[6];
final int segType = pi.currentSegment(coords);
pi.next();
if (segType != PathIterator.SEG_LINETO &&
segType != PathIterator.SEG_MOVETO) {
continue;
}
final int x = Math.round(coords[0]);
final int y = Math.round(coords[1]);
final Shape shape = ShapeUtilities.createTranslatedShape(
getItemShape(seriesIndex, i++), x, y);
Paint paint;
if (useFillPaint) {
paint = lookupSeriesFillPaint(seriesIndex);
}
else {
paint = lookupSeriesPaint(seriesIndex);
}
g2.setPaint(paint);
g2.fill(shape);
if (isSeriesFilled(seriesIndex) && this.drawOutlineWhenFilled) {
g2.setPaint(lookupSeriesOutlinePaint(seriesIndex));
g2.setStroke(lookupSeriesOutlineStroke(seriesIndex));
g2.draw(shape);
}
// add an entity for the item, but only if it falls within the
// data area...
if (entities != null &&
AbstractXYItemRenderer.isPointInRect(dataArea, x, y)) {
addEntity(entities, shape, dataset, seriesIndex, i-1, x, y);
}
}
}
}
/**
* Draw the angular gridlines - the spokes.
*
* @param g2 the drawing surface.
* @param plot the plot (<code>null</code> not permitted).
* @param ticks the ticks (<code>null</code> not permitted).
* @param dataArea the data area.
*/
@Override
public void drawAngularGridLines(Graphics2D g2, PolarPlot plot,
List<ValueTick> ticks, Rectangle2D dataArea) {
g2.setFont(plot.getAngleLabelFont());
g2.setStroke(plot.getAngleGridlineStroke());
g2.setPaint(plot.getAngleGridlinePaint());
ValueAxis axis = plot.getAxis();
double centerValue, outerValue;
if (axis.isInverted()) {
outerValue = axis.getLowerBound();
centerValue = axis.getUpperBound();
} else {
outerValue = axis.getUpperBound();
centerValue = axis.getLowerBound();
}
Point center = plot.translateToJava2D(0, centerValue, axis, dataArea);
for (ValueTick tick : ticks) {
double tickVal = tick.getValue();
Point p = plot.translateToJava2D(tickVal, outerValue, plot.getAxis(),
dataArea);
g2.setPaint(plot.getAngleGridlinePaint());
g2.drawLine(center.x, center.y, p.x, p.y);
if (plot.isAngleLabelsVisible()) {
int x = p.x;
int y = p.y;
g2.setPaint(plot.getAngleLabelPaint());
TextUtilities.drawAlignedString(tick.getText(), g2, x, y,
tick.getTextAnchor());
}
}
}
/**
* Draw the radial gridlines - the rings.
*
* @param g2 the drawing surface (<code>null</code> not permitted).
* @param plot the plot (<code>null</code> not permitted).
* @param radialAxis the radial axis (<code>null</code> not permitted).
* @param ticks the ticks (<code>null</code> not permitted).
* @param dataArea the data area.
*/
@Override
public void drawRadialGridLines(Graphics2D g2, PolarPlot plot,
ValueAxis radialAxis, List<ValueTick> ticks, Rectangle2D dataArea) {
ParamChecks.nullNotPermitted(radialAxis, "radialAxis");
g2.setFont(radialAxis.getTickLabelFont());
g2.setPaint(plot.getRadiusGridlinePaint());
g2.setStroke(plot.getRadiusGridlineStroke());
double centerValue;
if (radialAxis.isInverted()) {
centerValue = radialAxis.getUpperBound();
} else {
centerValue = radialAxis.getLowerBound();
}
Point center = plot.translateToJava2D(0, centerValue, radialAxis, dataArea);
for (ValueTick tick : ticks) {
double angleDegrees = plot.isCounterClockwise()
? plot.getAngleOffset() : -plot.getAngleOffset();
Point p = plot.translateToJava2D(angleDegrees,
((NumberTick)tick).getNumber().doubleValue(), radialAxis, dataArea);
int r = p.x - center.x;
int upperLeftX = center.x - r;
int upperLeftY = center.y - r;
int d = 2 * r;
Ellipse2D ring = new Ellipse2D.Double(upperLeftX, upperLeftY, d, d);
g2.setPaint(plot.getRadiusGridlinePaint());
g2.draw(ring);
}
}
/**
* Return the legend for the given series.
*
* @param series the series index.
*
* @return The legend item.
*/
@Override
public LegendItem getLegendItem(int series) {
LegendItem result;
PolarPlot plot = getPlot();
if (plot == null) {
return null;
}
XYDataset dataset = plot.getDataset(plot.getIndexOf(this));
if (dataset == null) {
return null;
}
String toolTipText = null;
if (getLegendItemToolTipGenerator() != null) {
toolTipText = getLegendItemToolTipGenerator().generateLabel(
dataset, series);
}
String urlText = null;
if (getLegendItemURLGenerator() != null) {
urlText = getLegendItemURLGenerator().generateLabel(dataset,
series);
}
Comparable seriesKey = dataset.getSeriesKey(series);
String label = seriesKey.toString();
String description = label;
Shape shape = lookupSeriesShape(series);
Paint paint;
if (this.useFillPaint) {
paint = lookupSeriesFillPaint(series);
}
else {
paint = lookupSeriesPaint(series);
}
Stroke stroke = lookupSeriesStroke(series);
Paint outlinePaint = lookupSeriesOutlinePaint(series);
Stroke outlineStroke = lookupSeriesOutlineStroke(series);
boolean shapeOutlined = isSeriesFilled(series)
&& this.drawOutlineWhenFilled;
result = new LegendItem(label, description, toolTipText, urlText,
getShapesVisible(), shape, /* shapeFilled=*/ true, paint,
shapeOutlined, outlinePaint, outlineStroke,
/* lineVisible= */ true, this.legendLine, stroke, paint);
result.setToolTipText(toolTipText);
result.setURLText(urlText);
result.setDataset(dataset);
result.setSeriesKey(seriesKey);
result.setSeriesIndex(series);
return result;
}
/**
* Returns the tooltip generator for the specified series and item.
*
* @param series the series index.
* @param item the item index.
*
* @return The tooltip generator (possibly <code>null</code>).
*
* @since 1.0.14
*/
@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 the specified series.
*
* @return The tooltip generator (possibly <code>null</code>).
*
* @since 1.0.14
*/
@Override
public XYToolTipGenerator getSeriesToolTipGenerator(int series) {
return this.toolTipGeneratorList.get(series);
}
/**
* Sets the tooltip generator for the specified series.
*
* @param series the series index.
* @param generator the tool tip generator (<code>null</code> permitted).
*
* @since 1.0.14
*/
@Override
public void setSeriesToolTipGenerator(int series,
XYToolTipGenerator generator) {
this.toolTipGeneratorList.set(series, generator);
fireChangeEvent();
}
/**
* Returns the default tool tip generator.
*
* @return The default tool tip generator (possibly <code>null</code>).
*
* @since 1.0.14
*/
@Override
public XYToolTipGenerator getBaseToolTipGenerator() {
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).
*
* @since 1.0.14
*/
@Override
public void setBaseToolTipGenerator(XYToolTipGenerator generator) {
this.baseToolTipGenerator = generator;
fireChangeEvent();
}
/**
* Returns the URL generator.
*
* @return The URL generator (possibly <code>null</code>).
*
* @since 1.0.14
*/
@Override
public XYURLGenerator getURLGenerator() {
return this.urlGenerator;
}
/**
* Sets the URL generator.
*
* @param urlGenerator the generator (<code>null</code> permitted)
*
* @since 1.0.14
*/
@Override
public void setURLGenerator(XYURLGenerator urlGenerator) {
this.urlGenerator = urlGenerator;
fireChangeEvent();
}
/**
* Returns the legend item tool tip generator.
*
* @return The tool tip generator (possibly <code>null</code>).
*
* @see #setLegendItemToolTipGenerator(XYSeriesLabelGenerator)
* @since 1.0.14
*/
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()
* @since 1.0.14
*/
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)
* @since 1.0.14
*/
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()
* @since 1.0.14
*/
public void setLegendItemURLGenerator(XYSeriesLabelGenerator generator) {
this.legendItemURLGenerator = generator;
fireChangeEvent();
}
/**
* Tests this renderer for equality with an arbitrary object.
*
* @param obj the object (<code>null</code> not permitted).
*
* @return <code>true</code> if this renderer is equal to <code>obj</code>,
* and <code>false</code> otherwise.
*/
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (!(obj instanceof DefaultPolarItemRenderer)) {
return false;
}
DefaultPolarItemRenderer that = (DefaultPolarItemRenderer) obj;
if (!this.seriesFilled.equals(that.seriesFilled)) {
return false;
}
if (this.drawOutlineWhenFilled != that.drawOutlineWhenFilled) {
return false;
}
if (!ObjectUtilities.equal(this.fillComposite, that.fillComposite)) {
return false;
}
if (this.useFillPaint != that.useFillPaint) {
return false;
}
if (!ShapeUtilities.equal(this.legendLine, that.legendLine)) {
return false;
}
if (this.shapesVisible != that.shapesVisible) {
return false;
}
if (this.connectFirstAndLastPoint != that.connectFirstAndLastPoint) {
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 (!ObjectUtilities.equal(this.legendItemToolTipGenerator,
that.legendItemToolTipGenerator)) {
return false;
}
if (!ObjectUtilities.equal(this.legendItemURLGenerator,
that.legendItemURLGenerator)) {
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 {
DefaultPolarItemRenderer clone
= (DefaultPolarItemRenderer) super.clone();
if (this.legendLine != null) {
clone.legendLine = ShapeUtilities.clone(this.legendLine);
}
clone.seriesFilled = (BooleanList) this.seriesFilled.clone();
clone.toolTipGeneratorList
= (ObjectList<XYToolTipGenerator>) this.toolTipGeneratorList.clone();
if (clone.baseToolTipGenerator instanceof PublicCloneable) {
clone.baseToolTipGenerator = ObjectUtilities.clone(this.baseToolTipGenerator);
}
if (clone.urlGenerator instanceof PublicCloneable) {
clone.urlGenerator = ObjectUtilities.clone(this.urlGenerator);
}
if (clone.legendItemToolTipGenerator instanceof PublicCloneable) {
clone.legendItemToolTipGenerator = ObjectUtilities.clone(this.legendItemToolTipGenerator);
}
if (clone.legendItemURLGenerator instanceof PublicCloneable) {
clone.legendItemURLGenerator = ObjectUtilities.clone(this.legendItemURLGenerator);
}
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.legendLine = SerialUtilities.readShape(stream);
this.fillComposite = SerialUtilities.readComposite(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);
SerialUtilities.writeComposite(this.fillComposite, stream);
}
}
| 32,725 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
PolarItemRenderer.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/renderer/PolarItemRenderer.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.]
*
* ----------------------
* PolarItemRenderer.java
* ----------------------
* (C) Copyright 2004-2011, by Solution Engineering, Inc. and Contributors.
*
* Original Author: Daniel Bridenbecker, Solution Engineering, Inc.;
* Contributor(s): David Gilbert (for Object Refinery Limited);
*
* Changes
* -------
* 19-Jan-2004 : Version 1, contributed by DB with minor changes by DG (DG);
* 03-Oct-2011 : Added tooltip and URL generator support (MH);
*
*/
package org.jfree.chart.renderer;
import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;
import java.util.List;
import org.jfree.chart.LegendItem;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.axis.ValueTick;
import org.jfree.chart.event.RendererChangeEvent;
import org.jfree.chart.event.RendererChangeListener;
import org.jfree.chart.labels.XYToolTipGenerator;
import org.jfree.chart.plot.PlotRenderingInfo;
import org.jfree.chart.plot.PolarPlot;
import org.jfree.chart.urls.XYURLGenerator;
import org.jfree.data.xy.XYDataset;
/**
* The interface for a renderer that can be used by the {@link PolarPlot}
* class.
*/
public interface PolarItemRenderer {
/**
* Plots the data for a given series.
*
* @param g2 the drawing surface.
* @param dataArea the data area.
* @param info collects plot rendering info.
* @param plot the plot.
* @param dataset the dataset.
* @param seriesIndex the series index.
*/
public void drawSeries(Graphics2D g2, Rectangle2D dataArea,
PlotRenderingInfo info, PolarPlot plot, XYDataset dataset,
int seriesIndex);
/**
* Draw the angular gridlines - the spokes.
*
* @param g2 the drawing surface.
* @param plot the plot.
* @param ticks the ticks.
* @param dataArea the data area.
*/
public void drawAngularGridLines(Graphics2D g2, PolarPlot plot,
List<ValueTick> ticks, Rectangle2D dataArea);
/**
* Draw the radial gridlines - the rings.
*
* @param g2 the drawing surface.
* @param plot the plot.
* @param radialAxis the radial axis.
* @param ticks the ticks.
* @param dataArea the data area.
*/
public void drawRadialGridLines(Graphics2D g2, PolarPlot plot,
ValueAxis radialAxis, List<ValueTick> ticks, Rectangle2D dataArea);
/**
* Return the legend for the given series.
*
* @param series the series index.
*
* @return The legend item.
*/
public LegendItem getLegendItem(int series);
/**
* Returns the plot that this renderer has been assigned to.
*
* @return The plot.
*/
public PolarPlot getPlot();
/**
* Sets the plot that this renderer is assigned to. This method will be
* called by the plot class...you do not need to call it yourself.
*
* @param plot the plot.
*/
public void setPlot(PolarPlot plot);
/**
* Adds a change listener.
*
* @param listener the listener.
*/
public void addChangeListener(RendererChangeListener listener);
/**
* Removes a change listener.
*
* @param listener the listener.
*/
public void removeChangeListener(RendererChangeListener listener);
//// TOOL TIP GENERATOR ///////////////////////////////////////////////////
/**
* Returns the tool tip generator for a data item.
*
* @param row the row index (zero based).
* @param column the column index (zero based).
*
* @return The generator (possibly <code>null</code>).
*
* @since 1.0.14
*/
public XYToolTipGenerator getToolTipGenerator(int row, int column);
/**
* Returns the tool tip generator for a series.
*
* @param series the series index (zero based).
*
* @return The generator (possibly <code>null</code>).
*
* @see #setSeriesToolTipGenerator(int, XYToolTipGenerator)
*
* @since 1.0.14
*/
public XYToolTipGenerator getSeriesToolTipGenerator(int 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)
*
* @since 1.0.14
*/
public void setSeriesToolTipGenerator(int series,
XYToolTipGenerator generator);
/**
* Returns the base tool tip generator.
*
* @return The generator (possibly <code>null</code>).
*
* @see #setBaseToolTipGenerator(XYToolTipGenerator)
*
* @since 1.0.14
*/
public XYToolTipGenerator getBaseToolTipGenerator();
/**
* Sets the base tool tip generator and sends a {@link RendererChangeEvent}
* to all registered listeners.
*
* @param generator the generator (<code>null</code> permitted).
*
* @see #getBaseToolTipGenerator()
*
* @since 1.0.14
*/
public void setBaseToolTipGenerator(XYToolTipGenerator generator);
//// URL GENERATOR ////////////////////////////////////////////////////////
/**
* Returns the URL generator for HTML image maps.
*
* @return The URL generator (possibly null).
*
* @since 1.0.14
*/
public XYURLGenerator getURLGenerator();
/**
* Sets the URL generator for HTML image maps.
*
* @param urlGenerator the URL generator (null permitted).
*
* @since 1.0.14
*/
public void setURLGenerator(XYURLGenerator urlGenerator);
}
| 6,910 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
WaferMapRenderer.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/renderer/WaferMapRenderer.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.]
*
* ---------------------
* WaferMapRenderer.java
* ---------------------
* (C) Copyright 2003-2014, by Robert Redburn and Contributors.
*
* Original Author: Robert Redburn;
* Contributor(s): David Gilbert (for Object Refinery Limited);
*
* Changes
* -------
* 25-Nov-2003 : Version 1, contributed by Robert Redburn. Changes have been
* made to fit the JFreeChart coding style (DG);
* 20-Apr-2005 : Small update for changes to LegendItem class (DG);
* ------------- JFREECHART 1.0.x ---------------------------------------------
* 02-Feb-2007 : Removed author tags from all over JFreeChart sources (DG);
* 10-Mar-2014 : Removed LegendItemCollection (DG);
*
*/
package org.jfree.chart.renderer;
import java.awt.Color;
import java.awt.Paint;
import java.awt.Shape;
import java.awt.Stroke;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.jfree.chart.LegendItem;
import org.jfree.chart.plot.DrawingSupplier;
import org.jfree.chart.plot.WaferMapPlot;
import org.jfree.data.general.WaferMapDataset;
/**
* A renderer for wafer map plots. Provides color management facilities.
*/
public class WaferMapRenderer extends AbstractRenderer {
/** paint index */
private Map<Number, Integer> paintIndex;
/** plot */
private WaferMapPlot plot;
/** paint limit */
private int paintLimit;
/** default paint limit */
private static final int DEFAULT_PAINT_LIMIT = 35;
/** default multivalue paint calculation */
public static final int POSITION_INDEX = 0;
/** The default value index. */
public static final int VALUE_INDEX = 1;
/** paint index method */
private int paintIndexMethod;
/**
* Creates a new renderer.
*/
public WaferMapRenderer() {
this(null, null);
}
/**
* Creates a new renderer.
*
* @param paintLimit the paint limit.
* @param paintIndexMethod the paint index method.
*/
public WaferMapRenderer(Integer paintLimit, Integer paintIndexMethod) {
super();
this.paintIndex = new HashMap<Number, Integer>();
if (paintLimit == null) {
this.paintLimit = DEFAULT_PAINT_LIMIT;
}
else {
this.paintLimit = paintLimit;
}
this.paintIndexMethod = VALUE_INDEX;
if (paintIndexMethod != null) {
if (isMethodValid(paintIndexMethod)) {
this.paintIndexMethod = paintIndexMethod;
}
}
}
/**
* Verifies that the passed paint index method is valid.
*
* @param method the method.
*
* @return <code>true</code> or </code>false</code>.
*/
private boolean isMethodValid(int method) {
switch (method) {
case POSITION_INDEX: return true;
case VALUE_INDEX: return true;
default: return false;
}
}
/**
* Returns the drawing supplier from the plot.
*
* @return The drawing supplier.
*/
@Override
public DrawingSupplier getDrawingSupplier() {
DrawingSupplier result = null;
WaferMapPlot p = getPlot();
if (p != null) {
result = p.getDrawingSupplier();
}
return result;
}
/**
* Returns the plot.
*
* @return The plot.
*/
public WaferMapPlot getPlot() {
return this.plot;
}
/**
* Sets the plot and build the paint index.
*
* @param plot the plot.
*/
public void setPlot(WaferMapPlot plot) {
this.plot = plot;
makePaintIndex();
}
/**
* Returns the paint for a given chip value.
*
* @param value the value.
*
* @return The paint.
*/
public Paint getChipColor(Number value) {
return getSeriesPaint(getPaintIndex(value));
}
/**
* Returns the paint index for a given chip value.
*
* @param value the value.
*
* @return The paint index.
*/
private int getPaintIndex(Number value) {
return this.paintIndex.get(value);
}
/**
* Builds a map of chip values to paint colors.
* paintlimit is the maximum allowed number of colors.
*/
private void makePaintIndex() {
if (this.plot == null) {
return;
}
WaferMapDataset data = this.plot.getDataset();
Number dataMin = data.getMinValue();
Number dataMax = data.getMaxValue();
Set<Number> uniqueValues = data.getUniqueValues();
if (uniqueValues.size() <= this.paintLimit) {
int count = 0; // assign a color for each unique value
for (Number uniqueValue : uniqueValues) {
this.paintIndex.put(uniqueValue, count++);
}
}
else {
// more values than paints so map
// multiple values to the same color
switch (this.paintIndexMethod) {
case POSITION_INDEX:
makePositionIndex(uniqueValues);
break;
case VALUE_INDEX:
makeValueIndex(dataMax, dataMin, uniqueValues);
break;
default:
break;
}
}
}
/**
* Builds the paintindex by assigning colors based on the number
* of unique values: totalvalues/totalcolors.
*
* @param uniqueValues the set of unique values.
*/
private void makePositionIndex(Set<Number> uniqueValues) {
int valuesPerColor = (int) Math.ceil(
(double) uniqueValues.size() / this.paintLimit
);
int count = 0; // assign a color for each unique value
int paint = 0;
for (Number uniqueValue : uniqueValues) {
this.paintIndex.put(uniqueValue, paint);
if (++count % valuesPerColor == 0) {
paint++;
}
if (paint > this.paintLimit) {
paint = this.paintLimit;
}
}
}
/**
* Builds the paintindex by assigning colors evenly across the range
* of values: maxValue-minValue/totalcolors
*
* @param max the maximum value.
* @param min the minumum value.
* @param uniqueValues the unique values.
*/
private void makeValueIndex(Number max, Number min, Set<Number> uniqueValues) {
double valueRange = max.doubleValue() - min.doubleValue();
double valueStep = valueRange / this.paintLimit;
int paint = 0;
double cutPoint = min.doubleValue() + valueStep;
for (Number value : uniqueValues) {
while (value.doubleValue() > cutPoint) {
cutPoint += valueStep;
paint++;
if (paint > this.paintLimit) {
paint = this.paintLimit;
}
}
this.paintIndex.put(value, paint);
}
}
/**
* Builds the list of legend entries. called by getLegendItems in
* WaferMapPlot to populate the plot legend.
*
* @return The legend items.
*/
public List<LegendItem> getLegendCollection() {
List<LegendItem> result = new ArrayList<LegendItem>();
if (this.paintIndex != null && this.paintIndex.size() > 0) {
if (this.paintIndex.size() <= this.paintLimit) {
for (Map.Entry<Number, Integer> entry : this.paintIndex.entrySet()) {
// in this case, every color has a unique value
String label = entry.getKey().toString();
String description = label;
Shape shape = new Rectangle2D.Double(1d, 1d, 1d, 1d);
Paint paint = lookupSeriesPaint(
entry.getValue());
Paint outlinePaint = Color.BLACK;
Stroke outlineStroke = DEFAULT_STROKE;
result.add(new LegendItem(label, description, null,
null, shape, paint, outlineStroke, outlinePaint));
}
}
else {
// in this case, every color has a range of values
Set<Integer> unique = new HashSet<Integer>();
for (Map.Entry<Number, Integer> entry : this.paintIndex.entrySet()) {
if (unique.add(entry.getValue())) {
String label = getMinPaintValue(
entry.getValue()).toString()
+ " - " + getMaxPaintValue(
entry.getValue()).toString();
String description = label;
Shape shape = new Rectangle2D.Double(1d, 1d, 1d, 1d);
Paint paint = getSeriesPaint(
entry.getValue()
);
Paint outlinePaint = Color.BLACK;
Stroke outlineStroke = DEFAULT_STROKE;
result.add(new LegendItem(label, description,
null, null, shape, paint, outlineStroke,
outlinePaint));
}
} // end foreach map entry
} // end else
}
return result;
}
/**
* Returns the minimum chip value assigned to a color
* in the paintIndex
*
* @param index the index.
*
* @return The value.
*/
private Number getMinPaintValue(Integer index) {
double minValue = Double.POSITIVE_INFINITY;
for (Map.Entry<Number, Integer> entry : this.paintIndex.entrySet()) {
if (entry.getValue().equals(index)) {
if (entry.getKey().doubleValue() < minValue) {
minValue = entry.getKey().doubleValue();
}
}
}
return minValue;
}
/**
* Returns the maximum chip value assigned to a color
* in the paintIndex
*
* @param index the index.
*
* @return The value
*/
private Number getMaxPaintValue(Integer index) {
double maxValue = Double.NEGATIVE_INFINITY;
for (Map.Entry<Number, Integer> entry : this.paintIndex.entrySet()) {
if (entry.getValue().equals(index)) {
if (entry.getKey().doubleValue() > maxValue) {
maxValue = entry.getKey().doubleValue();
}
}
}
return maxValue;
}
} // end class wafermaprenderer
| 11,911 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
RendererUtilities.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/renderer/RendererUtilities.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.]
*
* ----------------------
* RendererUtilities.java
* ----------------------
* (C) Copyright 2007-2012, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 19-Apr-2007 : Version 1 (DG);
* 27-Mar-2009 : Fixed results for unsorted datasets (DG);
* 19-May-2009 : Fixed FindBugs warnings, patch by Michal Wozniak (DG);
* 23-Aug-2012 : Fixed rendering anomaly bug 3561093 (DG);
*
*/
package org.jfree.chart.renderer;
import org.jfree.data.DomainOrder;
import org.jfree.data.xy.XYDataset;
/**
* Utility methods related to the rendering process.
*
* @since 1.0.6
*/
public class RendererUtilities {
/**
* Finds the lower index of the range of live items in the specified data
* series.
*
* @param dataset the dataset (<code>null</code> not permitted).
* @param series the series index.
* @param xLow the lowest x-value in the live range.
* @param xHigh the highest x-value in the live range.
*
* @return The index of the required item.
*
* @since 1.0.6
*
* @see #findLiveItemsUpperBound(XYDataset, int, double, double)
*/
public static int findLiveItemsLowerBound(XYDataset dataset, int series,
double xLow, double xHigh) {
if (dataset == null) {
throw new IllegalArgumentException("Null 'dataset' argument.");
}
if (xLow >= xHigh) {
throw new IllegalArgumentException("Requires xLow < xHigh.");
}
int itemCount = dataset.getItemCount(series);
if (itemCount <= 1) {
return 0;
}
if (dataset.getDomainOrder() == DomainOrder.ASCENDING) {
// for data in ascending order by x-value, we are (broadly) looking
// for the index of the highest x-value that is less than xLow
int low = 0;
int high = itemCount - 1;
double lowValue = dataset.getXValue(series, low);
if (lowValue >= xLow) {
// special case where the lowest x-value is >= xLow
return low;
}
double highValue = dataset.getXValue(series, high);
if (highValue < xLow) {
// special case where the highest x-value is < xLow
return high;
}
while (high - low > 1) {
int mid = (low + high) / 2;
double midV = dataset.getXValue(series, mid);
if (midV >= xLow) {
high = mid;
}
else {
low = mid;
}
}
return high;
}
else if (dataset.getDomainOrder() == DomainOrder.DESCENDING) {
// when the x-values are sorted in descending order, the lower
// bound is found by calculating relative to the xHigh value
int low = 0;
int high = itemCount - 1;
double lowValue = dataset.getXValue(series, low);
if (lowValue <= xHigh) {
return low;
}
double highValue = dataset.getXValue(series, high);
if (highValue > xHigh) {
return high;
}
while (high - low > 1) {
int mid = (low + high) / 2;
double midV = dataset.getXValue(series, mid);
if (midV > xHigh) {
low = mid;
}
else {
high = mid;
}
}
return high;
}
else {
// we don't know anything about the ordering of the x-values,
// but we can still skip any initial values that fall outside the
// range...
int index = 0;
// skip any items that don't need including...
double x = dataset.getXValue(series, index);
while (index < itemCount && x < xLow) {
index++;
if (index < itemCount) {
x = dataset.getXValue(series, index);
}
}
return Math.min(Math.max(0, index), itemCount - 1);
}
}
/**
* Finds the upper index of the range of live items in the specified data
* series.
*
* @param dataset the dataset (<code>null</code> not permitted).
* @param series the series index.
* @param xLow the lowest x-value in the live range.
* @param xHigh the highest x-value in the live range.
*
* @return The index of the required item.
*
* @since 1.0.6
*
* @see #findLiveItemsLowerBound(XYDataset, int, double, double)
*/
public static int findLiveItemsUpperBound(XYDataset dataset, int series,
double xLow, double xHigh) {
if (dataset == null) {
throw new IllegalArgumentException("Null 'dataset' argument.");
}
if (xLow >= xHigh) {
throw new IllegalArgumentException("Requires xLow < xHigh.");
}
int itemCount = dataset.getItemCount(series);
if (itemCount <= 1) {
return 0;
}
if (dataset.getDomainOrder() == DomainOrder.ASCENDING) {
int low = 0;
int high = itemCount - 1;
double lowValue = dataset.getXValue(series, low);
if (lowValue > xHigh) {
return low;
}
double highValue = dataset.getXValue(series, high);
if (highValue <= xHigh) {
return high;
}
int mid = (low + high) / 2;
while (high - low > 1) {
double midV = dataset.getXValue(series, mid);
if (midV <= xHigh) {
low = mid;
}
else {
high = mid;
}
mid = (low + high) / 2;
}
return mid;
}
else if (dataset.getDomainOrder() == DomainOrder.DESCENDING) {
// when the x-values are descending, the upper bound is found by
// comparing against xLow
int low = 0;
int high = itemCount - 1;
int mid = (low + high) / 2;
double lowValue = dataset.getXValue(series, low);
if (lowValue < xLow) {
return low;
}
double highValue = dataset.getXValue(series, high);
if (highValue >= xLow) {
return high;
}
while (high - low > 1) {
double midV = dataset.getXValue(series, mid);
if (midV >= xLow) {
low = mid;
}
else {
high = mid;
}
mid = (low + high) / 2;
}
return mid;
}
else {
// we don't know anything about the ordering of the x-values,
// but we can still skip any trailing values that fall outside the
// range...
int index = itemCount - 1;
// skip any items that don't need including...
double x = dataset.getXValue(series, index);
while (index >= 0 && x > xHigh) {
index--;
if (index >= 0) {
x = dataset.getXValue(series, index);
}
}
return Math.max(index, 0);
}
}
/**
* Finds a range of item indices that is guaranteed to contain all the
* x-values from x0 to x1 (inclusive).
*
* @param dataset the dataset (<code>null</code> not permitted).
* @param series the series index.
* @param xLow the lower bound of the x-value range.
* @param xHigh the upper bound of the x-value range.
*
* @return The indices of the boundary items.
*/
public static int[] findLiveItems(XYDataset dataset, int series,
double xLow, double xHigh) {
// here we could probably be a little faster by searching for both
// indices simultaneously, but I'll look at that later if it seems
// like it matters...
int i0 = findLiveItemsLowerBound(dataset, series, xLow, xHigh);
int i1 = findLiveItemsUpperBound(dataset, series, xLow, xHigh);
if (i0 > i1) {
i0 = i1;
}
return new int[] {i0, i1};
}
}
| 9,721 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
Outlier.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/renderer/Outlier.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.]
*
* ------------
* Outlier.java
* ------------
* (C) Copyright 2003-2008, 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 (DG);
* 28-Aug-2003 : Minor tidy-up (DG);
* ------------- JFREECHART 1.0.x ---------------------------------------------
* 02-Feb-2007 : Removed author tags from all over JFreeChart sources (DG);
* 21-Nov-2007 : Implemented equals() to shut up FindBugs (DG);
*
*/
package org.jfree.chart.renderer;
import java.awt.geom.Point2D;
/**
* Represents one outlier in the box and whisker plot.
* <P>
* All the coordinates in this class are in Java2D space.
*/
public class Outlier implements Comparable {
/**
* The xy coordinates of the bounding box containing the outlier ellipse.
*/
private Point2D point;
/** The radius of the ellipse */
private double radius;
/**
* Constructs an outlier item consisting of a point and the radius of the
* outlier ellipse
*
* @param xCoord the x coordinate of the point.
* @param yCoord the y coordinate of the point.
* @param radius the radius of the ellipse.
*/
public Outlier(double xCoord, double yCoord, double radius) {
this.point = new Point2D.Double(xCoord - radius, yCoord - radius);
this.radius = radius;
}
/**
* Returns the xy coordinates of the bounding box containing the outlier
* ellipse.
*
* @return The location of the outlier ellipse.
*/
public Point2D getPoint() {
return this.point;
}
/**
* Sets the xy coordinates of the bounding box containing the outlier
* ellipse.
*
* @param point the location.
*/
public void setPoint(Point2D point) {
this.point = point;
}
/**
* Returns the x coordinate of the bounding box containing the outlier
* ellipse.
*
* @return The x coordinate.
*/
public double getX() {
return getPoint().getX();
}
/**
* Returns the y coordinate of the bounding box containing the outlier
* ellipse.
*
* @return The y coordinate.
*/
public double getY() {
return getPoint().getY();
}
/**
* Returns the radius of the outlier ellipse.
*
* @return The radius.
*/
public double getRadius() {
return this.radius;
}
/**
* Sets the radius of the outlier ellipse.
*
* @param radius the new radius.
*/
public void setRadius(double radius) {
this.radius = radius;
}
/**
* Compares this object with the specified object for order, based on
* the outlier's point.
*
* @param o the Object to be compared.
* @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(Object o) {
Outlier outlier = (Outlier) o;
Point2D p1 = getPoint();
Point2D p2 = outlier.getPoint();
if (p1.equals(p2)) {
return 0;
}
else if ((p1.getX() < p2.getX()) || (p1.getY() < p2.getY())) {
return -1;
}
else {
return 1;
}
}
/**
* Returns a true if outlier is overlapped and false if it is not.
* Overlapping is determined by the respective bounding boxes plus
* a small margin.
*
* @param other the other outlier.
*
* @return A <code>boolean</code> indicating whether or not an overlap has
* occurred.
*/
public boolean overlaps(Outlier other) {
return ((other.getX() >= getX() - (this.radius * 1.1))
&& (other.getX() <= getX() + (this.radius * 1.1))
&& (other.getY() >= getY() - (this.radius * 1.1))
&& (other.getY() <= getY() + (this.radius * 1.1)));
}
/**
* Tests this outlier 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 Outlier)) {
return false;
}
Outlier that = (Outlier) obj;
if (!this.point.equals(that.point)) {
return false;
}
if (this.radius != that.radius) {
return false;
}
return true;
}
/**
* Returns a textual representation of the outlier.
*
* @return A <code>String</code> representing the outlier.
*/
@Override
public String toString() {
return "{" + getX() + "," + getY() + "}";
}
}
| 6,202 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
OutlierListCollection.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/renderer/OutlierListCollection.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.]
*
* --------------------------
* OutlierListCollection.java
* --------------------------
* (C) Copyright 2003-2008, by David Browning and Contributors.
*
* Original Author: David Browning (for Australian Institute of Marine
* Science);
* Contributor(s): -;
*
* Changes
* -------
* 05-Aug-2003 : Version 1, contributed by David Browning (DG);
* 01-Sep-2003 : Made storage internal rather than extending ArrayList (DG);
* ------------- JFREECHART 1.0.x ---------------------------------------------
* 02-Feb-2007 : Removed author tags from all over JFreeChart sources (DG);
*
*/
package org.jfree.chart.renderer;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* A collection of outlier lists for a box and whisker plot. Each collection is
* associated with a single box and whisker entity.
*
* Outliers are grouped in lists for each entity. Lists contain
* one or more outliers, determined by whether overlaps have
* occurred. Overlapping outliers are grouped in the same list.
*
* @see org.jfree.chart.renderer.OutlierList
*/
public class OutlierListCollection implements Iterable<OutlierList> {
/** Storage for the outlier lists. */
private List<OutlierList> outlierLists;
/**
* Unbelievably, outliers which are more than 2 * interquartile range are
* called far outs... See Tukey EDA (a classic one of a kind...)
*/
private boolean highFarOut = false;
/**
* A flag that indicates whether or not the collection contains low far
* out values.
*/
private boolean lowFarOut = false;
/**
* Creates a new empty collection.
*/
public OutlierListCollection() {
this.outlierLists = new ArrayList<OutlierList>();
}
/**
* A flag to indicate the presence of one or more far out values at the
* top end of the range.
*
* @return A <code>boolean</code>.
*/
public boolean isHighFarOut() {
return this.highFarOut;
}
/**
* Sets the flag that indicates the presence of one or more far out values
* at the top end of the range.
*
* @param farOut the flag.
*/
public void setHighFarOut(boolean farOut) {
this.highFarOut = farOut;
}
/**
* A flag to indicate the presence of one or more far out values at the
* bottom end of the range.
*
* @return A <code>boolean</code>.
*/
public boolean isLowFarOut() {
return this.lowFarOut;
}
/**
* Sets the flag that indicates the presence of one or more far out values
* at the bottom end of the range.
*
* @param farOut the flag.
*/
public void setLowFarOut(boolean farOut) {
this.lowFarOut = farOut;
}
/**
* Appends the specified element as a new <code>OutlierList</code> to the
* end of this list if it does not overlap an outlier in an existing list.
*
* If it does overlap, it is appended to the outlier list which it overlaps
* and that list is updated.
*
* @param outlier element to be appended to this list.
*
* @return <tt>true</tt> (as per the general contract of Collection.add).
*/
public boolean add(Outlier outlier) {
if (this.outlierLists.isEmpty()) {
return this.outlierLists.add(new OutlierList(outlier));
}
else {
boolean updated = false;
for (OutlierList list : this.outlierLists) {
if (list.isOverlapped(outlier)) {
updated = updateOutlierList(list, outlier);
}
}
if (!updated) {
//System.err.print(" creating new outlier list ");
updated = this.outlierLists.add(new OutlierList(outlier));
}
return updated;
}
}
/**
* Returns an iterator for the outlier lists.
*
* @return An iterator.
*/
public Iterator<OutlierList> iterator() {
return this.outlierLists.iterator();
}
/**
* Updates the outlier list by adding the outlier to the end of the list and
* setting the averaged outlier to the average x and y coordinnate values
* of the outliers in the list.
*
* @param list the outlier list to be updated.
* @param outlier the outlier to be added
*
* @return <tt>true</tt> (as per the general contract of Collection.add).
*/
private boolean updateOutlierList(OutlierList list, Outlier outlier) {
boolean result = list.add(outlier);
list.updateAveragedOutlier();
list.setMultiple(true);
return result;
}
}
| 5,924 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
PaintScale.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/renderer/PaintScale.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.]
*
* ---------------
* PaintScale.java
* ---------------
* (C) Copyright 2006-2008, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 05-Jul-2006 : Version 1 (DG);
* 31-Jan-2007 : Added getLowerBound() and getUpperBound() methods (DG);
*
*/
package org.jfree.chart.renderer;
import java.awt.Paint;
import org.jfree.chart.renderer.xy.XYBlockRenderer;
/**
* A source for <code>Paint</code> instances, used by the
* {@link XYBlockRenderer}.
* <br><br>
* NOTE: Classes that implement this interface should also implement
* <code>PublicCloneable</code> and <code>Serializable</code>, so
* that any renderer (or other object instance) that references an instance of
* this interface can still be cloned or serialized.
*
* @since 1.0.4
*/
public interface PaintScale {
/**
* Returns the lower bound for the scale.
*
* @return The lower bound.
*
* @see #getUpperBound()
*/
public double getLowerBound();
/**
* Returns the upper bound for the scale.
*
* @return The upper bound.
*
* @see #getLowerBound()
*/
public double getUpperBound();
/**
* Returns a <code>Paint</code> instance for the specified value.
*
* @param value the value.
*
* @return A <code>Paint</code> instance (never <code>null</code>).
*/
public Paint getPaint(double value);
}
| 2,698 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
RendererState.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/renderer/RendererState.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.]
*
* ------------------
* RendererState.java
* ------------------
* (C) Copyright 2003-2008, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes:
* --------
* 07-Oct-2003 : Version 1 (DG);
* 09-Jun-2005 : Added a convenience method to access the entity
* collection (DG);
*
*/
package org.jfree.chart.renderer;
import org.jfree.chart.ChartRenderingInfo;
import org.jfree.chart.entity.EntityCollection;
import org.jfree.chart.plot.PlotRenderingInfo;
/**
* Represents the current state of a renderer.
*/
public class RendererState {
/** The plot rendering info. */
private PlotRenderingInfo info;
/**
* Creates a new state object.
*
* @param info the plot rendering info.
*/
public RendererState(PlotRenderingInfo info) {
this.info = info;
}
/**
* Returns the plot rendering info.
*
* @return The info.
*/
public PlotRenderingInfo getInfo() {
return this.info;
}
/**
* A convenience method that returns a reference to the entity
* collection (may be <code>null</code>) being used to record
* chart entities.
*
* @return The entity collection (possibly <code>null</code>).
*/
public EntityCollection getEntityCollection() {
EntityCollection result = null;
if (this.info != null) {
ChartRenderingInfo owner = this.info.getOwner();
if (owner != null) {
result = owner.getEntityCollection();
}
}
return result;
}
}
| 2,862 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
AbstractRenderer.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/renderer/AbstractRenderer.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.]
*
* ---------------------
* AbstractRenderer.java
* ---------------------
* (C) Copyright 2002-2013, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): Nicolas Brodu;
* Michael Zinsmaier;
*
* Changes:
* --------
* 22-Aug-2002 : Version 1, draws code out of AbstractXYItemRenderer to share
* with AbstractCategoryItemRenderer (DG);
* 01-Oct-2002 : Fixed errors reported by Checkstyle (DG);
* 06-Nov-2002 : Moved to the com.jrefinery.chart.renderer package (DG);
* 21-Nov-2002 : Added a paint table for the renderer to use (DG);
* 17-Jan-2003 : Moved plot classes into a separate package (DG);
* 25-Mar-2003 : Implemented Serializable (DG);
* 29-Apr-2003 : Added valueLabelFont and valueLabelPaint attributes, based on
* code from Arnaud Lelievre (DG);
* 29-Jul-2003 : Amended code that doesn't compile with JDK 1.2.2 (DG);
* 13-Aug-2003 : Implemented Cloneable (DG);
* 15-Sep-2003 : Fixed serialization (NB);
* 17-Sep-2003 : Changed ChartRenderingInfo --> PlotRenderingInfo (DG);
* 07-Oct-2003 : Moved PlotRenderingInfo into RendererState to allow for
* multiple threads using a single renderer (DG);
* 20-Oct-2003 : Added missing setOutlinePaint() method (DG);
* 23-Oct-2003 : Split item label attributes into 'positive' and 'negative'
* values (DG);
* 26-Nov-2003 : Added methods to get the positive and negative item label
* positions (DG);
* 01-Mar-2004 : Modified readObject() method to prevent null pointer exceptions
* after deserialization (DG);
* 19-Jul-2004 : Fixed bug in getItemLabelFont(int, int) method (DG);
* 04-Oct-2004 : Updated equals() method, eliminated use of NumberUtils,
* renamed BooleanUtils --> BooleanUtilities, ShapeUtils -->
* ShapeUtilities (DG);
* 15-Mar-2005 : Fixed serialization of baseFillPaint (DG);
* 16-May-2005 : Base outline stroke should never be null (DG);
* 01-Jun-2005 : Added hasListener() method for unit testing (DG);
* 08-Jun-2005 : Fixed equals() method to handle GradientPaint (DG);
* ------------- JFREECHART 1.0.x ---------------------------------------------
* 02-Feb-2007 : Minor API doc update (DG);
* 19-Feb-2007 : Fixes for clone() method (DG);
* 28-Feb-2007 : Use cached event to signal changes (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);
* 13-Jun-2007 : Added new autoPopulate flags for core series attributes (DG);
* 23-Oct-2007 : Updated lookup methods to better handle overridden
* methods (DG);
* 04-Dec-2007 : Modified hashCode() implementation (DG);
* 29-Apr-2008 : Minor API doc update (DG);
* 17-Jun-2008 : Added legendShape, legendTextFont and legendTextPaint
* attributes (DG);
* 18-Aug-2008 : Added clearSeriesPaints() and clearSeriesStrokes() (DG);
* 28-Jan-2009 : Equals method doesn't test Shape equality correctly (DG);
* 27-Mar-2009 : Added dataBoundsIncludesVisibleSeriesOnly attribute, and
* updated renderer events for series visibility changes (DG);
* 01-Apr-2009 : Factored up the defaultEntityRadius field from the
* AbstractXYItemRenderer class (DG);
* 28-Apr-2009 : Added flag to allow a renderer to treat the legend shape as
* a line (DG);
*
*/
package org.jfree.chart.renderer;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
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 java.io.Serializable;
import java.util.Arrays;
import java.util.EventListener;
import java.util.List;
import javax.swing.event.EventListenerList;
import org.jfree.chart.HashUtilities;
import org.jfree.chart.ui.TextAnchor;
import org.jfree.chart.util.BooleanList;
import org.jfree.chart.util.ObjectList;
import org.jfree.chart.util.ObjectUtilities;
import org.jfree.chart.util.PaintList;
import org.jfree.chart.util.PaintUtilities;
import org.jfree.chart.util.ShapeList;
import org.jfree.chart.util.ShapeUtilities;
import org.jfree.chart.util.StrokeList;
import org.jfree.chart.event.RendererChangeEvent;
import org.jfree.chart.event.RendererChangeListener;
import org.jfree.chart.labels.ItemLabelAnchor;
import org.jfree.chart.labels.ItemLabelPosition;
import org.jfree.chart.plot.DrawingSupplier;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.item.DefaultLabelIRS;
import org.jfree.chart.renderer.item.DefaultPaintIRS;
import org.jfree.chart.renderer.item.DefaultShapeIRS;
import org.jfree.chart.renderer.item.DefaultStrokeIRS;
import org.jfree.chart.renderer.item.DefaultVisibilityIRS;
import org.jfree.chart.renderer.item.LabelIRS;
import org.jfree.chart.renderer.item.PaintIRS;
import org.jfree.chart.renderer.item.ShapeIRS;
import org.jfree.chart.renderer.item.StrokeIRS;
import org.jfree.chart.renderer.item.VisibilityIRS;
import org.jfree.chart.title.LegendTitle;
import org.jfree.chart.util.ParamChecks;
import org.jfree.chart.util.SerialUtilities;
/**
* Base class providing common services for renderers. Most methods that update
* attributes of the renderer will fire a {@link RendererChangeEvent}, which
* normally means the plot that owns the renderer will receive notification that
* the renderer has been changed (the plot will, in turn, notify the chart).
*/
public abstract class AbstractRenderer implements Cloneable, Serializable {
/** For serialization. */
private static final long serialVersionUID = -828267569428206075L;
/** Zero represented as a <code>Double</code>. */
public static final Double ZERO = 0.0;
/** The default paint. */
public static final Paint DEFAULT_PAINT = Color.BLUE;
/** The default outline paint. */
public static final Paint DEFAULT_OUTLINE_PAINT = Color.GRAY;
/** The default stroke. */
public static final Stroke DEFAULT_STROKE = new BasicStroke(1.0f);
/** The default outline stroke. */
public static final Stroke DEFAULT_OUTLINE_STROKE = new BasicStroke(1.0f);
/** The default shape. */
public static final Shape DEFAULT_SHAPE
= new Rectangle2D.Double(-3.0, -3.0, 6.0, 6.0);
/** The default value label font. */
public static final Font DEFAULT_VALUE_LABEL_FONT
= new Font("SansSerif", Font.PLAIN, 10);
/** The default value label paint. */
public static final Paint DEFAULT_VALUE_LABEL_PAINT = Color.BLACK;
/**
* A hook that allows to control the rendering of individual item labels
* (if the renderer uses {@link #getItemLabelFont(int, int)} ... )
*/
private LabelIRS labelIRS = new DefaultLabelIRS(this);
/**
* A hook that allows to control the painting of individual items (if the
* renderer uses {@link #getItemPaint(int, int)} ... )
*/
private PaintIRS paintIRS = new DefaultPaintIRS(this);
/**
* A hook that allows to control the shape of individual items
* (if the renderer uses {@link #getItemShape(int, int)} ... )
*/
private ShapeIRS shapeIRS = new DefaultShapeIRS(this);
/**
* A hook that allows to use individual strokes for each item
* (if the renderer uses {@link #getItemStroke(int, int)} ... )
*/
private StrokeIRS strokeIRS = new DefaultStrokeIRS(this);
/**
* A hook that allows to control the visibility of individual items
* (if the renderer uses {@link #getItemVisible(int, int)} ... )
*/
private VisibilityIRS visibilityIRS = new DefaultVisibilityIRS(this);
/** A list of flags that controls whether or not each series is visible. */
private BooleanList seriesVisibleList;
/** The default visibility for all series. */
private boolean defaultSeriesVisible;
/**
* A list of flags that controls whether or not each series is visible in
* the legend.
*/
private BooleanList seriesVisibleInLegendList;
/** The default visibility for each series in the legend. */
private boolean defaultSeriesVisibleInLegend;
/** The paint list. */
private PaintList paintList;
/**
* A flag that controls whether or not the paintList is auto-populated
* in the {@link #lookupSeriesPaint(int)} method.
*
* @since 1.0.6
*/
private boolean autoPopulateSeriesPaint;
/** The base paint. */
private transient Paint defaultPaint;
/** The fill paint list. */
private PaintList fillPaintList;
/**
* A flag that controls whether or not the fillPaintList is auto-populated
* in the {@link #lookupSeriesFillPaint(int)} method.
*
* @since 1.0.6
*/
private boolean autoPopulateSeriesFillPaint;
/** The base fill paint. */
private transient Paint defaultFillPaint;
/** The outline paint list. */
private PaintList outlinePaintList;
/**
* A flag that controls whether or not the outlinePaintList is
* auto-populated in the {@link #lookupSeriesOutlinePaint(int)} method.
*
* @since 1.0.6
*/
private boolean autoPopulateSeriesOutlinePaint;
/** The base outline paint. */
private transient Paint defaultOutlinePaint;
/** The stroke list. */
private StrokeList strokeList;
/**
* A flag that controls whether or not the strokeList is auto-populated
* in the {@link #lookupSeriesStroke(int)} method.
*
* @since 1.0.6
*/
private boolean autoPopulateSeriesStroke;
/** The base stroke. */
private transient Stroke defaultStroke;
/** The outline stroke list. */
private StrokeList outlineStrokeList;
/** The base outline stroke. */
private transient Stroke defaultOutlineStroke;
/**
* A flag that controls whether or not the outlineStrokeList is
* auto-populated in the {@link #lookupSeriesOutlineStroke(int)} method.
*
* @since 1.0.6
*/
private boolean autoPopulateSeriesOutlineStroke;
/** A shape list. */
private ShapeList shapeList;
/**
* A flag that controls whether or not the shapeList is auto-populated
* in the {@link #lookupSeriesShape(int)} method.
*
* @since 1.0.6
*/
private boolean autoPopulateSeriesShape;
/** The base shape. */
private transient Shape defaultShape;
/** Visibility of the item labels PER series. */
private BooleanList itemLabelsVisibleList;
/** The base item labels visible. */
private Boolean defaultItemLabelsVisible;
/** The item label font list (one font per series). */
private ObjectList<Font> itemLabelFontList;
/** The base item label font. */
private Font defaultItemLabelFont;
/** The item label paint list (one paint per series). */
private PaintList itemLabelPaintList;
/** The base item label paint. */
private transient Paint defaultItemLabelPaint;
/** The positive item label position (per series). */
private ObjectList<ItemLabelPosition> positiveItemLabelPositionList;
/** The fallback positive item label position. */
private ItemLabelPosition defaultPositiveItemLabelPosition;
/** The negative item label position (per series). */
private ObjectList<ItemLabelPosition> negativeItemLabelPositionList;
/** The fallback negative item label position. */
private ItemLabelPosition defaultNegativeItemLabelPosition;
/** The item label anchor offset. */
private double itemLabelAnchorOffset = 2.0;
/**
* Flags that control whether or not entities are generated for each
* series. This will be overridden by 'createEntities'.
*/
private BooleanList createEntitiesList;
/**
* The default flag that controls whether or not entities are generated.
* This flag is used when both the above flags return null.
*/
private boolean defaultCreateEntities;
/**
* The per-series legend shape settings.
*
* @since 1.0.11
*/
private ShapeList legendShapeList;
/**
* The base shape for legend items. If this is <code>null</code>, the
* series shape will be used.
*
* @since 1.0.11
*/
private transient Shape defaultLegendShape;
/**
* A special flag that, if true, will cause the getLegendItem() method
* to configure the legend shape as if it were a line.
*
* @since 1.0.14
*/
private boolean treatLegendShapeAsLine;
/**
* The per-series legend text font.
*
* @since 1.0.11
*/
private ObjectList<Font> legendTextFont;
/**
* The base legend font.
*
* @since 1.0.11
*/
private Font defaultLegendTextFont;
/**
* The per series legend text paint settings.
*
* @since 1.0.11
*/
private PaintList legendTextPaint;
/**
* The default paint for the legend text items (if this is
* <code>null</code>, the {@link LegendTitle} class will determine the
* text paint to use.
*
* @since 1.0.11
*/
private transient Paint defaultLegendTextPaint;
/**
* A flag that controls whether or not the renderer will include the
* non-visible series when calculating the data bounds.
*
* @since 1.0.13
*/
private boolean dataBoundsIncludesVisibleSeriesOnly = true;
/** The default radius for the entity 'hotspot' */
private int defaultEntityRadius;
/** Storage for registered change listeners. */
private transient EventListenerList listenerList;
/** An event for re-use. */
private transient RendererChangeEvent event;
/**
* Default constructor.
*/
public AbstractRenderer() {
this.seriesVisibleList = new BooleanList();
this.defaultSeriesVisible = true;
this.seriesVisibleInLegendList = new BooleanList();
this.defaultSeriesVisibleInLegend = true;
this.paintList = new PaintList();
this.defaultPaint = DEFAULT_PAINT;
this.autoPopulateSeriesPaint = true;
this.fillPaintList = new PaintList();
this.defaultFillPaint = Color.WHITE;
this.autoPopulateSeriesFillPaint = false;
this.outlinePaintList = new PaintList();
this.defaultOutlinePaint = DEFAULT_OUTLINE_PAINT;
this.autoPopulateSeriesOutlinePaint = false;
this.strokeList = new StrokeList();
this.defaultStroke = DEFAULT_STROKE;
this.autoPopulateSeriesStroke = true;
this.outlineStrokeList = new StrokeList();
this.defaultOutlineStroke = DEFAULT_OUTLINE_STROKE;
this.autoPopulateSeriesOutlineStroke = false;
this.shapeList = new ShapeList();
this.defaultShape = DEFAULT_SHAPE;
this.autoPopulateSeriesShape = true;
this.itemLabelsVisibleList = new BooleanList();
this.defaultItemLabelsVisible = Boolean.FALSE;
this.itemLabelFontList = new ObjectList<Font>();
this.defaultItemLabelFont = new Font("SansSerif", Font.PLAIN, 10);
this.itemLabelPaintList = new PaintList();
this.defaultItemLabelPaint = Color.BLACK;
this.positiveItemLabelPositionList = new ObjectList<ItemLabelPosition>();
this.defaultPositiveItemLabelPosition = new ItemLabelPosition(
ItemLabelAnchor.OUTSIDE12, TextAnchor.BOTTOM_CENTER);
this.negativeItemLabelPositionList = new ObjectList<ItemLabelPosition>();
this.defaultNegativeItemLabelPosition = new ItemLabelPosition(
ItemLabelAnchor.OUTSIDE6, TextAnchor.TOP_CENTER);
this.createEntitiesList = new BooleanList();
this.defaultCreateEntities = true;
this.defaultEntityRadius = 3;
this.legendShapeList = new ShapeList();
this.defaultLegendShape = null;
this.treatLegendShapeAsLine = false;
this.legendTextFont = new ObjectList<Font>();
this.defaultLegendTextFont = new Font("Dialog", Font.PLAIN, 12);
this.legendTextPaint = new PaintList();
this.defaultLegendTextPaint = null;
this.listenerList = new EventListenerList();
}
/**
* Returns the drawing supplier from the plot.
*
* @return The drawing supplier.
*/
public abstract DrawingSupplier getDrawingSupplier();
// SETTER FOR ITEM RENDERING STRATEGIES
/**
* @param labelIRS {@link #labelIRS} (<code>null</code> not permitted)
*/
public void setLabelIRS(LabelIRS labelIRS) {
ParamChecks.nullNotPermitted(labelIRS, "labelIRS");
this.labelIRS = labelIRS;
}
/**
* @param paintIRS {@link #paintIRS} (<code>null</code> not permitted)
*/
public void setPaintIRS(PaintIRS paintIRS) {
ParamChecks.nullNotPermitted(paintIRS, "paintIRS");
this.paintIRS = paintIRS;
}
/**
* @param shapeIRS {@link #shapeIRS} (<code>null</code> not permitted)
*/
public void setShapeIRS(ShapeIRS shapeIRS) {
ParamChecks.nullNotPermitted(shapeIRS, "shapeIRS");
this.shapeIRS = shapeIRS;
}
/**
* @param strokeIRS {@link #strokeIRS} (<code>null</code> not permitted)
*/
public void setStrokeIRS(StrokeIRS strokeIRS) {
ParamChecks.nullNotPermitted(strokeIRS, "strokeIRS");
this.strokeIRS = strokeIRS;
}
/**
* @param visibilityIRS {@link #visibilityIRS} (<code>null</code> not
* permitted)
*/
public void setVisibilityIRS(VisibilityIRS visibilityIRS) {
ParamChecks.nullNotPermitted(visibilityIRS, null);
this.visibilityIRS = visibilityIRS;
}
// SERIES VISIBLE (not yet respected by all renderers)
/**
* Returns a boolean that indicates whether or not the specified item
* should be drawn (this is typically used to hide an entire series).
* <p>
* The default implementation passes control to the
* {@link DefaultVisibilityIRS} which uses the
* <code>isSeriesVisible(series)</code> method. You can implement your
* own {@link VisibilityIRS} or override this method if you require
* different behavior.
*
* @param series the series index.
* @param column the column (or category) index (zero-based).
*
* @return The item visibility
*/
public boolean getItemVisible(int series, int item) {
return visibilityIRS.getItemVisible(series, item);
}
/**
* Returns a boolean that indicates whether or not the specified series
* should be drawn.
*
* @param series the series index.
*
* @return A boolean.
*/
public boolean isSeriesVisible(int series) {
boolean result = this.defaultSeriesVisible;
Boolean b = this.seriesVisibleList.getBoolean(series);
if (b != null) {
result = b;
}
return result;
}
/**
* Returns the flag that controls whether a series is visible.
*
* @param series the series index (zero-based).
*
* @return The flag (possibly <code>null</code>).
*
* @see #setSeriesVisible(int, Boolean)
*/
public Boolean getSeriesVisible(int series) {
return this.seriesVisibleList.getBoolean(series);
}
/**
* Sets the flag that controls whether a series is visible and sends a
* {@link RendererChangeEvent} to all registered listeners.
*
* @param series the series index (zero-based).
* @param visible the flag (<code>null</code> permitted).
*
* @see #getSeriesVisible(int)
*/
public void setSeriesVisible(int series, Boolean visible) {
setSeriesVisible(series, visible, true);
}
/**
* Sets the flag that controls whether a series is visible and, if
* requested, sends a {@link RendererChangeEvent} to all registered
* listeners.
*
* @param series the series index.
* @param visible the flag (<code>null</code> permitted).
* @param notify notify listeners?
*
* @see #getSeriesVisible(int)
*/
public void setSeriesVisible(int series, Boolean visible, boolean notify) {
this.seriesVisibleList.setBoolean(series, visible);
if (notify) {
// we create an event with a special flag set...the purpose of
// this is to communicate to the plot (the default receiver of
// the event) that series visibility has changed so the axis
// ranges might need updating...
RendererChangeEvent e = new RendererChangeEvent(this, true);
notifyListeners(e);
}
}
/**
* Returns the default visibility for all series.
*
* @return The default visibility.
*
* @see #setDefaultSeriesVisible(boolean)
*/
public boolean getDefaultSeriesVisible() {
return this.defaultSeriesVisible;
}
/**
* Sets the default series visibility and sends a
* {@link RendererChangeEvent} to all registered listeners.
*
* @param visible the flag.
*
* @see #getDefaultSeriesVisible()
*/
public void setDefaultSeriesVisible(boolean visible) {
// defer argument checking...
setDefaultSeriesVisible(visible, true);
}
/**
* Sets the default series visibility and, if requested, sends
* a {@link RendererChangeEvent} to all registered listeners.
*
* @param visible the visibility.
* @param notify notify listeners?
*
* @see #getDefaultSeriesVisible()
*/
public void setDefaultSeriesVisible(boolean visible, boolean notify) {
this.defaultSeriesVisible = visible;
if (notify) {
// we create an event with a special flag set...the purpose of
// this is to communicate to the plot (the default receiver of
// the event) that series visibility has changed so the axis
// ranges might need updating...
RendererChangeEvent e = new RendererChangeEvent(this, true);
notifyListeners(e);
}
}
// SERIES VISIBLE IN LEGEND (not yet respected by all renderers)
/**
* Returns <code>true</code> if the series should be shown in the legend,
* and <code>false</code> otherwise.
*
* @param series the series index.
*
* @return A boolean.
*/
public boolean isSeriesVisibleInLegend(int series) {
boolean result = this.defaultSeriesVisibleInLegend;
Boolean b = this.seriesVisibleInLegendList.getBoolean(series);
if (b != null) {
result = b;
}
return result;
}
/**
* Returns the flag that controls whether a series is visible in the
* legend. This method returns only the "per series" settings - to
* incorporate the default settings as well, you need to use the
* {@link #isSeriesVisibleInLegend(int)} method.
*
* @param series the series index (zero-based).
*
* @return The flag (possibly <code>null</code>).
*
* @see #setSeriesVisibleInLegend(int, Boolean)
*/
public Boolean getSeriesVisibleInLegend(int series) {
return this.seriesVisibleInLegendList.getBoolean(series);
}
/**
* Sets the flag that controls whether a series is visible in the legend
* and sends a {@link RendererChangeEvent} to all registered listeners.
*
* @param series the series index (zero-based).
* @param visible the flag (<code>null</code> permitted).
*
* @see #getSeriesVisibleInLegend(int)
*/
public void setSeriesVisibleInLegend(int series, Boolean visible) {
setSeriesVisibleInLegend(series, visible, true);
}
/**
* Sets the flag that controls whether a series is visible in the legend
* and, if requested, sends a {@link RendererChangeEvent} to all registered
* listeners.
*
* @param series the series index.
* @param visible the flag (<code>null</code> permitted).
* @param notify notify listeners?
*
* @see #getSeriesVisibleInLegend(int)
*/
public void setSeriesVisibleInLegend(int series, Boolean visible,
boolean notify) {
this.seriesVisibleInLegendList.setBoolean(series, visible);
if (notify) {
fireChangeEvent();
}
}
/**
* Returns the default visibility in the legend for all series.
*
* @return The default visibility.
*
* @see #setDefaultSeriesVisibleInLegend(boolean)
*/
public boolean getDefaultSeriesVisibleInLegend() {
return this.defaultSeriesVisibleInLegend;
}
/**
* Sets the default visibility in the legend and sends a
* {@link RendererChangeEvent} to all registered listeners.
*
* @param visible the flag.
*
* @see #getDefaultSeriesVisibleInLegend()
*/
public void setDefaultSeriesVisibleInLegend(boolean visible) {
// defer argument checking...
setDefaultSeriesVisibleInLegend(visible, true);
}
/**
* Sets the default visibility in the legend and, if requested, sends
* a {@link RendererChangeEvent} to all registered listeners.
*
* @param visible the visibility.
* @param notify notify listeners?
*
* @see #getDefaultSeriesVisibleInLegend()
*/
public void setDefaultSeriesVisibleInLegend(boolean visible,
boolean notify) {
this.defaultSeriesVisibleInLegend = visible;
if (notify) {
fireChangeEvent();
}
}
// PAINT
/**
* Returns the paint used to fill data items as they are drawn.
* (this is typically the same for an entire series).
* <p>
* The default implementation passes control to the {@link DefaultPaintIRS}
* which uses the <code>lookupSeriesPaint(row)</code> method. You can
* implement your own {@link PaintIRS} or override this method if you
* require different behavior.
*
* @param row the row (or series) index (zero-based).
* @param column the column (or category) index (zero-based).
*
* @return The paint (never <code>null</code>).
*/
public Paint getItemPaint(int row, int column) {
return paintIRS.getItemPaint(row, column);
}
/**
* Returns the paint used to fill an item drawn by the renderer.
*
* @param series the series index (zero-based).
*
* @return The paint (never <code>null</code>).
*
* @since 1.0.6
*/
public Paint lookupSeriesPaint(int series) {
Paint seriesPaint = getSeriesPaint(series);
if (seriesPaint == null && this.autoPopulateSeriesPaint) {
DrawingSupplier supplier = getDrawingSupplier();
if (supplier != null) {
seriesPaint = supplier.getNextPaint();
setSeriesPaint(series, seriesPaint, false);
}
}
if (seriesPaint == null) {
seriesPaint = this.defaultPaint;
}
return seriesPaint;
}
/**
* Returns the paint used to fill an item drawn by the renderer.
*
* @param series the series index (zero-based).
*
* @return The paint (possibly <code>null</code>).
*
* @see #setSeriesPaint(int, Paint)
*/
public Paint getSeriesPaint(int series) {
return this.paintList.getPaint(series);
}
/**
* Sets the paint used for a series and sends a {@link RendererChangeEvent}
* to all registered listeners.
*
* @param series the series index (zero-based).
* @param paint the paint (<code>null</code> permitted).
*
* @see #getSeriesPaint(int)
*/
public void setSeriesPaint(int series, Paint paint) {
setSeriesPaint(series, paint, true);
}
/**
* Sets the paint used for a series and, if requested, sends a
* {@link RendererChangeEvent} to all registered listeners.
*
* @param series the series index.
* @param paint the paint (<code>null</code> permitted).
* @param notify notify listeners?
*
* @see #getSeriesPaint(int)
*/
public void setSeriesPaint(int series, Paint paint, boolean notify) {
this.paintList.setPaint(series, paint);
if (notify) {
fireChangeEvent();
}
}
/**
* Clears the series paint settings for this renderer and, if requested,
* sends a {@link RendererChangeEvent} to all registered listeners.
*
* @param notify notify listeners?
*
* @since 1.0.11
*/
public void clearSeriesPaints(boolean notify) {
this.paintList.clear();
if (notify) {
fireChangeEvent();
}
}
/**
* Returns the default paint.
*
* @return The default paint (never <code>null</code>).
*
* @see #setDefaultPaint(Paint)
*/
public Paint getDefaultPaint() {
return this.defaultPaint;
}
/**
* Sets the default paint and sends a {@link RendererChangeEvent} to all
* registered listeners.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getDefaultPaint()
*/
public void setDefaultPaint(Paint paint) {
// defer argument checking...
setDefaultPaint(paint, true);
}
/**
* Sets the default paint and, if requested, sends a
* {@link RendererChangeEvent} to all registered listeners.
*
* @param paint the paint (<code>null</code> not permitted).
* @param notify notify listeners?
*
* @see #getDefaultPaint()
*/
public void setDefaultPaint(Paint paint, boolean notify) {
this.defaultPaint = paint;
if (notify) {
fireChangeEvent();
}
}
/**
* Returns the flag that controls whether or not the series paint list is
* automatically populated when {@link #lookupSeriesPaint(int)} is called.
*
* @return A boolean.
*
* @since 1.0.6
*
* @see #setAutoPopulateSeriesPaint(boolean)
*/
public boolean getAutoPopulateSeriesPaint() {
return this.autoPopulateSeriesPaint;
}
/**
* Sets the flag that controls whether or not the series paint list is
* automatically populated when {@link #lookupSeriesPaint(int)} is called.
*
* @param auto the new flag value.
*
* @since 1.0.6
*
* @see #getAutoPopulateSeriesPaint()
*/
public void setAutoPopulateSeriesPaint(boolean auto) {
this.autoPopulateSeriesPaint = auto;
}
//// FILL PAINT //////////////////////////////////////////////////////////
/**
* Returns the paint used to fill data items as they are drawn.
* (this is typically the same for an entire series).
* <p>
* The default implementation passes control to the {@link DefaultPaintIRS}
* which uses the <code>lookupSeriesFillPaint(row)</code> method. You can
* implement your own {@link PaintIRS} or override this method if you
* require different behavior.
*
* @param row the row (or series) index (zero-based).
* @param column the column (or category) index (zero-based).
*
* @return The paint (never <code>null</code>).
*/
public Paint getItemFillPaint(int row, int column) {
return paintIRS.getItemFillPaint(row, column);
}
/**
* Returns the paint used to fill an item drawn by the renderer.
*
* @param series the series (zero-based index).
*
* @return The paint (never <code>null</code>).
*
* @since 1.0.6
*/
public Paint lookupSeriesFillPaint(int series) {
Paint seriesFillPaint = getSeriesFillPaint(series);
if (seriesFillPaint == null && this.autoPopulateSeriesFillPaint) {
DrawingSupplier supplier = getDrawingSupplier();
if (supplier != null) {
seriesFillPaint = supplier.getNextFillPaint();
setSeriesFillPaint(series, seriesFillPaint, false);
}
}
if (seriesFillPaint == null) {
seriesFillPaint = this.defaultFillPaint;
}
return seriesFillPaint;
}
/**
* Returns the paint used to fill an item drawn by the renderer.
*
* @param series the series (zero-based index).
*
* @return The paint (never <code>null</code>).
*
* @see #setSeriesFillPaint(int, Paint)
*/
public Paint getSeriesFillPaint(int series) {
return this.fillPaintList.getPaint(series);
}
/**
* Sets the paint used for a series fill and sends a
* {@link RendererChangeEvent} to all registered listeners.
*
* @param series the series index (zero-based).
* @param paint the paint (<code>null</code> permitted).
*
* @see #getSeriesFillPaint(int)
*/
public void setSeriesFillPaint(int series, Paint paint) {
setSeriesFillPaint(series, paint, true);
}
/**
* Sets the paint used to fill a series and, if requested,
* sends a {@link RendererChangeEvent} to all registered listeners.
*
* @param series the series index (zero-based).
* @param paint the paint (<code>null</code> permitted).
* @param notify notify listeners?
*
* @see #getSeriesFillPaint(int)
*/
public void setSeriesFillPaint(int series, Paint paint, boolean notify) {
this.fillPaintList.setPaint(series, paint);
if (notify) {
fireChangeEvent();
}
}
/**
* Returns the default fill paint.
*
* @return The paint (never <code>null</code>).
*
* @see #setDefaultFillPaint(Paint)
*/
public Paint getDefaultFillPaint() {
return this.defaultFillPaint;
}
/**
* Sets the default fill paint and sends a {@link RendererChangeEvent} to
* all registered listeners.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getDefaultFillPaint()
*/
public void setDefaultFillPaint(Paint paint) {
// defer argument checking...
setDefaultFillPaint(paint, true);
}
/**
* Sets the default fill paint and, if requested, sends a
* {@link RendererChangeEvent} to all registered listeners.
*
* @param paint the paint (<code>null</code> not permitted).
* @param notify notify listeners?
*
* @see #getDefaultFillPaint()
*/
public void setDefaultFillPaint(Paint paint, boolean notify) {
ParamChecks.nullNotPermitted(paint, "paint");
this.defaultFillPaint = paint;
if (notify) {
fireChangeEvent();
}
}
/**
* Returns the flag that controls whether or not the series fill paint list
* is automatically populated when {@link #lookupSeriesFillPaint(int)} is
* called.
*
* @return A boolean.
*
* @since 1.0.6
*
* @see #setAutoPopulateSeriesFillPaint(boolean)
*/
public boolean getAutoPopulateSeriesFillPaint() {
return this.autoPopulateSeriesFillPaint;
}
/**
* Sets the flag that controls whether or not the series fill paint list is
* automatically populated when {@link #lookupSeriesFillPaint(int)} is
* called.
*
* @param auto the new flag value.
*
* @since 1.0.6
*
* @see #getAutoPopulateSeriesFillPaint()
*/
public void setAutoPopulateSeriesFillPaint(boolean auto) {
this.autoPopulateSeriesFillPaint = auto;
}
// OUTLINE PAINT //////////////////////////////////////////////////////////
/**
* Returns the paint used to outline data items as they are drawn.
* (this is typically the same for an entire series).
* <p>
* The default implementation passes control to the {@link DefaultPaintIRS}
* which uses the <code>return lookupSeriesOutlinePaint(row)</code> method.
* You can implement your own {@link PaintIRS} or override this method if
* you require different behavior.
*
* @param row the row (or series) index (zero-based).
* @param column the column (or category) index (zero-based).
*
* @return The paint (never <code>null</code>).
*/
public Paint getItemOutlinePaint(int row, int column) {
return paintIRS.getItemOutlinePaint(row, column);
}
/**
* Returns the paint used to outline an item drawn by the renderer.
*
* @param series the series (zero-based index).
*
* @return The paint (never <code>null</code>).
*
* @since 1.0.6
*/
public Paint lookupSeriesOutlinePaint(int series) {
Paint seriesOutlinePaint = getSeriesOutlinePaint(series);
if (seriesOutlinePaint == null && this.autoPopulateSeriesOutlinePaint) {
DrawingSupplier supplier = getDrawingSupplier();
if (supplier != null) {
seriesOutlinePaint = supplier.getNextOutlinePaint();
setSeriesOutlinePaint(series, seriesOutlinePaint, false);
}
}
if (seriesOutlinePaint == null) {
seriesOutlinePaint = this.defaultOutlinePaint;
}
return seriesOutlinePaint;
}
/**
* Returns the paint used to outline an item drawn by the renderer.
*
* @param series the series (zero-based index).
*
* @return The paint (possibly <code>null</code>).
*
* @see #setSeriesOutlinePaint(int, Paint)
*/
public Paint getSeriesOutlinePaint(int series) {
return this.outlinePaintList.getPaint(series);
}
/**
* Sets the paint used for a series outline and sends a
* {@link RendererChangeEvent} to all registered listeners.
*
* @param series the series index (zero-based).
* @param paint the paint (<code>null</code> permitted).
*
* @see #getSeriesOutlinePaint(int)
*/
public void setSeriesOutlinePaint(int series, Paint paint) {
setSeriesOutlinePaint(series, paint, true);
}
/**
* Sets the paint used to draw the outline for a series and, if requested,
* sends a {@link RendererChangeEvent} to all registered listeners.
*
* @param series the series index (zero-based).
* @param paint the paint (<code>null</code> permitted).
* @param notify notify listeners?
*
* @see #getSeriesOutlinePaint(int)
*/
public void setSeriesOutlinePaint(int series, Paint paint, boolean notify) {
this.outlinePaintList.setPaint(series, paint);
if (notify) {
fireChangeEvent();
}
}
/**
* Returns the default outline paint.
*
* @return The paint (never <code>null</code>).
*
* @see #setDefaultOutlinePaint(Paint)
*/
public Paint getDefaultOutlinePaint() {
return this.defaultOutlinePaint;
}
/**
* Sets the default outline paint and sends a {@link RendererChangeEvent} to
* all registered listeners.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getDefaultOutlinePaint()
*/
public void setDefaultOutlinePaint(Paint paint) {
// defer argument checking...
setDefaultOutlinePaint(paint, true);
}
/**
* Sets the default outline paint and, if requested, sends a
* {@link RendererChangeEvent} to all registered listeners.
*
* @param paint the paint (<code>null</code> not permitted).
* @param notify notify listeners?
*
* @see #getDefaultOutlinePaint()
*/
public void setDefaultOutlinePaint(Paint paint, boolean notify) {
ParamChecks.nullNotPermitted(paint, "paint");
this.defaultOutlinePaint = paint;
if (notify) {
fireChangeEvent();
}
}
/**
* Returns the flag that controls whether or not the series outline paint
* list is automatically populated when
* {@link #lookupSeriesOutlinePaint(int)} is called.
*
* @return A boolean.
*
* @since 1.0.6
*
* @see #setAutoPopulateSeriesOutlinePaint(boolean)
*/
public boolean getAutoPopulateSeriesOutlinePaint() {
return this.autoPopulateSeriesOutlinePaint;
}
/**
* Sets the flag that controls whether or not the series outline paint list
* is automatically populated when {@link #lookupSeriesOutlinePaint(int)}
* is called.
*
* @param auto the new flag value.
*
* @since 1.0.6
*
* @see #getAutoPopulateSeriesOutlinePaint()
*/
public void setAutoPopulateSeriesOutlinePaint(boolean auto) {
this.autoPopulateSeriesOutlinePaint = auto;
}
// STROKE
/**
* Returns the stroke used to draw data items.
* (this is typically the same for an entire series).
* <p>
* The default implementation passes control to the {@link DefaultStrokeIRS}
* which uses the <code>lookupSeriesStroke(row)</code> method. You can
* implement your own {@link StrokeIRS} or override this method if you
* require different behavior.
*
* @param row the row (or series) index (zero-based).
* @param column the column (or category) index (zero-based).
*
* @return The stroke (never <code>null</code>).
*/
public Stroke getItemStroke(int row, int column) {
return strokeIRS.getItemStroke(row, column);
}
/**
* Returns the stroke used to draw the items in a series.
*
* @param series the series (zero-based index).
*
* @return The stroke (never <code>null</code>).
*
* @since 1.0.6
*/
public Stroke lookupSeriesStroke(int series) {
Stroke result = getSeriesStroke(series);
if (result == null && this.autoPopulateSeriesStroke) {
DrawingSupplier supplier = getDrawingSupplier();
if (supplier != null) {
result = supplier.getNextStroke();
setSeriesStroke(series, result, false);
}
}
if (result == null) {
result = this.defaultStroke;
}
return result;
}
/**
* Returns the stroke used to draw the items in a series.
*
* @param series the series (zero-based index).
*
* @return The stroke (possibly <code>null</code>).
*
* @see #setSeriesStroke(int, Stroke)
*/
public Stroke getSeriesStroke(int series) {
return this.strokeList.getStroke(series);
}
/**
* Sets the stroke used for a series and sends a {@link RendererChangeEvent}
* to all registered listeners.
*
* @param series the series index (zero-based).
* @param stroke the stroke (<code>null</code> permitted).
*
* @see #getSeriesStroke(int)
*/
public void setSeriesStroke(int series, Stroke stroke) {
setSeriesStroke(series, stroke, true);
}
/**
* Sets the stroke for a series and, if requested, sends a
* {@link RendererChangeEvent} to all registered listeners.
*
* @param series the series index (zero-based).
* @param stroke the stroke (<code>null</code> permitted).
* @param notify notify listeners?
*
* @see #getSeriesStroke(int)
*/
public void setSeriesStroke(int series, Stroke stroke, boolean notify) {
this.strokeList.setStroke(series, stroke);
if (notify) {
fireChangeEvent();
}
}
/**
* Clears the series stroke settings for this renderer and, if requested,
* sends a {@link RendererChangeEvent} to all registered listeners.
*
* @param notify notify listeners?
*
* @since 1.0.11
*/
public void clearSeriesStrokes(boolean notify) {
this.strokeList.clear();
if (notify) {
fireChangeEvent();
}
}
/**
* Returns the default stroke.
*
* @return The default stroke (never <code>null</code>).
*
* @see #setDefaultStroke(Stroke)
*/
public Stroke getDefaultStroke() {
return this.defaultStroke;
}
/**
* Sets the default stroke and sends a {@link RendererChangeEvent} to all
* registered listeners.
*
* @param stroke the stroke (<code>null</code> not permitted).
*
* @see #getDefaultStroke()
*/
public void setDefaultStroke(Stroke stroke) {
// defer argument checking...
setDefaultStroke(stroke, true);
}
/**
* Sets the default stroke and, if requested, sends a
* {@link RendererChangeEvent} to all registered listeners.
*
* @param stroke the stroke (<code>null</code> not permitted).
* @param notify notify listeners?
*
* @see #getDefaultStroke()
*/
public void setDefaultStroke(Stroke stroke, boolean notify) {
ParamChecks.nullNotPermitted(stroke, "stroke");
this.defaultStroke = stroke;
if (notify) {
fireChangeEvent();
}
}
/**
* Returns the flag that controls whether or not the series stroke list is
* automatically populated when {@link #lookupSeriesStroke(int)} is called.
*
* @return A boolean.
*
* @since 1.0.6
*
* @see #setAutoPopulateSeriesStroke(boolean)
*/
public boolean getAutoPopulateSeriesStroke() {
return this.autoPopulateSeriesStroke;
}
/**
* Sets the flag that controls whether or not the series stroke list is
* automatically populated when {@link #lookupSeriesStroke(int)} is called.
*
* @param auto the new flag value.
*
* @since 1.0.6
*
* @see #getAutoPopulateSeriesStroke()
*/
public void setAutoPopulateSeriesStroke(boolean auto) {
this.autoPopulateSeriesStroke = auto;
}
// OUTLINE STROKE
/**
* Returns the stroke used to outline data items
* (this is typically the same for an entire series).
* <p>
* The default implementation passes control to the {@link DefaultStrokeIRS}
* which uses the <code>lookupSeriesOutlineStroke(row)</code> method. You
* can implement your own {@link StrokeIRS} or override this method if you
* require different behavior.
*
* @param row the row (or series) index (zero-based).
* @param column the column (or category) index (zero-based).
*
* @return The stroke (never <code>null</code>).
*/
public Stroke getItemOutlineStroke(int row, int column) {
return strokeIRS.getItemOutlineStroke(row, column);
}
/**
* Returns the stroke used to outline the items in a series.
*
* @param series the series (zero-based index).
*
* @return The stroke (never <code>null</code>).
*
* @since 1.0.6
*/
public Stroke lookupSeriesOutlineStroke(int series) {
Stroke result = getSeriesOutlineStroke(series);
if (result == null && this.autoPopulateSeriesOutlineStroke) {
DrawingSupplier supplier = getDrawingSupplier();
if (supplier != null) {
result = supplier.getNextOutlineStroke();
setSeriesOutlineStroke(series, result, false);
}
}
if (result == null) {
result = this.defaultOutlineStroke;
}
return result;
}
/**
* Returns the stroke used to outline the items in a series.
*
* @param series the series (zero-based index).
*
* @return The stroke (possibly <code>null</code>).
*
* @see #setSeriesOutlineStroke(int, Stroke)
*/
public Stroke getSeriesOutlineStroke(int series) {
return this.outlineStrokeList.getStroke(series);
}
/**
* Sets the outline stroke used for a series and sends a
* {@link RendererChangeEvent} to all registered listeners.
*
* @param series the series index (zero-based).
* @param stroke the stroke (<code>null</code> permitted).
*
* @see #getSeriesOutlineStroke(int)
*/
public void setSeriesOutlineStroke(int series, Stroke stroke) {
setSeriesOutlineStroke(series, stroke, true);
}
/**
* Sets the outline stroke for a series and, if requested, sends a
* {@link RendererChangeEvent} to all registered listeners.
*
* @param series the series index.
* @param stroke the stroke (<code>null</code> permitted).
* @param notify notify listeners?
*
* @see #getSeriesOutlineStroke(int)
*/
public void setSeriesOutlineStroke(int series, Stroke stroke,
boolean notify) {
this.outlineStrokeList.setStroke(series, stroke);
if (notify) {
fireChangeEvent();
}
}
/**
* Returns the default outline stroke.
*
* @return The stroke (never <code>null</code>).
*
* @see #setDefaultOutlineStroke(Stroke)
*/
public Stroke getDefaultOutlineStroke() {
return this.defaultOutlineStroke;
}
/**
* Sets the default outline stroke and sends a {@link RendererChangeEvent}
* to all registered listeners.
*
* @param stroke the stroke (<code>null</code> not permitted).
*
* @see #getDefaultOutlineStroke()
*/
public void setDefaultOutlineStroke(Stroke stroke) {
setDefaultOutlineStroke(stroke, true);
}
/**
* Sets the default outline stroke and, if requested, sends a
* {@link RendererChangeEvent} to all registered listeners.
*
* @param stroke the stroke (<code>null</code> not permitted).
* @param notify a flag that controls whether or not listeners are
* notified.
*
* @see #getDefaultOutlineStroke()
*/
public void setDefaultOutlineStroke(Stroke stroke, boolean notify) {
ParamChecks.nullNotPermitted(stroke, "stroke");
this.defaultOutlineStroke = stroke;
if (notify) {
fireChangeEvent();
}
}
/**
* Returns the flag that controls whether or not the series outline stroke
* list is automatically populated when
* {@link #lookupSeriesOutlineStroke(int)} is called.
*
* @return A boolean.
*
* @since 1.0.6
*
* @see #setAutoPopulateSeriesOutlineStroke(boolean)
*/
public boolean getAutoPopulateSeriesOutlineStroke() {
return this.autoPopulateSeriesOutlineStroke;
}
/**
* Sets the flag that controls whether or not the series outline stroke list
* is automatically populated when {@link #lookupSeriesOutlineStroke(int)}
* is called.
*
* @param auto the new flag value.
*
* @since 1.0.6
*
* @see #getAutoPopulateSeriesOutlineStroke()
*/
public void setAutoPopulateSeriesOutlineStroke(boolean auto) {
this.autoPopulateSeriesOutlineStroke = auto;
}
// SHAPE
/**
* Returns a shape used to represent a data item.
* (this is typically the same for an entire series).
* <p>
* The default implementation passes control to the {@link DefaultShapeIRS}
* which uses the <code>lookupSeriesShape(row)</code> method. You can
* implement your own {@link ShapeIRS} or override this method if you
* require different behavior.
*
* @param row the row (or series) index (zero-based).
* @param column the column (or category) index (zero-based).
*
* @return The shape (never <code>null</code>).
*/
public Shape getItemShape(int row, int column) {
return shapeIRS.getItemShape(row, column);
}
/**
* Returns a shape used to represent the items in a series.
*
* @param series the series (zero-based index).
*
* @return The shape (never <code>null</code>).
*
* @since 1.0.6
*/
public Shape lookupSeriesShape(int series) {
Shape result = getSeriesShape(series);
if (result == null && this.autoPopulateSeriesShape) {
DrawingSupplier supplier = getDrawingSupplier();
if (supplier != null) {
result = supplier.getNextShape();
setSeriesShape(series, result, false);
}
}
if (result == null) {
result = this.defaultShape;
}
return result;
}
/**
* Returns a shape used to represent the items in a series.
*
* @param series the series (zero-based index).
*
* @return The shape (possibly <code>null</code>).
*
* @see #setSeriesShape(int, Shape)
*/
public Shape getSeriesShape(int series) {
return this.shapeList.getShape(series);
}
/**
* Sets the shape used for a series and sends a {@link RendererChangeEvent}
* to all registered listeners.
*
* @param series the series index (zero-based).
* @param shape the shape (<code>null</code> permitted).
*
* @see #getSeriesShape(int)
*/
public void setSeriesShape(int series, Shape shape) {
setSeriesShape(series, shape, true);
}
/**
* Sets the shape for a series and, if requested, sends a
* {@link RendererChangeEvent} to all registered listeners.
*
* @param series the series index (zero based).
* @param shape the shape (<code>null</code> permitted).
* @param notify notify listeners?
*
* @see #getSeriesShape(int)
*/
public void setSeriesShape(int series, Shape shape, boolean notify) {
this.shapeList.setShape(series, shape);
if (notify) {
fireChangeEvent();
}
}
/**
* Returns the default shape.
*
* @return The shape (never <code>null</code>).
*
* @see #setDefaultShape(Shape)
*/
public Shape getDefaultShape() {
return this.defaultShape;
}
/**
* Sets the default shape and sends a {@link RendererChangeEvent} to all
* registered listeners.
*
* @param shape the shape (<code>null</code> not permitted).
*
* @see #getDefaultShape()
*/
public void setDefaultShape(Shape shape) {
// defer argument checking...
setDefaultShape(shape, true);
}
/**
* Sets the default shape and, if requested, sends a
* {@link RendererChangeEvent} to all registered listeners.
*
* @param shape the shape (<code>null</code> not permitted).
* @param notify notify listeners?
*
* @see #getDefaultShape()
*/
public void setDefaultShape(Shape shape, boolean notify) {
ParamChecks.nullNotPermitted(shape, "shape");
this.defaultShape = shape;
if (notify) {
fireChangeEvent();
}
}
/**
* Returns the flag that controls whether or not the series shape list is
* automatically populated when {@link #lookupSeriesShape(int)} is called.
*
* @return A boolean.
*
* @since 1.0.6
*
* @see #setAutoPopulateSeriesShape(boolean)
*/
public boolean getAutoPopulateSeriesShape() {
return this.autoPopulateSeriesShape;
}
/**
* Sets the flag that controls whether or not the series shape list is
* automatically populated when {@link #lookupSeriesShape(int)} is called.
*
* @param auto the new flag value.
*
* @since 1.0.6
*
* @see #getAutoPopulateSeriesShape()
*/
public void setAutoPopulateSeriesShape(boolean auto) {
this.autoPopulateSeriesShape = auto;
}
// ITEM LABEL VISIBILITY...
/**
* Returns <code>true</code> if an item label is visible, and
* <code>false</code> otherwise (this is typically the same for an entire
* series).
* <p>
* The default implementation passes control to the
* {@link DefaultVisibilityIRS} which uses the
* <code>isSeriesItemLabelsVisible(row)</code> method. You can implement
* your own {@link VisibilityIRS} or override this method if you require
* different behavior.
*
* @param row the row (or series) index (zero-based).
* @param column the column (or category) index (zero-based).
*
* @return true if the item label is visible
*/
public boolean isItemLabelVisible(int row, int column) {
return labelIRS.isItemLabelVisible(row, column);
}
/**
* Returns <code>true</code> if the item labels for a series are visible,
* and <code>false</code> otherwise.
*
* @param series the series index (zero-based).
*
* @return A boolean.
*/
public boolean isSeriesItemLabelsVisible(int series) {
Boolean b = this.itemLabelsVisibleList.getBoolean(series);
if (b == null) {
b = this.defaultItemLabelsVisible;
}
if (b == null) {
b = Boolean.FALSE;
}
return b;
}
/**
* Sets a flag that controls the visibility of the item labels for a series,
* and sends a {@link RendererChangeEvent} to all registered listeners.
*
* @param series the series index (zero-based).
* @param visible the flag.
*/
public void setSeriesItemLabelsVisible(int series, boolean visible) {
setSeriesItemLabelsVisible(series, Boolean.valueOf(visible));
}
/**
* Sets the visibility of the item labels for a series and sends a
* {@link RendererChangeEvent} to all registered listeners.
*
* @param series the series index (zero-based).
* @param visible the flag (<code>null</code> permitted).
*/
public void setSeriesItemLabelsVisible(int series, Boolean visible) {
setSeriesItemLabelsVisible(series, visible, true);
}
/**
* Sets the visibility of item labels for a series and, if requested, sends
* a {@link RendererChangeEvent} to all registered listeners.
*
* @param series the series index (zero-based).
* @param visible the visible flag.
* @param notify a flag that controls whether or not listeners are
* notified.
*/
public void setSeriesItemLabelsVisible(int series, Boolean visible,
boolean notify) {
this.itemLabelsVisibleList.setBoolean(series, visible);
if (notify) {
fireChangeEvent();
}
}
/**
* Returns the default setting for item label visibility.
*
* @return A flag (possibly <code>null</code>).
*
* @see #setDefaultItemLabelsVisible(boolean)
*/
public boolean getDefaultItemLabelsVisible() {
return this.defaultItemLabelsVisible;
}
/**
* Sets the default flag that controls whether or not item labels are
* visible, and sends a {@link RendererChangeEvent} to all registered
* listeners.
*
* @param visible the flag.
*
* @see #getDefaultItemLabelsVisible()
*/
public void setDefaultItemLabelsVisible(boolean visible) {
setDefaultItemLabelsVisible(visible, true);
}
/**
* Sets the base visibility for item labels and, if requested, sends a
* {@link RendererChangeEvent} to all registered listeners.
*
* @param visible the flag (<code>null</code> is permitted, and viewed
* as equivalent to <code>Boolean.FALSE</code>).
* @param notify a flag that controls whether or not listeners are
* notified.
*
* @see #getBaseItemLabelsVisible()
*/
public void setDefaultItemLabelsVisible(boolean visible, boolean notify) {
this.defaultItemLabelsVisible = visible;
if (notify) {
fireChangeEvent();
}
}
//// ITEM LABEL FONT //////////////////////////////////////////////////////
/**
* Returns the font for an item label (this is typically the same for an
* entire series).
* <p>
* The default implementation passes control to the {@link DefaultLabelIRS}
* You can implement your own {@link LabelIRS} or override this method if
* you require different behavior.
*
* @param row the row (or series) index (zero-based).
* @param column the column (or category) index (zero-based).
*
* @return The font (never <code>null</code>).
*/
public Font getItemLabelFont(int row, int column) {
return labelIRS.getItemLabelFont(row, column);
}
/**
* Returns the font for all the item labels in a series.
*
* @param series the series index (zero-based).
*
* @return The font (possibly <code>null</code>).
*
* @see #setSeriesItemLabelFont(int, Font)
*/
public Font getSeriesItemLabelFont(int series) {
return this.itemLabelFontList.get(series);
}
/**
* Sets the item label font for a series and sends a
* {@link RendererChangeEvent} to all registered listeners.
*
* @param series the series index (zero-based).
* @param font the font (<code>null</code> permitted).
*
* @see #getSeriesItemLabelFont(int)
*/
public void setSeriesItemLabelFont(int series, Font font) {
setSeriesItemLabelFont(series, font, true);
}
/**
* Sets the item label font for a series and, if requested, sends a
* {@link RendererChangeEvent} to all registered listeners.
*
* @param series the series index (zero based).
* @param font the font (<code>null</code> permitted).
* @param notify a flag that controls whether or not listeners are
* notified.
*
* @see #getSeriesItemLabelFont(int)
*/
public void setSeriesItemLabelFont(int series, Font font, boolean notify) {
this.itemLabelFontList.set(series, font);
if (notify) {
fireChangeEvent();
}
}
/**
* Returns the default item label font (this is used when no other font
* setting is available).
*
* @return The font (<code>never</code> null).
*
* @see #setDefaultItemLabelFont(Font)
*/
public Font getDefaultItemLabelFont() {
return this.defaultItemLabelFont;
}
/**
* Sets the default item label font and sends a {@link RendererChangeEvent}
* to all registered listeners.
*
* @param font the font (<code>null</code> not permitted).
*
* @see #getDefaultItemLabelFont()
*/
public void setDefaultItemLabelFont(Font font) {
ParamChecks.nullNotPermitted(font, "font");
setDefaultItemLabelFont(font, true);
}
/**
* Sets the default item label font and, if requested, sends a
* {@link RendererChangeEvent} to all registered listeners.
*
* @param font the font (<code>null</code> not permitted).
* @param notify a flag that controls whether or not listeners are
* notified.
*
* @see #getDefaultItemLabelFont()
*/
public void setDefaultItemLabelFont(Font font, boolean notify) {
this.defaultItemLabelFont = font;
if (notify) {
fireChangeEvent();
}
}
//// ITEM LABEL PAINT ////////////////////////////////////////////////////
/**
* Returns the paint used to draw an item label.
*
* @param row the row index (zero based).
* @param column the column index (zero based).
*
* @return The paint (never <code>null</code>).
*/
public Paint getItemLabelPaint(int row, int column) {
Paint result = getSeriesItemLabelPaint(row);
if (result == null) {
result = this.defaultItemLabelPaint;
}
return result;
}
/**
* Returns the paint used to draw the item labels for a series.
*
* @param series the series index (zero based).
*
* @return The paint (possibly <code>null</code>).
*
* @see #setSeriesItemLabelPaint(int, Paint)
*/
public Paint getSeriesItemLabelPaint(int series) {
return this.itemLabelPaintList.getPaint(series);
}
/**
* Sets the item label paint for a series and sends a
* {@link RendererChangeEvent} to all registered listeners.
*
* @param series the series (zero based index).
* @param paint the paint (<code>null</code> permitted).
*
* @see #getSeriesItemLabelPaint(int)
*/
public void setSeriesItemLabelPaint(int series, Paint paint) {
setSeriesItemLabelPaint(series, paint, true);
}
/**
* Sets the item label paint for a series and, if requested, sends a
* {@link RendererChangeEvent} to all registered listeners.
*
* @param series the series index (zero based).
* @param paint the paint (<code>null</code> permitted).
* @param notify a flag that controls whether or not listeners are
* notified.
*
* @see #getSeriesItemLabelPaint(int)
*/
public void setSeriesItemLabelPaint(int series, Paint paint,
boolean notify) {
this.itemLabelPaintList.setPaint(series, paint);
if (notify) {
fireChangeEvent();
}
}
/**
* Returns the default item label paint.
*
* @return The paint (never <code>null</code>).
*
* @see #setDefaultItemLabelPaint(Paint)
*/
public Paint getDefaultItemLabelPaint() {
return this.defaultItemLabelPaint;
}
/**
* Sets the default item label paint and sends a {@link RendererChangeEvent}
* to all registered listeners.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getDefaultItemLabelPaint()
*/
public void setDefaultItemLabelPaint(Paint paint) {
// defer argument checking...
setDefaultItemLabelPaint(paint, true);
}
/**
* Sets the default item label paint and, if requested, sends a
* {@link RendererChangeEvent} to all registered listeners..
*
* @param paint the paint (<code>null</code> not permitted).
* @param notify a flag that controls whether or not listeners are
* notified.
*
* @see #getDefaultItemLabelPaint()
*/
public void setDefaultItemLabelPaint(Paint paint, boolean notify) {
ParamChecks.nullNotPermitted(paint, "paint");
this.defaultItemLabelPaint = paint;
if (notify) {
fireChangeEvent();
}
}
// POSITIVE ITEM LABEL POSITION...
/**
* Returns the item label position for positive values (this is typically
* the same for an entire series).
* <p>
* The default implementation passes control to the {@link DefaultLabelIRS}
* You can implement your own {@link LabelIRS} or override this method if
* you require different behavior.
*
* @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>).
*
* @see #getNegativeItemLabelPosition(int, int)
*/
public ItemLabelPosition getPositiveItemLabelPosition(int row, int column) {
return labelIRS.getPositiveItemLabelPosition(row, column);
}
/**
* Returns the item label position for all positive values in a series.
*
* @param series the series index (zero-based).
*
* @return The item label position (never <code>null</code>).
*
* @see #setSeriesPositiveItemLabelPosition(int, ItemLabelPosition)
*/
public ItemLabelPosition getSeriesPositiveItemLabelPosition(int series) {
ItemLabelPosition position
= this.positiveItemLabelPositionList.get(series);
if (position == null) {
position = this.defaultPositiveItemLabelPosition;
}
return position;
}
/**
* Sets the item label position for all positive values in a series and
* sends a {@link RendererChangeEvent} to all registered listeners.
*
* @param series the series index (zero-based).
* @param position the position (<code>null</code> permitted).
*
* @see #getSeriesPositiveItemLabelPosition(int)
*/
public void setSeriesPositiveItemLabelPosition(int series,
ItemLabelPosition position) {
setSeriesPositiveItemLabelPosition(series, position, true);
}
/**
* Sets the item label position for all positive values in a series and (if
* requested) sends a {@link RendererChangeEvent} to all registered
* listeners.
*
* @param series the series index (zero-based).
* @param position the position (<code>null</code> permitted).
* @param notify notify registered listeners?
*
* @see #getSeriesPositiveItemLabelPosition(int)
*/
public void setSeriesPositiveItemLabelPosition(int series,
ItemLabelPosition position, boolean notify) {
this.positiveItemLabelPositionList.set(series, position);
if (notify) {
fireChangeEvent();
}
}
/**
* Returns the default positive item label position.
*
* @return The position (never <code>null</code>).
*
* @see #setDefaultPositiveItemLabelPosition(ItemLabelPosition)
*/
public ItemLabelPosition getDefaultPositiveItemLabelPosition() {
return this.defaultPositiveItemLabelPosition;
}
/**
* Sets the default positive item label position.
*
* @param position the position (<code>null</code> not permitted).
*
* @see #getDefaultPositiveItemLabelPosition()
*/
public void setDefaultPositiveItemLabelPosition(
ItemLabelPosition position) {
// defer argument checking...
setDefaultPositiveItemLabelPosition(position, true);
}
/**
* Sets the default positive item label position and, if requested, sends a
* {@link RendererChangeEvent} to all registered listeners.
*
* @param position the position (<code>null</code> not permitted).
* @param notify notify registered listeners?
*
* @see #getDefaultPositiveItemLabelPosition()
*/
public void setDefaultPositiveItemLabelPosition(ItemLabelPosition position,
boolean notify) {
ParamChecks.nullNotPermitted(position, "positions");
this.defaultPositiveItemLabelPosition = position;
if (notify) {
fireChangeEvent();
}
}
// NEGATIVE ITEM LABEL POSITION...
/**
* Returns the item label position for negative values (this is typically
* the same for an entire series).
* <p>
* The default implementation passes control to the {@link DefaultLabelIRS}
* You can implement your own {@link LabelIRS} or override this method if
* you require different behavior.
*
* @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>).
*
* @see #getPositiveItemLabelPosition(int, int)
*/
public ItemLabelPosition getNegativeItemLabelPosition(int row, int column) {
return labelIRS.getNegativeItemLabelPosition(row, column);
}
/**
* Returns the item label position for all negative values in a series.
*
* @param series the series index (zero-based).
*
* @return The item label position (never <code>null</code>).
*
* @see #setSeriesNegativeItemLabelPosition(int, ItemLabelPosition)
*/
public ItemLabelPosition getSeriesNegativeItemLabelPosition(int series) {
ItemLabelPosition position = this.negativeItemLabelPositionList.get(
series);
if (position == null) {
position = this.defaultNegativeItemLabelPosition;
}
return position;
}
/**
* Sets the item label position for negative values in a series and sends a
* {@link RendererChangeEvent} to all registered listeners.
*
* @param series the series index (zero-based).
* @param position the position (<code>null</code> permitted).
*
* @see #getSeriesNegativeItemLabelPosition(int)
*/
public void setSeriesNegativeItemLabelPosition(int series,
ItemLabelPosition position) {
setSeriesNegativeItemLabelPosition(series, position, true);
}
/**
* Sets the item label position for negative values in a series and (if
* requested) sends a {@link RendererChangeEvent} to all registered
* listeners.
*
* @param series the series index (zero-based).
* @param position the position (<code>null</code> permitted).
* @param notify notify registered listeners?
*
* @see #getSeriesNegativeItemLabelPosition(int)
*/
public void setSeriesNegativeItemLabelPosition(int series,
ItemLabelPosition position, boolean notify) {
this.negativeItemLabelPositionList.set(series, position);
if (notify) {
fireChangeEvent();
}
}
/**
* Returns the default item label position for negative values.
*
* @return The position (never <code>null</code>).
*
* @see #setDefaultNegativeItemLabelPosition(ItemLabelPosition)
*/
public ItemLabelPosition getDefaultNegativeItemLabelPosition() {
return this.defaultNegativeItemLabelPosition;
}
/**
* Sets the default item label position for negative values and sends a
* {@link RendererChangeEvent} to all registered listeners.
*
* @param position the position (<code>null</code> not permitted).
*
* @see #getDefaultNegativeItemLabelPosition()
*/
public void setDefaultNegativeItemLabelPosition(
ItemLabelPosition position) {
setDefaultNegativeItemLabelPosition(position, true);
}
/**
* Sets the default negative item label position and, if requested, sends a
* {@link RendererChangeEvent} to all registered listeners.
*
* @param position the position (<code>null</code> not permitted).
* @param notify notify registered listeners?
*
* @see #getDefaultNegativeItemLabelPosition()
*/
public void setDefaultNegativeItemLabelPosition(ItemLabelPosition position,
boolean notify) {
ParamChecks.nullNotPermitted(position, "positions");
this.defaultNegativeItemLabelPosition = position;
if (notify) {
fireChangeEvent();
}
}
/**
* Returns the item label anchor offset.
*
* @return The offset.
*
* @see #setItemLabelAnchorOffset(double)
*/
public double getItemLabelAnchorOffset() {
return this.itemLabelAnchorOffset;
}
/**
* Sets the item label anchor offset.
*
* @param offset the offset.
*
* @see #getItemLabelAnchorOffset()
*/
public void setItemLabelAnchorOffset(double offset) {
this.itemLabelAnchorOffset = offset;
fireChangeEvent();
}
/**
* Returns a boolean that indicates whether or not the specified item
* should have a chart entity created for it.
*
* @param series the series index.
* @param item the item index.
*
* @return A boolean.
*/
public boolean getItemCreateEntity(int series, int item) {
Boolean b = getSeriesCreateEntities(series);
if (b != null) {
return b;
}
// otherwise...
return this.defaultCreateEntities;
}
/**
* Returns the flag that controls whether entities are created for a
* series.
*
* @param series the series index (zero-based).
*
* @return The flag (possibly <code>null</code>).
*
* @see #setSeriesCreateEntities(int, Boolean)
*/
public Boolean getSeriesCreateEntities(int series) {
return this.createEntitiesList.getBoolean(series);
}
/**
* Sets the flag that controls whether entities are created for a series,
* and sends a {@link RendererChangeEvent} to all registered listeners.
*
* @param series the series index (zero-based).
* @param create the flag (<code>null</code> permitted).
*
* @see #getSeriesCreateEntities(int)
*/
public void setSeriesCreateEntities(int series, Boolean create) {
setSeriesCreateEntities(series, create, true);
}
/**
* Sets the flag that controls whether entities are created for a series
* and, if requested, sends a {@link RendererChangeEvent} to all registered
* listeners.
*
* @param series the series index.
* @param create the flag (<code>null</code> permitted).
* @param notify notify listeners?
*
* @see #getSeriesCreateEntities(int)
*/
public void setSeriesCreateEntities(int series, Boolean create,
boolean notify) {
this.createEntitiesList.setBoolean(series, create);
if (notify) {
fireChangeEvent();
}
}
/**
* Returns the default flag for creating entities.
*
* @return The default flag for creating entities.
*
* @see #setDefaultCreateEntities(boolean)
*/
public boolean getDefaultCreateEntities() {
return this.defaultCreateEntities;
}
/**
* Sets the default flag that controls whether entities are created
* for a series, and sends a {@link RendererChangeEvent}
* to all registered listeners.
*
* @param create the flag.
*
* @see #getDefaultCreateEntities()
*/
public void setDefaultCreateEntities(boolean create) {
// defer argument checking...
setDefaultCreateEntities(create, true);
}
/**
* Sets the default flag that controls whether entities are created and,
* if requested, sends a {@link RendererChangeEvent} to all registered
* listeners.
*
* @param create the visibility.
* @param notify notify listeners?
*
* @see #getDefaultCreateEntities()
*/
public void setDefaultCreateEntities(boolean create, boolean notify) {
this.defaultCreateEntities = create;
if (notify) {
fireChangeEvent();
}
}
/**
* Returns the radius of the circle used for the default entity area
* when no area is specified.
*
* @return A radius.
*
* @see #setDefaultEntityRadius(int)
*/
public int getDefaultEntityRadius() {
return this.defaultEntityRadius;
}
/**
* Sets the radius of the circle used for the default entity area
* when no area is specified.
*
* @param radius the radius.
*
* @see #getDefaultEntityRadius()
*/
public void setDefaultEntityRadius(int radius) {
this.defaultEntityRadius = radius;
}
/**
* Performs a lookup for the legend shape.
*
* @param series the series index.
*
* @return The shape (possibly <code>null</code>).
*
* @since 1.0.11
*/
public Shape lookupLegendShape(int series) {
Shape result = getLegendShape(series);
if (result == null) {
result = this.defaultLegendShape;
}
if (result == null) {
result = lookupSeriesShape(series);
}
return result;
}
/**
* Returns the legend shape defined for the specified series (possibly
* <code>null</code>).
*
* @param series the series index.
*
* @return The shape (possibly <code>null</code>).
*
* @see #lookupLegendShape(int)
*
* @since 1.0.11
*/
public Shape getLegendShape(int series) {
return this.legendShapeList.getShape(series);
}
/**
* Sets the shape used for the legend item for the specified series, and
* sends a {@link RendererChangeEvent} to all registered listeners.
*
* @param series the series index.
* @param shape the shape (<code>null</code> permitted).
*
* @since 1.0.11
*/
public void setLegendShape(int series, Shape shape) {
this.legendShapeList.setShape(series, shape);
fireChangeEvent();
}
/**
* Returns the default legend shape, which may be <code>null</code>.
*
* @return The default legend shape.
*
* @since 1.0.11
*/
public Shape getDefaultLegendShape() {
return this.defaultLegendShape;
}
/**
* Sets the default legend shape and sends a
* {@link RendererChangeEvent} to all registered listeners.
*
* @param shape the shape (<code>null</code> permitted).
*
* @since 1.0.11
*/
public void setDefaultLegendShape(Shape shape) {
this.defaultLegendShape = shape;
fireChangeEvent();
}
/**
* Returns the flag that controls whether or not the legend shape is
* treated as a line when creating legend items.
*
* @return A boolean.
*
* @since 1.0.14
*/
protected boolean getTreatLegendShapeAsLine() {
return this.treatLegendShapeAsLine;
}
/**
* Sets the flag that controls whether or not the legend shape is
* treated as a line when creating legend items.
*
* @param treatAsLine the new flag value.
*
* @since 1.0.14
*/
protected void setTreatLegendShapeAsLine(boolean treatAsLine) {
if (this.treatLegendShapeAsLine != treatAsLine) {
this.treatLegendShapeAsLine = treatAsLine;
fireChangeEvent();
}
}
/**
* Performs a lookup for the legend text font.
*
* @param series the series index.
*
* @return The font.
*
* @since 1.0.11
*/
public Font lookupLegendTextFont(int series) {
Font result = getLegendTextFont(series);
if (result == null) {
result = this.defaultLegendTextFont;
}
return result;
}
/**
* Returns the legend text font defined for the specified series (possibly
* <code>null</code>).
*
* @param series the series index.
*
* @return The font (possibly <code>null</code>).
*
* @see #lookupLegendTextFont(int)
*
* @since 1.0.11
*/
public Font getLegendTextFont(int series) {
return this.legendTextFont.get(series);
}
/**
* Sets the font used for the legend text for the specified series, and
* sends a {@link RendererChangeEvent} to all registered listeners.
*
* @param series the series index.
* @param font the font (<code>null</code> permitted).
*
* @since 1.0.11
*/
public void setLegendTextFont(int series, Font font) {
this.legendTextFont.set(series, font);
fireChangeEvent();
}
/**
* Returns the default legend text font.
*
* @return The default legend text font.
*
* @since 1.0.11
*/
public Font getDefaultLegendTextFont() {
return this.defaultLegendTextFont;
}
/**
* Sets the default legend text font and sends a
* {@link RendererChangeEvent} to all registered listeners.
*
* @param font the font (<code>null</code> not permitted).
*
* @since 1.0.11
*/
public void setDefaultLegendTextFont(Font font) {
ParamChecks.nullNotPermitted(font, "font");
this.defaultLegendTextFont = font;
fireChangeEvent();
}
/**
* Performs a lookup for the legend text paint.
*
* @param series the series index.
*
* @return The paint (possibly <code>null</code>).
*
* @since 1.0.11
*/
public Paint lookupLegendTextPaint(int series) {
Paint result = getLegendTextPaint(series);
if (result == null) {
result = this.defaultLegendTextPaint;
}
return result;
}
/**
* Returns the legend text paint defined for the specified series (possibly
* <code>null</code>).
*
* @param series the series index.
*
* @return The paint (possibly <code>null</code>).
*
* @see #lookupLegendTextPaint(int)
*
* @since 1.0.11
*/
public Paint getLegendTextPaint(int series) {
return this.legendTextPaint.getPaint(series);
}
/**
* Sets the paint used for the legend text for the specified series, and
* sends a {@link RendererChangeEvent} to all registered listeners.
*
* @param series the series index.
* @param paint the paint (<code>null</code> permitted).
*
* @since 1.0.11
*/
public void setLegendTextPaint(int series, Paint paint) {
this.legendTextPaint.setPaint(series, paint);
fireChangeEvent();
}
/**
* Returns the default legend text paint, which may be <code>null</code>.
*
* @return The default legend text paint.
*
* @since 1.0.11
*/
public Paint getDefaultLegendTextPaint() {
return this.defaultLegendTextPaint;
}
/**
* Sets the default legend text paint and sends a
* {@link RendererChangeEvent} to all registered listeners.
*
* @param paint the paint (<code>null</code> permitted).
*
* @since 1.0.11
*/
public void setDefaultLegendTextPaint(Paint paint) {
this.defaultLegendTextPaint = paint;
fireChangeEvent();
}
/**
* Returns the flag that controls whether or not the data bounds reported
* by this renderer will exclude non-visible series.
*
* @return A boolean.
*
* @since 1.0.13
*/
public boolean getDataBoundsIncludesVisibleSeriesOnly() {
return this.dataBoundsIncludesVisibleSeriesOnly;
}
/**
* Sets the flag that controls whether or not the data bounds reported
* by this renderer will exclude non-visible series and sends a
* {@link RendererChangeEvent} to all registered listeners.
*
* @param visibleOnly include only visible series.
*
* @since 1.0.13
*/
public void setDataBoundsIncludesVisibleSeriesOnly(boolean visibleOnly) {
this.dataBoundsIncludesVisibleSeriesOnly = visibleOnly;
notifyListeners(new RendererChangeEvent(this, true));
}
/** The adjacent offset. */
private static final double ADJ = Math.cos(Math.PI / 6.0);
/** The opposite offset. */
private static final double OPP = Math.sin(Math.PI / 6.0);
/**
* Calculates the item label anchor point.
*
* @param anchor the anchor.
* @param x the x coordinate.
* @param y the y coordinate.
* @param orientation the plot orientation.
*
* @return The anchor point (never <code>null</code>).
*/
protected Point2D calculateLabelAnchorPoint(ItemLabelAnchor anchor,
double x, double y, PlotOrientation orientation) {
Point2D result = null;
if (anchor == ItemLabelAnchor.CENTER) {
result = new Point2D.Double(x, y);
}
else if (anchor == ItemLabelAnchor.INSIDE1) {
result = new Point2D.Double(x + OPP * this.itemLabelAnchorOffset,
y - ADJ * this.itemLabelAnchorOffset);
}
else if (anchor == ItemLabelAnchor.INSIDE2) {
result = new Point2D.Double(x + ADJ * this.itemLabelAnchorOffset,
y - OPP * this.itemLabelAnchorOffset);
}
else if (anchor == ItemLabelAnchor.INSIDE3) {
result = new Point2D.Double(x + this.itemLabelAnchorOffset, y);
}
else if (anchor == ItemLabelAnchor.INSIDE4) {
result = new Point2D.Double(x + ADJ * this.itemLabelAnchorOffset,
y + OPP * this.itemLabelAnchorOffset);
}
else if (anchor == ItemLabelAnchor.INSIDE5) {
result = new Point2D.Double(x + OPP * this.itemLabelAnchorOffset,
y + ADJ * this.itemLabelAnchorOffset);
}
else if (anchor == ItemLabelAnchor.INSIDE6) {
result = new Point2D.Double(x, y + this.itemLabelAnchorOffset);
}
else if (anchor == ItemLabelAnchor.INSIDE7) {
result = new Point2D.Double(x - OPP * this.itemLabelAnchorOffset,
y + ADJ * this.itemLabelAnchorOffset);
}
else if (anchor == ItemLabelAnchor.INSIDE8) {
result = new Point2D.Double(x - ADJ * this.itemLabelAnchorOffset,
y + OPP * this.itemLabelAnchorOffset);
}
else if (anchor == ItemLabelAnchor.INSIDE9) {
result = new Point2D.Double(x - this.itemLabelAnchorOffset, y);
}
else if (anchor == ItemLabelAnchor.INSIDE10) {
result = new Point2D.Double(x - ADJ * this.itemLabelAnchorOffset,
y - OPP * this.itemLabelAnchorOffset);
}
else if (anchor == ItemLabelAnchor.INSIDE11) {
result = new Point2D.Double(x - OPP * this.itemLabelAnchorOffset,
y - ADJ * this.itemLabelAnchorOffset);
}
else if (anchor == ItemLabelAnchor.INSIDE12) {
result = new Point2D.Double(x, y - this.itemLabelAnchorOffset);
}
else if (anchor == ItemLabelAnchor.OUTSIDE1) {
result = new Point2D.Double(
x + 2.0 * OPP * this.itemLabelAnchorOffset,
y - 2.0 * ADJ * this.itemLabelAnchorOffset);
}
else if (anchor == ItemLabelAnchor.OUTSIDE2) {
result = new Point2D.Double(
x + 2.0 * ADJ * this.itemLabelAnchorOffset,
y - 2.0 * OPP * this.itemLabelAnchorOffset);
}
else if (anchor == ItemLabelAnchor.OUTSIDE3) {
result = new Point2D.Double(x + 2.0 * this.itemLabelAnchorOffset,
y);
}
else if (anchor == ItemLabelAnchor.OUTSIDE4) {
result = new Point2D.Double(
x + 2.0 * ADJ * this.itemLabelAnchorOffset,
y + 2.0 * OPP * this.itemLabelAnchorOffset);
}
else if (anchor == ItemLabelAnchor.OUTSIDE5) {
result = new Point2D.Double(
x + 2.0 * OPP * this.itemLabelAnchorOffset,
y + 2.0 * ADJ * this.itemLabelAnchorOffset);
}
else if (anchor == ItemLabelAnchor.OUTSIDE6) {
result = new Point2D.Double(x,
y + 2.0 * this.itemLabelAnchorOffset);
}
else if (anchor == ItemLabelAnchor.OUTSIDE7) {
result = new Point2D.Double(
x - 2.0 * OPP * this.itemLabelAnchorOffset,
y + 2.0 * ADJ * this.itemLabelAnchorOffset);
}
else if (anchor == ItemLabelAnchor.OUTSIDE8) {
result = new Point2D.Double(
x - 2.0 * ADJ * this.itemLabelAnchorOffset,
y + 2.0 * OPP * this.itemLabelAnchorOffset);
}
else if (anchor == ItemLabelAnchor.OUTSIDE9) {
result = new Point2D.Double(x - 2.0 * this.itemLabelAnchorOffset,
y);
}
else if (anchor == ItemLabelAnchor.OUTSIDE10) {
result = new Point2D.Double(
x - 2.0 * ADJ * this.itemLabelAnchorOffset,
y - 2.0 * OPP * this.itemLabelAnchorOffset);
}
else if (anchor == ItemLabelAnchor.OUTSIDE11) {
result = new Point2D.Double(
x - 2.0 * OPP * this.itemLabelAnchorOffset,
y - 2.0 * ADJ * this.itemLabelAnchorOffset);
}
else if (anchor == ItemLabelAnchor.OUTSIDE12) {
result = new Point2D.Double(x,
y - 2.0 * this.itemLabelAnchorOffset);
}
return result;
}
/**
* Registers an object to receive notification of changes to the renderer.
*
* @param listener the listener (<code>null</code> not permitted).
*
* @see #removeChangeListener(RendererChangeListener)
*/
public void addChangeListener(RendererChangeListener listener) {
ParamChecks.nullNotPermitted(listener, "listener");
this.listenerList.add(RendererChangeListener.class, listener);
}
/**
* Deregisters an object so that it no longer receives
* notification of changes to the renderer.
*
* @param listener the object (<code>null</code> not permitted).
*
* @see #addChangeListener(RendererChangeListener)
*/
public void removeChangeListener(RendererChangeListener listener) {
ParamChecks.nullNotPermitted(listener, "listener");
this.listenerList.remove(RendererChangeListener.class, listener);
}
/**
* Returns <code>true</code> if the specified object is registered with
* the dataset as a listener. Most applications won't need to call this
* method, it exists mainly for use by unit testing code.
*
* @param listener the listener.
*
* @return A boolean.
*/
public boolean hasListener(EventListener listener) {
List<Object> list = Arrays.asList(this.listenerList.getListenerList());
return list.contains(listener);
}
/**
* Sends a {@link RendererChangeEvent} to all registered listeners.
*
* @since 1.0.5
*/
protected void fireChangeEvent() {
// the commented out code would be better, but only if
// RendererChangeEvent is immutable, which it isn't. See if there is
// a way to fix this...
//if (this.event == null) {
// this.event = new RendererChangeEvent(this);
//}
//notifyListeners(this.event);
notifyListeners(new RendererChangeEvent(this));
}
/**
* Notifies all registered listeners that the renderer has been modified.
*
* @param event information about the change event.
*/
public void notifyListeners(RendererChangeEvent event) {
Object[] ls = this.listenerList.getListenerList();
for (int i = ls.length - 2; i >= 0; i -= 2) {
if (ls[i] == RendererChangeListener.class) {
((RendererChangeListener) ls[i + 1]).rendererChanged(event);
}
}
}
/**
* 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 AbstractRenderer)) {
return false;
}
AbstractRenderer that = (AbstractRenderer) obj;
if (this.dataBoundsIncludesVisibleSeriesOnly
!= that.dataBoundsIncludesVisibleSeriesOnly) {
return false;
}
if (this.treatLegendShapeAsLine != that.treatLegendShapeAsLine) {
return false;
}
if (this.defaultEntityRadius != that.defaultEntityRadius) {
return false;
}
if (!this.seriesVisibleList.equals(that.seriesVisibleList)) {
return false;
}
if (this.defaultSeriesVisible != that.defaultSeriesVisible) {
return false;
}
if (!this.seriesVisibleInLegendList.equals(
that.seriesVisibleInLegendList)) {
return false;
}
if (this.defaultSeriesVisibleInLegend
!= that.defaultSeriesVisibleInLegend) {
return false;
}
if (!ObjectUtilities.equal(this.paintList, that.paintList)) {
return false;
}
if (!PaintUtilities.equal(this.defaultPaint, that.defaultPaint)) {
return false;
}
if (!ObjectUtilities.equal(this.fillPaintList, that.fillPaintList)) {
return false;
}
if (!PaintUtilities.equal(this.defaultFillPaint,
that.defaultFillPaint)) {
return false;
}
if (!ObjectUtilities.equal(this.outlinePaintList,
that.outlinePaintList)) {
return false;
}
if (!PaintUtilities.equal(this.defaultOutlinePaint,
that.defaultOutlinePaint)) {
return false;
}
if (!ObjectUtilities.equal(this.strokeList, that.strokeList)) {
return false;
}
if (!ObjectUtilities.equal(this.defaultStroke, that.defaultStroke)) {
return false;
}
if (!ObjectUtilities.equal(this.outlineStrokeList,
that.outlineStrokeList)) {
return false;
}
if (!ObjectUtilities.equal(this.defaultOutlineStroke,
that.defaultOutlineStroke)) {
return false;
}
if (!ObjectUtilities.equal(this.shapeList, that.shapeList)) {
return false;
}
if (!ShapeUtilities.equal(this.defaultShape, that.defaultShape)) {
return false;
}
if (!ObjectUtilities.equal(this.itemLabelsVisibleList,
that.itemLabelsVisibleList)) {
return false;
}
if (!ObjectUtilities.equal(this.defaultItemLabelsVisible,
that.defaultItemLabelsVisible)) {
return false;
}
if (!ObjectUtilities.equal(this.itemLabelFontList,
that.itemLabelFontList)) {
return false;
}
if (!ObjectUtilities.equal(this.defaultItemLabelFont,
that.defaultItemLabelFont)) {
return false;
}
if (!ObjectUtilities.equal(this.itemLabelPaintList,
that.itemLabelPaintList)) {
return false;
}
if (!PaintUtilities.equal(this.defaultItemLabelPaint,
that.defaultItemLabelPaint)) {
return false;
}
if (!ObjectUtilities.equal(this.positiveItemLabelPositionList,
that.positiveItemLabelPositionList)) {
return false;
}
if (!ObjectUtilities.equal(this.defaultPositiveItemLabelPosition,
that.defaultPositiveItemLabelPosition)) {
return false;
}
if (!ObjectUtilities.equal(this.negativeItemLabelPositionList,
that.negativeItemLabelPositionList)) {
return false;
}
if (!ObjectUtilities.equal(this.defaultNegativeItemLabelPosition,
that.defaultNegativeItemLabelPosition)) {
return false;
}
if (this.itemLabelAnchorOffset != that.itemLabelAnchorOffset) {
return false;
}
if (!ObjectUtilities.equal(this.createEntitiesList,
that.createEntitiesList)) {
return false;
}
if (this.defaultCreateEntities != that.defaultCreateEntities) {
return false;
}
if (!ObjectUtilities.equal(this.legendShapeList,
that.legendShapeList)) {
return false;
}
if (!ShapeUtilities.equal(this.defaultLegendShape,
that.defaultLegendShape)) {
return false;
}
if (!ObjectUtilities.equal(this.legendTextFont, that.legendTextFont)) {
return false;
}
if (!ObjectUtilities.equal(this.defaultLegendTextFont,
that.defaultLegendTextFont)) {
return false;
}
if (!ObjectUtilities.equal(this.legendTextPaint,
that.legendTextPaint)) {
return false;
}
if (!PaintUtilities.equal(this.defaultLegendTextPaint,
that.defaultLegendTextPaint)) {
return false;
}
return true;
}
/**
* Returns a hashcode for the renderer.
*
* @return The hashcode.
*/
@Override
public int hashCode() {
int result = 193;
result = HashUtilities.hashCode(result, this.seriesVisibleList);
result = HashUtilities.hashCode(result, this.defaultSeriesVisible);
result = HashUtilities.hashCode(result, this.seriesVisibleInLegendList);
result = HashUtilities.hashCode(result, this.defaultSeriesVisibleInLegend);
result = HashUtilities.hashCode(result, this.paintList);
result = HashUtilities.hashCode(result, this.defaultPaint);
result = HashUtilities.hashCode(result, this.fillPaintList);
result = HashUtilities.hashCode(result, this.defaultFillPaint);
result = HashUtilities.hashCode(result, this.outlinePaintList);
result = HashUtilities.hashCode(result, this.defaultOutlinePaint);
result = HashUtilities.hashCode(result, this.strokeList);
result = HashUtilities.hashCode(result, this.defaultStroke);
result = HashUtilities.hashCode(result, this.outlineStrokeList);
result = HashUtilities.hashCode(result, this.defaultOutlineStroke);
// shapeList
// baseShape
result = HashUtilities.hashCode(result, this.itemLabelsVisibleList);
result = HashUtilities.hashCode(result, this.defaultItemLabelsVisible);
// itemLabelFontList
// baseItemLabelFont
// itemLabelPaintList
// baseItemLabelPaint
// positiveItemLabelPositionList
// basePositiveItemLabelPosition
// negativeItemLabelPositionList
// baseNegativeItemLabelPosition
// itemLabelAnchorOffset
// createEntityList
// baseCreateEntities
return result;
}
/**
* Returns an independent copy of the renderer.
*
* @return A clone.
*
* @throws CloneNotSupportedException if some component of the renderer
* does not support cloning.
*/
@Override
protected Object clone() throws CloneNotSupportedException {
AbstractRenderer clone = (AbstractRenderer) super.clone();
if (this.seriesVisibleList != null) {
clone.seriesVisibleList
= (BooleanList) this.seriesVisibleList.clone();
}
if (this.seriesVisibleInLegendList != null) {
clone.seriesVisibleInLegendList
= (BooleanList) this.seriesVisibleInLegendList.clone();
}
// 'paint' : immutable, no need to clone reference
if (this.paintList != null) {
clone.paintList = (PaintList) this.paintList.clone();
}
// 'basePaint' : immutable, no need to clone reference
if (this.fillPaintList != null) {
clone.fillPaintList = (PaintList) this.fillPaintList.clone();
}
// 'outlinePaint' : immutable, no need to clone reference
if (this.outlinePaintList != null) {
clone.outlinePaintList = (PaintList) this.outlinePaintList.clone();
}
// 'baseOutlinePaint' : immutable, no need to clone reference
// 'stroke' : immutable, no need to clone reference
if (this.strokeList != null) {
clone.strokeList = (StrokeList) this.strokeList.clone();
}
// 'baseStroke' : immutable, no need to clone reference
// 'outlineStroke' : immutable, no need to clone reference
if (this.outlineStrokeList != null) {
clone.outlineStrokeList
= (StrokeList) this.outlineStrokeList.clone();
}
// 'baseOutlineStroke' : immutable, no need to clone reference
if (this.shapeList != null) {
clone.shapeList = (ShapeList) this.shapeList.clone();
}
if (this.defaultShape != null) {
clone.defaultShape = ShapeUtilities.clone(this.defaultShape);
}
// 'itemLabelsVisible' : immutable, no need to clone reference
if (this.itemLabelsVisibleList != null) {
clone.itemLabelsVisibleList
= (BooleanList) this.itemLabelsVisibleList.clone();
}
// 'basePaint' : immutable, no need to clone reference
// 'itemLabelFont' : immutable, no need to clone reference
if (this.itemLabelFontList != null) {
clone.itemLabelFontList
= (ObjectList<Font>) this.itemLabelFontList.clone();
}
// 'baseItemLabelFont' : immutable, no need to clone reference
// 'itemLabelPaint' : immutable, no need to clone reference
if (this.itemLabelPaintList != null) {
clone.itemLabelPaintList
= (PaintList) this.itemLabelPaintList.clone();
}
// 'baseItemLabelPaint' : immutable, no need to clone reference
// 'postiveItemLabelAnchor' : immutable, no need to clone reference
if (this.positiveItemLabelPositionList != null) {
clone.positiveItemLabelPositionList
= (ObjectList<ItemLabelPosition>) this.positiveItemLabelPositionList.clone();
}
// 'baseItemLabelAnchor' : immutable, no need to clone reference
// 'negativeItemLabelAnchor' : immutable, no need to clone reference
if (this.negativeItemLabelPositionList != null) {
clone.negativeItemLabelPositionList
= (ObjectList<ItemLabelPosition>) this.negativeItemLabelPositionList.clone();
}
// 'baseNegativeItemLabelAnchor' : immutable, no need to clone reference
if (this.createEntitiesList != null) {
clone.createEntitiesList
= (BooleanList) this.createEntitiesList.clone();
}
if (this.legendShapeList != null) {
clone.legendShapeList = (ShapeList) this.legendShapeList.clone();
}
if (this.legendTextFont != null) {
clone.legendTextFont = (ObjectList<Font>) this.legendTextFont.clone();
}
if (this.legendTextPaint != null) {
clone.legendTextPaint = (PaintList) this.legendTextPaint.clone();
}
clone.listenerList = new EventListenerList();
clone.event = null;
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.defaultPaint, stream);
SerialUtilities.writePaint(this.defaultFillPaint, stream);
SerialUtilities.writePaint(this.defaultOutlinePaint, stream);
SerialUtilities.writeStroke(this.defaultStroke, stream);
SerialUtilities.writeStroke(this.defaultOutlineStroke, stream);
SerialUtilities.writeShape(this.defaultShape, stream);
SerialUtilities.writePaint(this.defaultItemLabelPaint, stream);
SerialUtilities.writeShape(this.defaultLegendShape, stream);
SerialUtilities.writePaint(this.defaultLegendTextPaint, 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.defaultPaint = SerialUtilities.readPaint(stream);
this.defaultFillPaint = SerialUtilities.readPaint(stream);
this.defaultOutlinePaint = SerialUtilities.readPaint(stream);
this.defaultStroke = SerialUtilities.readStroke(stream);
this.defaultOutlineStroke = SerialUtilities.readStroke(stream);
this.defaultShape = SerialUtilities.readShape(stream);
this.defaultItemLabelPaint = SerialUtilities.readPaint(stream);
this.defaultLegendShape = SerialUtilities.readShape(stream);
this.defaultLegendTextPaint = SerialUtilities.readPaint(stream);
// listeners are not restored automatically, but storage must be
// provided...
this.listenerList = new EventListenerList();
}
}
| 109,772 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
Renderer.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/renderer/Renderer.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.]
*
* -------------
* Renderer.java
* -------------
*
* (C) Copyright 2012, by Object Refinery Limited and Contributors.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* ------------- JFREECHART Future State Edition (1.2.0?) ---------------------
* < under development >
*
*/
package org.jfree.chart.renderer;
import java.awt.Font;
import java.awt.Paint;
import java.awt.Shape;
import java.awt.Stroke;
import org.jfree.chart.LegendItem;
import org.jfree.chart.LegendItemSource;
import org.jfree.chart.event.RendererChangeEvent;
import org.jfree.chart.event.RendererChangeListener;
import org.jfree.chart.labels.ItemLabelPosition;
/**
* A base interface for renderers.
*/
public interface Renderer extends LegendItemSource {
/**
* Returns the number of passes through the dataset required by the
* renderer. Usually this will be one, but some renderers may use
* a second or third pass to overlay items on top of things that were
* drawn in an earlier pass.
*
* @return The pass count.
*/
public int getPassCount();
/**
* Add a renderer change listener.
*
* @param listener the listener.
*
* @see #removeChangeListener(RendererChangeListener)
*/
public void addChangeListener(RendererChangeListener listener);
/**
* Removes a change listener.
*
* @param listener the listener.
*
* @see #addChangeListener(RendererChangeListener)
*/
public void removeChangeListener(RendererChangeListener listener);
//// VISIBLE //////////////////////////////////////////////////////////////
/**
* Returns a boolean that indicates whether or not the specified item
* should be drawn.
*
* @param series the series index.
* @param item the item index.
*
* @return A boolean.
*/
public boolean getItemVisible(int series, int item);
/**
* Returns a boolean that indicates whether or not the specified series
* should be drawn.
*
* @param series the series index.
*
* @return A boolean.
*/
public boolean isSeriesVisible(int series);
/**
* Returns the flag that controls whether a series is visible.
*
* @param series the series index (zero-based).
*
* @return The flag (possibly <code>null</code>).
*
* @see #setSeriesVisible(int, Boolean)
*/
public Boolean getSeriesVisible(int series);
/**
* Sets the flag that controls whether a series is visible and sends a
* {@link RendererChangeEvent} to all registered listeners.
*
* @param series the series index (zero-based).
* @param visible the flag (<code>null</code> permitted).
*
* @see #getSeriesVisible(int)
*/
public void setSeriesVisible(int series, Boolean visible);
/**
* Sets the flag that controls whether a series is visible and, if
* requested, sends a {@link RendererChangeEvent} to all registered
* listeners.
*
* @param series the series index.
* @param visible the flag (<code>null</code> permitted).
* @param notify notify listeners?
*
* @see #getSeriesVisible(int)
*/
public void setSeriesVisible(int series, Boolean visible, boolean notify);
/**
* Returns the default visibility for all series.
*
* @return The default visibility.
*
* @see #setDefaultSeriesVisible(boolean)
*/
public boolean getDefaultSeriesVisible();
/**
* Sets the default visibility and sends a {@link RendererChangeEvent} to all
* registered listeners.
*
* @param visible the flag.
*
* @see #getDefaultSeriesVisible()
*/
public void setDefaultSeriesVisible(boolean visible);
/**
* Sets the base visibility and, if requested, sends
* a {@link RendererChangeEvent} to all registered listeners.
*
* @param visible the visibility.
* @param notify notify listeners?
*
* @see #getDefaultSeriesVisible()
*/
public void setDefaultSeriesVisible(boolean visible, boolean notify);
// SERIES VISIBLE IN LEGEND (not yet respected by all renderers)
/**
* Returns <code>true</code> if the series should be shown in the legend,
* and <code>false</code> otherwise.
*
* @param series the series index.
*
* @return A boolean.
*/
public boolean isSeriesVisibleInLegend(int series);
/**
* Returns the flag that controls whether a series is visible in the
* legend. This method returns only the "per series" settings - to
* incorporate the override and base settings as well, you need to use the
* {@link #isSeriesVisibleInLegend(int)} method.
*
* @param series the series index (zero-based).
*
* @return The flag (possibly <code>null</code>).
*
* @see #setSeriesVisibleInLegend(int, Boolean)
*/
public Boolean getSeriesVisibleInLegend(int series);
/**
* Sets the flag that controls whether a series is visible in the legend
* and sends a {@link RendererChangeEvent} to all registered listeners.
*
* @param series the series index (zero-based).
* @param visible the flag (<code>null</code> permitted).
*
* @see #getSeriesVisibleInLegend(int)
*/
public void setSeriesVisibleInLegend(int series, Boolean visible);
/**
* Sets the flag that controls whether a series is visible in the legend
* and, if requested, sends a {@link RendererChangeEvent} to all registered
* listeners.
*
* @param series the series index.
* @param visible the flag (<code>null</code> permitted).
* @param notify notify listeners?
*
* @see #getSeriesVisibleInLegend(int)
*/
public void setSeriesVisibleInLegend(int series, Boolean visible,
boolean notify);
/**
* Returns the default visibility in the legend for all series.
*
* @return The base visibility.
*
* @see #setDefaultSeriesVisibleInLegend(boolean)
*/
public boolean getDefaultSeriesVisibleInLegend();
/**
* Sets the default visibility in the legend and sends a
* {@link RendererChangeEvent} to all registered listeners.
*
* @param visible the flag.
*
* @see #getDefaultSeriesVisibleInLegend()
*/
public void setDefaultSeriesVisibleInLegend(boolean visible);
/**
* Sets the default visibility in the legend and, if requested, sends
* a {@link RendererChangeEvent} to all registered listeners.
*
* @param visible the visibility.
* @param notify notify listeners?
*
* @see #getDefaultSeriesVisibleInLegend()
*/
public void setDefaultSeriesVisibleInLegend(boolean visible, boolean notify);
//// PAINT /////////////////////////////////////////////////////////////////
/**
* Returns the paint used to fill data items as they are drawn.
*
* @param row the row (or series) index (zero-based).
* @param column the column (or category) index (zero-based).
*
* @return The paint (never <code>null</code>).
*/
public Paint getItemPaint(int row, int column);
/**
* Returns the paint used to fill an item drawn by the renderer.
*
* @param series the series index (zero-based).
*
* @return The paint (possibly <code>null</code>).
*
* @see #setSeriesPaint(int, Paint)
*/
public Paint getSeriesPaint(int series);
/**
* Sets the paint used for a series and sends a {@link RendererChangeEvent}
* to all registered listeners.
*
* @param series the series index (zero-based).
* @param paint the paint (<code>null</code> permitted).
*
* @see #getSeriesPaint(int)
*/
public void setSeriesPaint(int series, Paint paint);
public void setSeriesPaint(int series, Paint paint, boolean notify);
/**
* Returns the default paint.
*
* @return The default paint (never <code>null</code>).
*
* @see #setDefaultPaint(Paint)
*/
public Paint getDefaultPaint();
/**
* Sets the default paint and sends a {@link RendererChangeEvent} to all
* registered listeners.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getDefaultPaint()
*/
public void setDefaultPaint(Paint paint);
public void setDefaultPaint(Paint paint, boolean notify);
//// FILL PAINT /////////////////////////////////////////////////////////
/**
* Returns the paint used to fill data items as they are drawn.
*
* @param row the row (or series) index (zero-based).
* @param column the column (or category) index (zero-based).
*
* @return The paint (never <code>null</code>).
*/
public Paint getItemFillPaint(int row, int column);
/**
* Returns the paint used to fill an item drawn by the renderer.
*
* @param series the series (zero-based index).
*
* @return The paint (possibly <code>null</code>).
*
* @see #setSeriesFillPaint(int, Paint)
*/
public Paint getSeriesFillPaint(int series);
/**
* Sets the paint used for a series outline and sends a
* {@link RendererChangeEvent} to all registered listeners.
*
* @param series the series index (zero-based).
* @param paint the paint (<code>null</code> permitted).
*
* @see #getSeriesFillPaint(int)
*/
public void setSeriesFillPaint(int series, Paint paint);
public void setSeriesFillPaint(int series, Paint paint, boolean notify);
/**
* Returns the default fill paint.
*
* @return The paint (never <code>null</code>).
*
* @see #setDefaultFillPaint(Paint)
*/
public Paint getDefaultFillPaint();
/**
* Sets the default fill paint and sends a {@link RendererChangeEvent} to
* all registered listeners.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getDefaultFillPaint()
*/
public void setDefaultFillPaint(Paint paint);
public void setDefaultFillPaint(Paint paint, boolean notify);
//// OUTLINE PAINT /////////////////////////////////////////////////////////
/**
* Returns the paint used to outline data items as they are drawn.
*
* @param row the row (or series) index (zero-based).
* @param column the column (or category) index (zero-based).
*
* @return The paint (never <code>null</code>).
*/
public Paint getItemOutlinePaint(int row, int column);
/**
* Returns the paint used to outline an item drawn by the renderer.
*
* @param series the series (zero-based index).
*
* @return The paint (possibly <code>null</code>).
*
* @see #setSeriesOutlinePaint(int, Paint)
*/
public Paint getSeriesOutlinePaint(int series);
/**
* Sets the paint used for a series outline and sends a
* {@link RendererChangeEvent} to all registered listeners.
*
* @param series the series index (zero-based).
* @param paint the paint (<code>null</code> permitted).
*
* @see #getSeriesOutlinePaint(int)
*/
public void setSeriesOutlinePaint(int series, Paint paint);
public void setSeriesOutlinePaint(int series, Paint paint, boolean notify);
/**
* Returns the default outline paint.
*
* @return The paint (never <code>null</code>).
*
* @see #setDefaultOutlinePaint(Paint)
*/
public Paint getDefaultOutlinePaint();
/**
* Sets the default outline paint and sends a {@link RendererChangeEvent} to
* all registered listeners.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getDefaultOutlinePaint()
*/
public void setDefaultOutlinePaint(Paint paint);
public void setDefaultOutlinePaint(Paint paint, boolean notify);
//// STROKE ////////////////////////////////////////////////////////////////
/**
* Returns the stroke used to draw data items.
*
* @param row the row (or series) index (zero-based).
* @param column the column (or category) index (zero-based).
*
* @return The stroke (never <code>null</code>).
*/
public Stroke getItemStroke(int row, int column);
/**
* Returns the stroke used to draw the items in a series.
*
* @param series the series (zero-based index).
*
* @return The stroke (never <code>null</code>).
*
* @see #setSeriesStroke(int, Stroke)
*/
public Stroke getSeriesStroke(int series);
/**
* Sets the stroke used for a series and sends a
* {@link RendererChangeEvent} to all registered listeners.
*
* @param series the series index (zero-based).
* @param stroke the stroke (<code>null</code> permitted).
*
* @see #getSeriesStroke(int)
*/
public void setSeriesStroke(int series, Stroke stroke);
public void setSeriesStroke(int series, Stroke stroke, boolean notify);
/**
* Returns the default stroke.
*
* @return The default stroke (never <code>null</code>).
*
* @see #setDefaultStroke(Stroke)
*/
public Stroke getDefaultStroke();
/**
* Sets the default stroke and sends a {@link RendererChangeEvent} to all
* registered listeners.
*
* @param stroke the stroke (<code>null</code> not permitted).
*
* @see #getDefaultStroke()
*/
public void setDefaultStroke(Stroke stroke);
public void setDefaultStroke(Stroke stroke, boolean notify);
//// OUTLINE STROKE ////////////////////////////////////////////////////////
/**
* Returns the stroke used to outline data items.
* <p>
* The default implementation passes control to the
* lookupSeriesOutlineStroke method. You can override this method if you
* require different behaviour.
*
* @param row the row (or series) index (zero-based).
* @param column the column (or category) index (zero-based).
*
* @return The stroke (never <code>null</code>).
*/
public Stroke getItemOutlineStroke(int row, int column);
/**
* Returns the stroke used to outline the items in a series.
*
* @param series the series (zero-based index).
*
* @return The stroke (possibly <code>null</code>).
*
* @see #setSeriesOutlineStroke(int, Stroke)
*/
public Stroke getSeriesOutlineStroke(int series);
/**
* Sets the outline stroke used for a series and sends a
* {@link RendererChangeEvent} to all registered listeners.
*
* @param series the series index (zero-based).
* @param stroke the stroke (<code>null</code> permitted).
*
* @see #getSeriesOutlineStroke(int)
*/
public void setSeriesOutlineStroke(int series, Stroke stroke);
public void setSeriesOutlineStroke(int series, Stroke stroke, boolean notify);
/**
* Returns the default outline stroke.
*
* @return The stroke (never <code>null</code>).
*
* @see #setDefaultOutlineStroke(Stroke)
*/
public Stroke getDefaultOutlineStroke();
/**
* Sets the default outline stroke and sends a {@link RendererChangeEvent} to
* all registered listeners.
*
* @param stroke the stroke (<code>null</code> not permitted).
*
* @see #getDefaultOutlineStroke()
*/
public void setDefaultOutlineStroke(Stroke stroke);
public void setDefaultOutlineStroke(Stroke stroke, boolean notify);
//// SHAPE /////////////////////////////////////////////////////////////////
/**
* Returns a shape used to represent a data item.
*
* @param row the row (or series) index (zero-based).
* @param column the column (or category) index (zero-based).
*
* @return The shape (never <code>null</code>).
*/
public Shape getItemShape(int row, int column);
/**
* Returns a shape used to represent the items in a series.
*
* @param series the series (zero-based index).
*
* @return The shape (possibly <code>null</code>).
*
* @see #setSeriesShape(int, Shape)
*/
public Shape getSeriesShape(int series);
/**
* Sets the shape used for a series and sends a {@link RendererChangeEvent}
* to all registered listeners.
*
* @param series the series index (zero-based).
* @param shape the shape (<code>null</code> permitted).
*
* @see #getSeriesShape(int)
*/
public void setSeriesShape(int series, Shape shape);
public void setSeriesShape(int series, Shape shape, boolean notify);
/**
* Returns the default shape.
*
* @return The shape (never <code>null</code>).
*
* @see #setDefaultShape(Shape)
*/
public Shape getDefaultShape();
/**
* Sets the default shape and sends a {@link RendererChangeEvent} to all
* registered listeners.
*
* @param shape the shape (<code>null</code> not permitted).
*
* @see #getDefaultShape()
*/
public void setDefaultShape(Shape shape);
public void setDefaultShape(Shape shape, boolean notify);
//// LEGEND ITEMS ///////////////////////////////////////////////////////////
/**
* Returns a legend item for a series. This method can return
* <code>null</code>, in which case the series will have no entry in the
* legend.
*
* @param datasetIndex the dataset index (zero-based).
* @param series the series (zero-based index).
*
* @return The legend item (possibly <code>null</code>).
*/
public LegendItem getLegendItem(int datasetIndex, int series);
// ITEM LABELS VISIBLE
/**
* Returns <code>true</code> if an item label is visible, and
* <code>false</code> otherwise.
*
* @param row the row index (zero-based).
* @param column the column index (zero-based).
*
* @return A boolean.
*/
public boolean isItemLabelVisible(int row, int column);
/**
* Returns <code>true</code> if the item labels for a series are visible,
* and <code>false</code> otherwise.
*
* @param series the series index (zero-based).
*
* @return A boolean.
*
* @see #setSeriesItemLabelsVisible(int, Boolean)
*/
public boolean isSeriesItemLabelsVisible(int series);
/**
* Sets a flag that controls the visibility of the item labels for a series.
*
* @param series the series index (zero-based).
* @param visible the flag.
*
* @see #isSeriesItemLabelsVisible(int)
*/
public void setSeriesItemLabelsVisible(int series, boolean visible);
/**
* Sets a flag that controls the visibility of the item labels for a series.
*
* @param series the series index (zero-based).
* @param visible the flag (<code>null</code> permitted).
*
* @see #isSeriesItemLabelsVisible(int)
*/
public void setSeriesItemLabelsVisible(int series, Boolean visible);
/**
* Sets the visibility of item labels for a series and, if requested, sends
* a {@link RendererChangeEvent} to all registered listeners.
*
* @param series the series index (zero-based).
* @param visible the visible flag.
* @param notify a flag that controls whether or not listeners are
* notified.
*
* @see #isSeriesItemLabelsVisible(int)
*/
public void setSeriesItemLabelsVisible(int series, Boolean visible,
boolean notify);
/**
* Returns the default setting for item label visibility.
*
* @return A flag.
*
* @see #setDefaultItemLabelsVisible(boolean)
*/
public boolean getDefaultItemLabelsVisible();
/**
* Sets the default flag that controls whether or not item labels are visible
* and sends a {@link RendererChangeEvent} to all registered listeners.
*
* @param visible the flag.
*
* @see #getDefaultItemLabelsVisible()
*/
public void setDefaultItemLabelsVisible(boolean visible);
/**
* Sets the default visibility for item labels and, if requested, sends a
* {@link RendererChangeEvent} to all registered listeners.
*
* @param visible the visibility flag.
* @param notify a flag that controls whether or not listeners are
* notified.
*
* @see #getDefaultItemLabelsVisible()
*/
public void setDefaultItemLabelsVisible(boolean visible, boolean notify);
//// ITEM LABEL FONT //////////////////////////////////////////////////////
/**
* Returns the font for an item label.
*
* @param row the row index (zero-based).
* @param column the column index (zero-based).
*
* @return The font (never <code>null</code>).
*/
public Font getItemLabelFont(int row, int column);
/**
* Returns the font for all the item labels in a series.
*
* @param series the series index (zero-based).
*
* @return The font (possibly <code>null</code>).
*
* @see #setSeriesItemLabelFont(int, Font)
*/
public Font getSeriesItemLabelFont(int series);
/**
* Sets the item label font for a series and sends a
* {@link RendererChangeEvent} to all registered listeners.
*
* @param series the series index (zero-based).
* @param font the font (<code>null</code> permitted).
*
* @see #getSeriesItemLabelFont(int)
*/
public void setSeriesItemLabelFont(int series, Font font);
public void setSeriesItemLabelFont(int series, Font font, boolean notify);
/**
* Returns the default item label font (this is used when no other font
* setting is available).
*
* @return The font (<code>never</code> null).
*
* @see #setDefaultItemLabelFont(Font)
*/
public Font getDefaultItemLabelFont();
/**
* Sets the default item label font and sends a {@link RendererChangeEvent}
* to all registered listeners.
*
* @param font the font (<code>null</code> not permitted).
*
* @see #getDefaultItemLabelFont()
*/
public void setDefaultItemLabelFont(Font font);
public void setDefaultItemLabelFont(Font font, boolean notify);
//// ITEM LABEL PAINT /////////////////////////////////////////////////////
/**
* Returns the paint used to draw an item label.
*
* @param row the row index (zero based).
* @param column the column index (zero based).
*
* @return The paint (never <code>null</code>).
*/
public Paint getItemLabelPaint(int row, int column);
/**
* Returns the paint used to draw the item labels for a series.
*
* @param series the series index (zero based).
*
* @return The paint (possibly <code>null</code>).
*
* @see #setSeriesItemLabelPaint(int, Paint)
*/
public Paint getSeriesItemLabelPaint(int series);
/**
* Sets the item label paint for a series and sends a
* {@link RendererChangeEvent} to all registered listeners.
*
* @param series the series (zero based index).
* @param paint the paint (<code>null</code> permitted).
*
* @see #getSeriesItemLabelPaint(int)
*/
public void setSeriesItemLabelPaint(int series, Paint paint);
public void setSeriesItemLabelPaint(int series, Paint paint, boolean notify);
/**
* Returns the default item label paint.
*
* @return The paint (never <code>null</code>).
*
* @see #setDefaultItemLabelPaint(Paint)
*/
public Paint getDefaultItemLabelPaint();
/**
* Sets the default item label paint and sends a {@link RendererChangeEvent}
* to all registered listeners.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getDefaultItemLabelPaint()
*/
public void setDefaultItemLabelPaint(Paint paint);
public void setDefaultItemLabelPaint(Paint paint, boolean notify);
// POSITIVE ITEM LABEL POSITION...
/**
* Returns the item label position for positive values.
*
* @param row the row index (zero-based).
* @param column the column index (zero-based).
*
* @return The item label position (never <code>null</code>).
*/
public ItemLabelPosition getPositiveItemLabelPosition(int row, int column);
/**
* Returns the item label position for all positive values in a series.
*
* @param series the series index (zero-based).
*
* @return The item label position.
*
* @see #setSeriesPositiveItemLabelPosition(int, ItemLabelPosition)
*/
public ItemLabelPosition getSeriesPositiveItemLabelPosition(int series);
/**
* Sets the item label position for all positive values in a series and
* sends a {@link RendererChangeEvent} to all registered listeners.
*
* @param series the series index (zero-based).
* @param position the position (<code>null</code> permitted).
*
* @see #getSeriesPositiveItemLabelPosition(int)
*/
public void setSeriesPositiveItemLabelPosition(int series,
ItemLabelPosition position);
/**
* Sets the item label position for all positive values in a series and (if
* requested) sends a {@link RendererChangeEvent} to all registered
* listeners.
*
* @param series the series index (zero-based).
* @param position the position (<code>null</code> permitted).
* @param notify notify registered listeners?
*
* @see #getSeriesPositiveItemLabelPosition(int)
*/
public void setSeriesPositiveItemLabelPosition(int series,
ItemLabelPosition position, boolean notify);
/**
* Returns the default positive item label position.
*
* @return The position.
*
* @see #setDefaultPositiveItemLabelPosition(ItemLabelPosition)
*/
public ItemLabelPosition getDefaultPositiveItemLabelPosition();
/**
* Sets the default positive item label position.
*
* @param position the position.
*
* @see #getDefaultPositiveItemLabelPosition()
*/
public void setDefaultPositiveItemLabelPosition(ItemLabelPosition position);
/**
* Sets the default positive item label position and, if requested, sends a
* {@link RendererChangeEvent} to all registered listeners.
*
* @param position the position.
* @param notify notify registered listeners?
*
* @see #getDefaultPositiveItemLabelPosition()
*/
public void setDefaultPositiveItemLabelPosition(ItemLabelPosition position,
boolean notify);
// NEGATIVE ITEM LABEL POSITION...
/**
* Returns the item label position for negative values. This method can be
* overridden to provide customisation of the item label position for
* individual data items.
*
* @param row the row index (zero-based).
* @param column the column (zero-based).
*
* @return The item label position.
*/
public ItemLabelPosition getNegativeItemLabelPosition(int row, int column);
/**
* Returns the item label position for all negative values in a series.
*
* @param series the series index (zero-based).
*
* @return The item label position.
*
* @see #setSeriesNegativeItemLabelPosition(int, ItemLabelPosition)
*/
public ItemLabelPosition getSeriesNegativeItemLabelPosition(int series);
/**
* Sets the item label position for negative values in a series and sends a
* {@link RendererChangeEvent} to all registered listeners.
*
* @param series the series index (zero-based).
* @param position the position (<code>null</code> permitted).
*
* @see #getSeriesNegativeItemLabelPosition(int)
*/
public void setSeriesNegativeItemLabelPosition(int series,
ItemLabelPosition position);
/**
* Sets the item label position for negative values in a series and (if
* requested) sends a {@link RendererChangeEvent} to all registered
* listeners.
*
* @param series the series index (zero-based).
* @param position the position (<code>null</code> permitted).
* @param notify notify registered listeners?
*
* @see #getSeriesNegativeItemLabelPosition(int)
*/
public void setSeriesNegativeItemLabelPosition(int series,
ItemLabelPosition position, boolean notify);
/**
* Returns the default item label position for negative values.
*
* @return The position.
*
* @see #setDefaultNegativeItemLabelPosition(ItemLabelPosition)
*/
public ItemLabelPosition getDefaultNegativeItemLabelPosition();
/**
* Sets the default item label position for negative values and sends a
* {@link RendererChangeEvent} to all registered listeners.
*
* @param position the position.
*
* @see #getDefaultNegativeItemLabelPosition()
*/
public void setDefaultNegativeItemLabelPosition(ItemLabelPosition position);
/**
* Sets the default negative item label position and, if requested, sends a
* {@link RendererChangeEvent} to all registered listeners.
*
* @param position the position.
* @param notify notify registered listeners?
*
* @see #getDefaultNegativeItemLabelPosition()
*/
public void setDefaultNegativeItemLabelPosition(ItemLabelPosition position,
boolean notify);
// CREATE ENTITIES
public boolean getItemCreateEntity(int series, int item);
public Boolean getSeriesCreateEntities(int series);
public void setSeriesCreateEntities(int series, Boolean create);
public void setSeriesCreateEntities(int series, Boolean create,
boolean notify);
public boolean getDefaultCreateEntities();
public void setDefaultCreateEntities(boolean create);
public void setDefaultCreateEntities(boolean create, boolean notify);
}
| 29,997 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
LookupPaintScale.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/renderer/LookupPaintScale.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.]
*
* ---------------------
* LookupPaintScale.java
* ---------------------
* (C) Copyright 2006-2013, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 05-Jul-2006 : Version 1 (DG);
* 31-Jan-2007 : Fixed serialization support (DG);
* 09-Mar-2007 : Fixed cloning (DG);
* 14-Jun-2007 : Use double primitive in PaintItem (DG);
* 28-Mar-2009 : Made PaintItem inner class static (DG);
* 17-Jun-2012 : Removed JCommon dependencies (DG);
*/
package org.jfree.chart.renderer;
import java.awt.Color;
import java.awt.Paint;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Collections;
import java.util.List;
import org.jfree.chart.util.PaintUtilities;
import org.jfree.chart.util.ParamChecks;
import org.jfree.chart.util.PublicCloneable;
import org.jfree.chart.util.SerialUtilities;
/**
* A paint scale that uses a lookup table to associate paint instances
* with data value ranges.
*
* @since 1.0.4
*/
public class LookupPaintScale implements PaintScale, PublicCloneable,
Serializable {
/**
* Stores the paint for a value.
*/
static class PaintItem implements Comparable<PaintItem>, Serializable {
/** For serialization. */
static final long serialVersionUID = 698920578512361570L;
/** The value. */
double value;
/** The paint. */
transient Paint paint;
/**
* Creates a new instance.
*
* @param value the value.
* @param paint the paint.
*/
public PaintItem(double value, Paint paint) {
this.value = value;
this.paint = paint;
}
/**
* Compares this item to an arbitrary object.
*
* @param that the object.
*
* @return An int defining the relative order of the objects.
*/
@Override
public int compareTo(PaintItem that) {
double d1 = this.value;
double d2 = that.value;
if (d1 > d2) {
return 1;
}
if (d1 < d2) {
return -1;
}
return 0;
}
/**
* Tests this item 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 PaintItem)) {
return false;
}
PaintItem that = (PaintItem) obj;
if (this.value != that.value) {
return false;
}
if (!PaintUtilities.equal(this.paint, that.paint)) {
return false;
}
return true;
}
@Override
public int hashCode() {
int hash = 7;
hash = 37 * hash + (int) (Double.doubleToLongBits(this.value)
^ (Double.doubleToLongBits(this.value) >>> 32));
hash = 37 * hash + (this.paint != null ? this.paint.hashCode() : 0);
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.paint, 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);
}
}
/** For serialization. */
static final long serialVersionUID = -5239384246251042006L;
/** The lower bound. */
private double lowerBound;
/** The upper bound. */
private double upperBound;
/** The default paint. */
private transient Paint defaultPaint;
/** The lookup table. */
private List<PaintItem> lookupTable;
/**
* Creates a new paint scale.
*/
public LookupPaintScale() {
this(0.0, 1.0, Color.LIGHT_GRAY);
}
/**
* Creates a new paint scale with the specified default paint.
*
* @param lowerBound the lower bound.
* @param upperBound the upper bound.
* @param defaultPaint the default paint (<code>null</code> not
* permitted).
*/
public LookupPaintScale(double lowerBound, double upperBound,
Paint defaultPaint) {
if (lowerBound >= upperBound) {
throw new IllegalArgumentException(
"Requires lowerBound < upperBound.");
}
ParamChecks.nullNotPermitted(defaultPaint, "defaultPaint");
this.lowerBound = lowerBound;
this.upperBound = upperBound;
this.defaultPaint = defaultPaint;
this.lookupTable = new java.util.ArrayList<PaintItem>();
}
/**
* Returns the default paint (never <code>null</code>).
*
* @return The default paint.
*/
public Paint getDefaultPaint() {
return this.defaultPaint;
}
/**
* Returns the lower bound.
*
* @return The lower bound.
*
* @see #getUpperBound()
*/
@Override
public double getLowerBound() {
return this.lowerBound;
}
/**
* Returns the upper bound.
*
* @return The upper bound.
*
* @see #getLowerBound()
*/
@Override
public double getUpperBound() {
return this.upperBound;
}
/**
* Adds an entry to the lookup table. Any values from <code>n</code> up
* to but not including the next value in the table take on the specified
* <code>paint</code>.
*
* @param value the data value.
* @param paint the paint (<code>null</code> not permitted).
*
* @since 1.0.6
*/
public void add(double value, Paint paint) {
ParamChecks.requireInRange(value, "value", lowerBound, upperBound);
ParamChecks.nullNotPermitted(paint, "paint");
PaintItem item = new PaintItem(value, paint);
int index = Collections.binarySearch(this.lookupTable, item);
if (index >= 0) {
this.lookupTable.set(index, item);
}
else {
this.lookupTable.add(-(index + 1), item);
}
}
/**
* Returns the paint associated with the specified value.
*
* @param value the value.
*
* @return The paint.
*
* @see #getDefaultPaint()
*/
@Override
public Paint getPaint(double value) {
// handle value outside bounds...
if (value < this.lowerBound || value > this.upperBound
|| Double.isNaN(value)) {
return this.defaultPaint;
}
int count = this.lookupTable.size();
if (count == 0) {
return this.defaultPaint;
}
// handle special case where value is less that item zero
PaintItem item = this.lookupTable.get(0);
if (value < item.value) {
return this.defaultPaint;
}
// for value in bounds, do the lookup...
int low = 0;
int high = this.lookupTable.size() - 1;
while (high - low > 1) {
int current = (low + high) / 2;
item = this.lookupTable.get(current);
if (value >= item.value) {
low = current;
}
else {
high = current;
}
}
if (high > low) {
item = this.lookupTable.get(high);
if (value < item.value) {
item = this.lookupTable.get(low);
}
}
return (item != null ? item.paint : this.defaultPaint);
}
/**
* 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 LookupPaintScale)) {
return false;
}
LookupPaintScale that = (LookupPaintScale) obj;
if (this.lowerBound != that.lowerBound) {
return false;
}
if (this.upperBound != that.upperBound) {
return false;
}
if (!PaintUtilities.equal(this.defaultPaint, that.defaultPaint)) {
return false;
}
if (!this.lookupTable.equals(that.lookupTable)) {
return false;
}
return true;
}
@Override
public int hashCode() {
int hash = 7;
hash = 59 * hash + (int) (Double.doubleToLongBits(this.lowerBound)
^ (Double.doubleToLongBits(this.lowerBound) >>> 32));
hash = 59 * hash + (int) (Double.doubleToLongBits(this.upperBound)
^ (Double.doubleToLongBits(this.upperBound) >>> 32));
hash = 59 * hash + (this.defaultPaint != null
? this.defaultPaint.hashCode() : 0);
hash = 59 * hash + (this.lookupTable != null
? this.lookupTable.hashCode() : 0);
return hash;
}
/**
* Returns a clone of the instance.
*
* @return A clone.
*
* @throws CloneNotSupportedException if there is a problem cloning the
* instance.
*/
@Override
public Object clone() throws CloneNotSupportedException {
LookupPaintScale clone = (LookupPaintScale) super.clone();
clone.lookupTable = new java.util.ArrayList<PaintItem>(this.lookupTable);
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.defaultPaint, 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.defaultPaint = SerialUtilities.readPaint(stream);
}
}
| 12,285 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
OutlierList.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/renderer/OutlierList.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.]
*
* ----------------
* OutlierList.java
* ----------------
* (C) Copyright 2003-2008, 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 (DG);
* 28-Aug-2003 : Minor tidy-up including Javadocs (DG);
* ------------- JFREECHART 1.0.x ---------------------------------------------
* 02-Feb-2007 : Removed author tags from all over JFreeChart sources (DG);
*
*/
package org.jfree.chart.renderer;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.List;
/**
* A collection of outliers for a single entity in a box and whisker plot.
*
* Outliers are grouped in lists for each entity. Lists contain
* one or more outliers, determined by whether overlaps have
* occured. Overlapping outliers are grouped in the same list.
*
* Each list contains an averaged outlier, which is the same as a single
* outlier if there is only one outlier in the list, but the average of
* all the outliers in the list if there is more than one.
*
* NB This is simply my scheme for displaying outliers, and might not be
* acceptable by the wider community.
*/
public class OutlierList {
/** Storage for the outliers. */
private List<Outlier> outliers;
/** The averaged outlier. */
private Outlier averagedOutlier;
/**
* A flag that indicates whether or not there are multiple outliers in the
* list.
*/
private boolean multiple = false;
/**
* Creates a new list containing a single outlier.
*
* @param outlier the outlier.
*/
public OutlierList(Outlier outlier) {
this.outliers = new ArrayList<Outlier>();
setAveragedOutlier(outlier);
}
/**
* Adds an outlier to the list.
*
* @param outlier the outlier.
*
* @return A boolean.
*/
public boolean add(Outlier outlier) {
return this.outliers.add(outlier);
}
/**
* Returns the number of outliers in the list.
*
* @return The item count.
*/
public int getItemCount() {
return this.outliers.size();
}
/**
* Returns the averaged outlier.
*
* @return The averaged outlier.
*/
public Outlier getAveragedOutlier() {
return this.averagedOutlier;
}
/**
* Sets the averaged outlier.
*
* @param averagedOutlier the averaged outlier.
*/
public void setAveragedOutlier(Outlier averagedOutlier) {
this.averagedOutlier = averagedOutlier;
}
/**
* Returns <code>true</code> if the list contains multiple outliers, and
* <code>false</code> otherwise.
*
* @return A boolean.
*/
public boolean isMultiple() {
return this.multiple;
}
/**
* Sets the flag that indicates whether or not this list represents
* multiple outliers.
*
* @param multiple the flag.
*/
public void setMultiple(boolean multiple) {
this.multiple = multiple;
}
/**
* Returns <code>true</code> if the outlier overlaps, and
* <code>false</code> otherwise.
*
* @param other the outlier.
*
* @return A boolean.
*/
public boolean isOverlapped(Outlier other) {
if (other == null) {
return false;
}
boolean result = other.overlaps(getAveragedOutlier());
return result;
}
/**
* Updates the averaged outlier.
*
*/
public void updateAveragedOutlier() {
double totalXCoords = 0.0;
double totalYCoords = 0.0;
int size = getItemCount();
for (Outlier o : this.outliers) {
totalXCoords += o.getX();
totalYCoords += o.getY();
}
getAveragedOutlier().getPoint().setLocation(
new Point2D.Double(totalXCoords / size, totalYCoords / size));
}
}
| 5,275 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
XYItemRenderer.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/renderer/xy/XYItemRenderer.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.]
*
* -------------------
* XYItemRenderer.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);
* Sylvain Vieujot;
* Focus Computer Services Limited;
* Richard Atkinson;
*
* 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 ---------------------------------------------
* 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);
* 17-Jun-2012 : Removed JCommon dependencies (DG);
*
* ------------- JFREECHART Future State Edition (1.2.0?) ---------------------
* < under development >
*
*/
package org.jfree.chart.renderer.xy;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.Stroke;
import java.awt.geom.Rectangle2D;
import java.util.Collection;
import org.jfree.chart.annotations.XYAnnotation;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.ui.Layer;
import org.jfree.chart.event.RendererChangeEvent;
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.Marker;
import org.jfree.chart.plot.PlotRenderingInfo;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.Renderer;
import org.jfree.chart.urls.XYURLGenerator;
import org.jfree.data.Range;
import org.jfree.data.xy.XYDataset;
/**
* Interface for rendering the visual representation of a single (x, y) item on
* an {@link XYPlot}.
* <p>
* To support cloning charts, it is recommended that renderers implement both
* the {@link Cloneable} and <code>PublicCloneable</code> interfaces.
*/
public interface XYItemRenderer extends Renderer {
/**
* Returns the plot that this renderer has been assigned to.
*
* @return The plot.
*/
public XYPlot getPlot();
/**
* Sets the plot that this renderer is assigned to. This method will be
* called by the plot class...you do not need to call it yourself.
*
* @param plot the plot.
*/
public void setPlot(XYPlot plot);
/**
* 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.
*/
public Range findDomainBounds(XYDataset dataset);
/**
* Returns the lower and upper bounds (range) of the y-values in the
* specified dataset. The implementation of this method will take
* into account the presentation used by the renderers (for example,
* a renderer that "stacks" values will return a bigger range than
* a renderer that doesn't).
*
* @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(XYDataset dataset);
//// LEGEND ITEM LABEL GENERATOR //////////////////////////////////////////
/**
* Returns the legend item label generator.
*
* @return The legend item label generator (never <code>null</code>).
*
* @see #setLegendItemLabelGenerator(XYSeriesLabelGenerator)
*/
public XYSeriesLabelGenerator getLegendItemLabelGenerator();
/**
* Sets the legend item label generator and sends a
* {@link RendererChangeEvent} to all registered listeners.
*
* @param generator the generator (<code>null</code> not permitted).
*/
public void setLegendItemLabelGenerator(XYSeriesLabelGenerator generator);
public void setLegendItemLabelGenerator(XYSeriesLabelGenerator generator,
boolean notify);
//// TOOL TIP GENERATOR ///////////////////////////////////////////////////
/**
* Returns the tool tip generator for a data item.
*
* @param row the row index (zero based).
* @param column the column index (zero based).
*
* @return The generator (possibly <code>null</code>).
*/
public XYToolTipGenerator getToolTipGenerator(int row, int column);
/**
* Returns the tool tip generator for a series.
*
* @param series the series index (zero based).
*
* @return The generator (possibly <code>null</code>).
*
* @see #setSeriesToolTipGenerator(int, XYToolTipGenerator)
*/
public XYToolTipGenerator getSeriesToolTipGenerator(int 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)
*/
public void setSeriesToolTipGenerator(int series,
XYToolTipGenerator generator);
public void setSeriesToolTipGenerator(int series,
XYToolTipGenerator generator, boolean notify);
/**
* Returns the default tool tip generator.
*
* @return The generator (possibly <code>null</code>).
*
* @see #setDefaultToolTipGenerator(XYToolTipGenerator)
*/
public XYToolTipGenerator getDefaultToolTipGenerator();
/**
* 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()
*/
public void setDefaultToolTipGenerator(XYToolTipGenerator generator);
public void setDefaultToolTipGenerator(XYToolTipGenerator generator,
boolean notify);
//// ITEM LABEL GENERATOR /////////////////////////////////////////////////
/**
* Returns the item label generator for a data item.
*
* @param row the row index (zero based).
* @param column the column index (zero based).
*
* @return The generator (possibly <code>null</code>).
*/
public XYItemLabelGenerator getItemLabelGenerator(int row, int column);
/**
* 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, XYItemLabelGenerator)
*/
public XYItemLabelGenerator 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 (<code>null</code> permitted).
*
* @see #getSeriesItemLabelGenerator(int)
*/
public void setSeriesItemLabelGenerator(int series,
XYItemLabelGenerator generator);
public void setSeriesItemLabelGenerator(int series,
XYItemLabelGenerator generator, boolean notify);
/**
* Returns the default item label generator.
*
* @return The generator (possibly <code>null</code>).
*
* @see #setDefaultItemLabelGenerator(XYItemLabelGenerator)
*/
public XYItemLabelGenerator 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(XYItemLabelGenerator generator);
public void setDefaultItemLabelGenerator(XYItemLabelGenerator generator,
boolean notify);
//// URL GENERATOR ////////////////////////////////////////////////////////
/**
* Returns the URL generator for HTML image maps.
*
* @return The URL generator (possibly null).
*/
public XYURLGenerator getURLGenerator();
/**
* Sets the URL generator for HTML image maps.
*
* @param urlGenerator the URL generator (null permitted).
*/
public void setURLGenerator(XYURLGenerator urlGenerator);
public void setURLGenerator(XYURLGenerator urlGenerator, boolean notify);
// FIXME: series level
//// ANNOTATIONS //////////////////////////////////////////////////////////
/**
* 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).
*/
public void addAnnotation(XYAnnotation annotation);
/**
* Adds an annotation to the specified layer.
*
* @param annotation the annotation (<code>null</code> not permitted).
* @param layer the layer (<code>null</code> not permitted).
*/
public void addAnnotation(XYAnnotation annotation, Layer 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.
*/
public boolean removeAnnotation(XYAnnotation annotation);
/**
* Removes all annotations and sends a {@link RendererChangeEvent}
* to all registered listeners.
*/
public void removeAnnotations();
/**
* Returns a collection of the annotations that are assigned to the
* renderer.
*
* @return A collection of annotations (possibly empty but never
* <code>null</code>).
*/
public Collection<XYAnnotation> getAnnotations();
/**
* 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.
*/
public void drawAnnotations(Graphics2D g2, Rectangle2D dataArea,
ValueAxis domainAxis, ValueAxis rangeAxis, Layer layer,
PlotRenderingInfo info);
//// DRAWING //////////////////////////////////////////////////////////////
/**
* 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 dataset.
* @param info an optional info collection object to return data back to
* the caller.
*
* @return The number of passes the renderer requires.
*/
public XYItemRendererState initialise(Graphics2D g2,
Rectangle2D dataArea,
XYPlot plot,
XYDataset dataset,
PlotRenderingInfo info);
/**
* Called for each item to be plotted.
* <p>
* The {@link XYPlot} can make multiple passes through the dataset,
* depending on the value returned by the renderer's initialise() method.
*
* @param g2 the graphics device.
* @param state the renderer state.
* @param dataArea the area within which the data is being rendered.
* @param info collects drawing info.
* @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.
*/
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);
/**
* 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.
*/
public void fillDomainGridBand(Graphics2D g2,
XYPlot plot,
ValueAxis axis,
Rectangle2D dataArea,
double start, double end);
/**
* 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.
*/
public void fillRangeGridBand(Graphics2D g2,
XYPlot plot,
ValueAxis axis,
Rectangle2D dataArea,
double start, double end);
/**
* Draws a grid line against 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.
*/
public void drawDomainGridline(Graphics2D g2,
XYPlot plot,
ValueAxis axis,
Rectangle2D dataArea,
double value);
/**
* 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.
* @param value the data value.
* @param paint the paint (<code>null</code> not permitted).
* @param stroke the stroke (<code>null</code> not permitted).
*/
public void drawRangeGridline(Graphics2D g2, XYPlot plot, ValueAxis axis,
Rectangle2D dataArea, double value, Paint paint, Stroke stroke);
/**
* Draws the specified <code>marker</code> against the domain axis.
*
* @param g2 the graphics device.
* @param plot the plot.
* @param axis the value axis.
* @param marker the marker.
* @param dataArea the axis data area.
*/
public void drawDomainMarker(Graphics2D g2, XYPlot plot, ValueAxis axis,
Marker marker, Rectangle2D dataArea);
/**
* Draws a horizontal line across the chart to represent a 'range marker'.
*
* @param g2 the graphics device.
* @param plot the plot.
* @param axis the value axis.
* @param marker the marker line.
* @param dataArea the axis data area.
*/
public void drawRangeMarker(Graphics2D g2, XYPlot plot, ValueAxis axis,
Marker marker, Rectangle2D dataArea);
}
| 17,925 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
XYBarRenderer.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/renderer/xy/XYBarRenderer.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.]
*
* ------------------
* XYBarRenderer.java
* ------------------
* (C) Copyright 2001-2012, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): Richard Atkinson;
* Christian W. Zuckschwerdt;
* Bill Kelemen;
* Marc van Glabbeek (bug 1775452);
* Richard West, Advanced Micro Devices, Inc.;
*
* Changes
* -------
* 13-Dec-2001 : Version 1, makes VerticalXYBarPlot class redundant (DG);
* 23-Jan-2002 : Added DrawInfo parameter to drawItem() method (DG);
* 09-Apr-2002 : Removed the translated zero from the drawItem method. Override
* the initialise() method to calculate it (DG);
* 24-May-2002 : Incorporated tooltips into chart entities (DG);
* 25-Jun-2002 : Removed redundant import (DG);
* 05-Aug-2002 : Small modification to drawItem method to support URLs for HTML
* image maps (RA);
* 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);
* 24-Aug-2003 : Added null checks in drawItem (BK);
* 16-Sep-2003 : Changed ChartRenderingInfo --> PlotRenderingInfo (DG);
* 07-Oct-2003 : Added renderer state (DG);
* 05-Dec-2003 : Changed call to obtain outline paint (DG);
* 10-Feb-2004 : Added state class, updated drawItem() method to make
* cut-and-paste overriding easier, and replaced property change
* with RendererChangeEvent (DG);
* 25-Feb-2004 : Replaced CrosshairInfo with CrosshairState (DG);
* 26-Apr-2004 : Added gradient paint transformer (DG);
* 19-May-2004 : Fixed bug (879709) with bar zero value for secondary axis (DG);
* 15-Jul-2004 : Switched getX() with getXValue() and getY() with
* getYValue() (DG);
* 01-Sep-2004 : Added a flag to control whether or not the bar outlines are
* drawn (DG);
* 03-Sep-2004 : Added option to use y-interval from dataset to determine the
* length of the bars (DG);
* 08-Sep-2004 : Added equals() method and updated clone() method (DG);
* 26-Jan-2005 : Added override for getLegendItem() method (DG);
* 20-Apr-2005 : Use generators for label tooltips and URLs (DG);
* 19-May-2005 : Added minimal item label implementation - needs improving (DG);
* 14-Oct-2005 : Fixed rendering problem with inverted axes (DG);
* ------------- JFREECHART 1.0.x ---------------------------------------------
* 21-Jun-2006 : Improved item label handling - see bug 1501768 (DG);
* 24-Aug-2006 : Added crosshair support (DG);
* 13-Dec-2006 : Updated getLegendItems() to return gradient paint
* transformer (DG);
* 02-Feb-2007 : Changed setUseYInterval() to only notify when the flag
* changes (DG);
* 06-Feb-2007 : Fixed bug 1086307, crosshairs with multiple axes (DG);
* 09-Feb-2007 : Updated getLegendItem() to observe drawBarOutline flag (DG);
* 05-Mar-2007 : Applied patch 1671126 by Sergei Ivanov, to fix rendering with
* LogarithmicAxis (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);
* 15-Jun-2007 : Changed default for drawBarOutline to false (DG);
* 26-Sep-2007 : Fixed bug 1775452, problem with bar margins for inverted
* axes, thanks to Marc van Glabbeek (DG);
* 12-Nov-2007 : Fixed NPE in drawItemLabel() method, thanks to Richard West
* (see patch 1827829) (DG);
* 17-Jun-2008 : Apply legend font and paint attributes (DG);
* 19-Jun-2008 : Added findRangeBounds() method override to fix bug in default
* axis range (DG);
* 24-Jun-2008 : Added new barPainter mechanism (DG);
* 03-Feb-2009 : Added defaultShadowsVisible flag (DG);
* 05-Feb-2009 : Added barAlignmentFactor (DG);
* 10-May-2012 : Fix findDomainBounds() and findRangeBounds() to account for
* non-visible series (DG);
* 16-Jun-2012 : Removed JCommon dependencies (DG);
*
*/
package org.jfree.chart.renderer.xy;
import java.awt.Font;
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.Serializable;
import org.jfree.chart.LegendItem;
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.PublicCloneable;
import org.jfree.chart.entity.EntityCollection;
import org.jfree.chart.event.RendererChangeEvent;
import org.jfree.chart.labels.ItemLabelAnchor;
import org.jfree.chart.labels.ItemLabelPosition;
import org.jfree.chart.labels.XYItemLabelGenerator;
import org.jfree.chart.labels.XYSeriesLabelGenerator;
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.text.TextUtilities;
import org.jfree.data.Range;
import org.jfree.data.xy.IntervalXYDataset;
import org.jfree.data.xy.XYDataset;
/**
* A renderer that draws bars on an {@link XYPlot} (requires an
* {@link IntervalXYDataset}). The example shown here is generated by the
* <code>XYBarChartDemo1.java</code> program included in the JFreeChart
* demo collection:
* <br><br>
* <img src="../../../../../images/XYBarRendererSample.png"
* alt="XYBarRendererSample.png" />
*/
public class XYBarRenderer extends AbstractXYItemRenderer
implements XYItemRenderer, Cloneable, PublicCloneable, Serializable {
/** For serialization. */
private static final long serialVersionUID = 770559577251370036L;
/**
* The default bar painter assigned to each new instance of this renderer.
*
* @since 1.0.11
*/
private static XYBarPainter defaultBarPainter = new GradientXYBarPainter();
/**
* Returns the default bar painter.
*
* @return The default bar painter.
*
* @since 1.0.11
*/
public static XYBarPainter getDefaultBarPainter() {
return XYBarRenderer.defaultBarPainter;
}
/**
* Sets the default bar painter.
*
* @param painter the painter (<code>null</code> not permitted).
*
* @since 1.0.11
*/
public static void setDefaultBarPainter(XYBarPainter painter) {
if (painter == null) {
throw new IllegalArgumentException("Null 'painter' argument.");
}
XYBarRenderer.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 XYBarRenderer.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) {
XYBarRenderer.defaultShadowsVisible = visible;
}
/**
* The state class used by this renderer.
*/
protected class XYBarRendererState extends XYItemRendererState {
/** Base for bars against the range axis, in Java 2D space. */
private double g2Base;
/**
* Creates a new state object.
*
* @param info the plot rendering info.
*/
public XYBarRendererState(PlotRenderingInfo info) {
super(info);
}
/**
* Returns the base (range) value in Java 2D space.
*
* @return The base value.
*/
public double getG2Base() {
return this.g2Base;
}
/**
* Sets the range axis base in Java2D space.
*
* @param value the value.
*/
public void setG2Base(double value) {
this.g2Base = value;
}
}
/** The default base value for the bars. */
private double base;
/**
* A flag that controls whether the bars use the y-interval supplied by the
* dataset.
*/
private boolean useYInterval;
/** Percentage margin (to reduce the width of bars). */
private double margin;
/** A flag that controls whether or not bar outlines are drawn. */
private boolean drawBarOutline;
/**
* 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 bar painter (never <code>null</code>).
*
* @since 1.0.11
*/
private XYBarPainter barPainter;
/**
* The flag that controls whether or not shadows are drawn for the bars.
*
* @since 1.0.11
*/
private boolean shadowsVisible;
/**
* 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;
/**
* A factor used to align the bars about the x-value.
*
* @since 1.0.13
*/
private double barAlignmentFactor;
/**
* The default constructor.
*/
public XYBarRenderer() {
this(0.0);
}
/**
* Constructs a new renderer.
*
* @param margin the percentage amount to trim from the width of each bar.
*/
public XYBarRenderer(double margin) {
super();
this.margin = margin;
this.base = 0.0;
this.useYInterval = false;
this.gradientPaintTransformer = new StandardGradientPaintTransformer();
this.drawBarOutline = false;
setDefaultLegendShape(new Rectangle2D.Double(-3.0, -5.0, 6.0, 10.0));
this.barPainter = getDefaultBarPainter();
this.shadowsVisible = getDefaultShadowsVisible();
this.shadowXOffset = 4.0;
this.shadowYOffset = 4.0;
this.barAlignmentFactor = -1.0;
}
/**
* Returns the base value for the bars.
*
* @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. The base value is not used if the dataset's
* y-interval is being used to determine the bar length.
*
* @param base the new base value.
*
* @see #getBase()
* @see #getUseYInterval()
*/
public void setBase(double base) {
this.base = base;
fireChangeEvent();
}
/**
* Returns a flag that determines whether the y-interval from the dataset is
* used to calculate the length of each bar.
*
* @return A boolean.
*
* @see #setUseYInterval(boolean)
*/
public boolean getUseYInterval() {
return this.useYInterval;
}
/**
* Sets the flag that determines whether the y-interval from the dataset is
* used to calculate the length of each bar, and sends a
* {@link RendererChangeEvent} to all registered listeners.
*
* @param use the flag.
*
* @see #getUseYInterval()
*/
public void setUseYInterval(boolean use) {
if (this.useYInterval != use) {
this.useYInterval = use;
fireChangeEvent();
}
}
/**
* Returns the margin which is a percentage amount by which the bars are
* trimmed.
*
* @return The margin.
*
* @see #setMargin(double)
*/
public double getMargin() {
return this.margin;
}
/**
* Sets the percentage amount by which the bars are trimmed and sends a
* {@link RendererChangeEvent} to all registered listeners.
*
* @param margin the new margin.
*
* @see #getMargin()
*/
public void setMargin(double margin) {
this.margin = margin;
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 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)
* @since 1.0.2
*/
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()
* @since 1.0.2
*/
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 #setNegativeItemLabelPositionFallback(ItemLabelPosition)
* @since 1.0.2
*/
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()
* @since 1.0.2
*/
public void setNegativeItemLabelPositionFallback(
ItemLabelPosition position) {
this.negativeItemLabelPositionFallback = position;
fireChangeEvent();
}
/**
* Returns the bar painter.
*
* @return The bar painter (never <code>null</code>).
*
* @since 1.0.11
*/
public XYBarPainter getBarPainter() {
return this.barPainter;
}
/**
* Sets the bar painter and sends a {@link RendererChangeEvent} to all
* registered listeners.
*
* @param painter the painter (<code>null</code> not permitted).
*
* @since 1.0.11
*/
public void setBarPainter(XYBarPainter 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 the renderer
* draws shadows for the bars, and sends a
* {@link RendererChangeEvent} to all registered listeners.
*
* @param visible the new flag value.
*
* @since 1.0.11
*/
public void setShadowVisible(boolean visible) {
this.shadowsVisible = visible;
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 bar alignment factor.
*
* @return The bar alignment factor.
*
* @since 1.0.13
*/
public double getBarAlignmentFactor() {
return this.barAlignmentFactor;
}
/**
* Sets the bar alignment factor and sends a {@link RendererChangeEvent}
* to all registered listeners. If the alignment factor is outside the
* range 0.0 to 1.0, no alignment will be performed by the renderer.
*
* @param factor the factor.
*
* @since 1.0.13
*/
public void setBarAlignmentFactor(double factor) {
this.barAlignmentFactor = factor;
fireChangeEvent();
}
/**
* Initialises the renderer and returns a state object that should be
* passed to all subsequent calls to the drawItem() method. 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 dataset 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 dataset, PlotRenderingInfo info) {
XYBarRendererState state = new XYBarRendererState(info);
ValueAxis rangeAxis = plot.getRangeAxisForDataset(plot.indexOf(
dataset));
state.setG2Base(rangeAxis.valueToJava2D(this.base, dataArea,
plot.getRangeAxisEdge()));
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) {
XYPlot xyplot = getPlot();
if (xyplot == null) {
return null;
}
XYDataset dataset = xyplot.getDataset(datasetIndex);
if (dataset == null) {
return null;
}
LegendItem result = 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);
}
Shape shape = this.lookupLegendShape(series);
Paint paint = lookupSeriesPaint(series);
Paint outlinePaint = lookupSeriesOutlinePaint(series);
Stroke outlineStroke = lookupSeriesOutlineStroke(series);
if (this.drawBarOutline) {
result = new LegendItem(label, description, toolTipText,
urlText, shape, paint, outlineStroke, outlinePaint);
}
else {
result = new LegendItem(label, description, toolTipText, urlText,
shape, 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);
if (getGradientPaintTransformer() != null) {
result.setFillPaintTransformer(getGradientPaintTransformer());
}
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 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 (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;
}
IntervalXYDataset intervalDataset = (IntervalXYDataset) dataset;
double value0;
double value1;
if (this.useYInterval) {
value0 = intervalDataset.getStartYValue(series, item);
value1 = intervalDataset.getEndYValue(series, item);
}
else {
value0 = this.base;
value1 = intervalDataset.getYValue(series, item);
}
if (Double.isNaN(value0) || Double.isNaN(value1)) {
return;
}
if (value0 <= value1) {
if (!rangeAxis.getRange().intersects(value0, value1)) {
return;
}
}
else {
if (!rangeAxis.getRange().intersects(value1, value0)) {
return;
}
}
double translatedValue0 = rangeAxis.valueToJava2D(value0, dataArea,
plot.getRangeAxisEdge());
double translatedValue1 = rangeAxis.valueToJava2D(value1, dataArea,
plot.getRangeAxisEdge());
double bottom = Math.min(translatedValue0, translatedValue1);
double top = Math.max(translatedValue0, translatedValue1);
double startX = intervalDataset.getStartXValue(series, item);
if (Double.isNaN(startX)) {
return;
}
double endX = intervalDataset.getEndXValue(series, item);
if (Double.isNaN(endX)) {
return;
}
if (startX <= endX) {
if (!domainAxis.getRange().intersects(startX, endX)) {
return;
}
}
else {
if (!domainAxis.getRange().intersects(endX, startX)) {
return;
}
}
// is there an alignment adjustment to be made?
if (this.barAlignmentFactor >= 0.0 && this.barAlignmentFactor <= 1.0) {
double x = intervalDataset.getXValue(series, item);
double interval = endX - startX;
startX = x - interval * this.barAlignmentFactor;
endX = startX + interval;
}
RectangleEdge location = plot.getDomainAxisEdge();
double translatedStartX = domainAxis.valueToJava2D(startX, dataArea,
location);
double translatedEndX = domainAxis.valueToJava2D(endX, dataArea,
location);
double translatedWidth = Math.max(1, Math.abs(translatedEndX
- translatedStartX));
double left = Math.min(translatedStartX, translatedEndX);
if (getMargin() > 0.0) {
double cut = translatedWidth * getMargin();
translatedWidth = translatedWidth - cut;
left = left + cut / 2;
}
Rectangle2D bar = null;
PlotOrientation orientation = plot.getOrientation();
if (orientation == PlotOrientation.HORIZONTAL) {
// clip left and right bounds to data area
bottom = Math.max(bottom, dataArea.getMinX());
top = Math.min(top, dataArea.getMaxX());
bar = new Rectangle2D.Double(
bottom, left, top - bottom, translatedWidth);
}
else if (orientation == PlotOrientation.VERTICAL) {
// clip top and bottom bounds to data area
bottom = Math.max(bottom, dataArea.getMinY());
top = Math.min(top, dataArea.getMaxY());
bar = new Rectangle2D.Double(left, bottom, translatedWidth,
top - bottom);
}
boolean positive = (value1 > 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 (getShadowsVisible()) {
this.barPainter.paintBarShadow(g2, this, series, item, bar, barBase,
!this.useYInterval);
}
this.barPainter.paintBar(g2, this, series, item, bar, barBase);
if (isItemLabelVisible(series, item)) {
XYItemLabelGenerator generator = getItemLabelGenerator(series,
item);
drawItemLabel(g2, dataset, series, item, plot, generator, bar,
value1 < 0.0);
}
// update the crosshair point
double x1 = (startX + endX) / 2.0;
double y1 = dataset.getYValue(series, item);
double transX1 = domainAxis.valueToJava2D(x1, dataArea, location);
double transY1 = rangeAxis.valueToJava2D(y1, dataArea,
plot.getRangeAxisEdge());
int domainAxisIndex = plot.getDomainAxisIndex(domainAxis);
int rangeAxisIndex = plot.getRangeAxisIndex(rangeAxis);
updateCrosshairValues(crosshairState, x1, y1, domainAxisIndex,
rangeAxisIndex, transX1, transY1, plot.getOrientation());
EntityCollection entities = state.getEntityCollection();
if (entities != null) {
addEntity(entities, bar, dataset, series, item, 0.0, 0.0);
}
}
/**
* Draws an item label. This method is provided as an alternative to
* {@link #drawItemLabel(Graphics2D, PlotOrientation, XYDataset, int, int,
* double, double, boolean)} so that the bar can be used to calculate the
* label anchor point.
*
* @param g2 the graphics device.
* @param dataset the dataset.
* @param series the series index.
* @param item the item index.
* @param plot the plot.
* @param generator the label generator (<code>null</code> permitted, in
* which case the method does nothing, just returns).
* @param bar the bar.
* @param negative a flag indicating a negative value.
*/
protected void drawItemLabel(Graphics2D g2, XYDataset dataset,
int series, int item, XYPlot plot, XYItemLabelGenerator generator,
Rectangle2D bar, boolean negative) {
if (generator == null) {
return; // nothing to do
}
String label = generator.generateLabel(dataset, series, item);
if (label == null) {
return; // nothing to do
}
Font labelFont = getItemLabelFont(series, item);
g2.setFont(labelFont);
Paint paint = getItemLabelPaint(series, item);
g2.setPaint(paint);
// find out where to place the label...
ItemLabelPosition position = null;
if (!negative) {
position = getPositiveItemLabelPosition(series, item);
}
else {
position = getNegativeItemLabelPosition(series, item);
}
// 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;
}
/**
* Returns the lower and upper bounds (range) of the x-values in the
* specified dataset. Since this renderer uses the x-interval in the
* dataset, this is taken into account for the range.
*
* @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) {
return findDomainBounds(dataset, true);
}
/**
* Returns the lower and upper bounds (range) of the y-values in the
* specified dataset. If the renderer is plotting the y-interval from the
* dataset, this is taken into account for the range.
*
* @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, this.useYInterval);
}
/**
* Returns a clone of the renderer.
*
* @return A clone.
*
* @throws CloneNotSupportedException if the renderer cannot be cloned.
*/
@Override
public Object clone() throws CloneNotSupportedException {
XYBarRenderer result = (XYBarRenderer) super.clone();
if (this.gradientPaintTransformer != null) {
result.gradientPaintTransformer = ObjectUtilities.clone(this.gradientPaintTransformer);
}
return result;
}
/**
* Tests this renderer 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 XYBarRenderer)) {
return false;
}
XYBarRenderer that = (XYBarRenderer) obj;
if (this.base != that.base) {
return false;
}
if (this.drawBarOutline != that.drawBarOutline) {
return false;
}
if (this.margin != that.margin) {
return false;
}
if (this.useYInterval != that.useYInterval) {
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 (this.shadowXOffset != that.shadowXOffset) {
return false;
}
if (this.shadowYOffset != that.shadowYOffset) {
return false;
}
if (this.barAlignmentFactor != that.barAlignmentFactor) {
return false;
}
return super.equals(obj);
}
}
| 41,965 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
XYDotRenderer.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/renderer/xy/XYDotRenderer.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.]
*
* ------------------
* XYDotRenderer.java
* ------------------
* (C) Copyright 2002-2013, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): Christian W. Zuckschwerdt;
* Michael Zinsmaier;
*
* Changes (from 29-Oct-2002)
* --------------------------
* 29-Oct-2002 : Added standard header (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);
* 25-Feb-2004 : Replaced CrosshairInfo with CrosshairState (DG);
* 19-Jan-2005 : Now uses only primitives from dataset (DG);
* ------------- JFREECHART 1.0.x ---------------------------------------------
* 10-Jul-2006 : Added dotWidth and dotHeight attributes (DG);
* 06-Feb-2007 : Fixed bug 1086307, crosshairs with multiple axes (DG);
* 09-Nov-2007 : Added legend shape attribute, plus override for
* getLegendItem() (DG);
* 17-Jun-2008 : Apply legend shape, font and paint attributes (DG);
* 17-Jun-2012 : Removed JCommon dependencies (DG);
*
*/
package org.jfree.chart.renderer.xy;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.Rectangle;
import java.awt.Shape;
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.ui.RectangleEdge;
import org.jfree.chart.entity.EntityCollection;
import org.jfree.chart.util.PublicCloneable;
import org.jfree.chart.util.ShapeUtilities;
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.ParamChecks;
import org.jfree.chart.util.SerialUtilities;
import org.jfree.data.xy.XYDataset;
/**
* A renderer that draws a small dot at each data point for an {@link XYPlot}.
* The example shown here is generated by the
* <code>ScatterPlotDemo4.java</code> program included in the JFreeChart
* demo collection:
* <br><br>
* <img src="../../../../../images/XYDotRendererSample.png"
* alt="XYDotRendererSample.png" />
*/
public class XYDotRenderer extends AbstractXYItemRenderer
implements XYItemRenderer, PublicCloneable {
/** For serialization. */
private static final long serialVersionUID = -2764344339073566425L;
/** The dot width. */
private int dotWidth;
/** The dot height. */
private int dotHeight;
/**
* The shape that is used to represent an item in the legend.
*
* @since 1.0.7
*/
private transient Shape legendShape;
/**
* Constructs a new renderer.
*/
public XYDotRenderer() {
super();
this.dotWidth = 1;
this.dotHeight = 1;
this.legendShape = new Rectangle2D.Double(-3.0, -3.0, 6.0, 6.0);
}
/**
* Returns the dot width (the default value is 1).
*
* @return The dot width.
*
* @since 1.0.2
* @see #setDotWidth(int)
*/
public int getDotWidth() {
return this.dotWidth;
}
/**
* Sets the dot width and sends a {@link RendererChangeEvent} to all
* registered listeners.
*
* @param w the new width (must be greater than zero).
*
* @throws IllegalArgumentException if <code>w</code> is less than one.
*
* @since 1.0.2
* @see #getDotWidth()
*/
public void setDotWidth(int w) {
if (w < 1) {
throw new IllegalArgumentException("Requires w > 0.");
}
this.dotWidth = w;
fireChangeEvent();
}
/**
* Returns the dot height (the default value is 1).
*
* @return The dot height.
*
* @since 1.0.2
* @see #setDotHeight(int)
*/
public int getDotHeight() {
return this.dotHeight;
}
/**
* Sets the dot height and sends a {@link RendererChangeEvent} to all
* registered listeners.
*
* @param h the new height (must be greater than zero).
*
* @throws IllegalArgumentException if <code>h</code> is less than one.
*
* @since 1.0.2
* @see #getDotHeight()
*/
public void setDotHeight(int h) {
if (h < 1) {
throw new IllegalArgumentException("Requires h > 0.");
}
this.dotHeight = h;
fireChangeEvent();
}
/**
* Returns the shape used to represent an item in the legend.
*
* @return The legend shape (never <code>null</code>).
*
* @see #setLegendShape(Shape)
*
* @since 1.0.7
*/
public Shape getLegendShape() {
return this.legendShape;
}
/**
* Sets the shape used as a line in each legend item and sends a
* {@link RendererChangeEvent} to all registered listeners.
*
* @param shape the shape (<code>null</code> not permitted).
*
* @see #getLegendShape()
*
* @since 1.0.7
*/
public void setLegendShape(Shape shape) {
ParamChecks.nullNotPermitted(shape, "shape");
this.legendShape = shape;
fireChangeEvent();
}
/**
* 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) {
// do nothing if item is not visible
if (!getItemVisible(series, item)) {
return;
}
// get the data point...
double x = dataset.getXValue(series, item);
double y = dataset.getYValue(series, item);
double adjx = (this.dotWidth - 1) / 2.0;
double adjy = (this.dotHeight - 1) / 2.0;
if (!Double.isNaN(y)) {
RectangleEdge xAxisLocation = plot.getDomainAxisEdge();
RectangleEdge yAxisLocation = plot.getRangeAxisEdge();
double transX = domainAxis.valueToJava2D(x, dataArea,
xAxisLocation) - adjx;
double transY = rangeAxis.valueToJava2D(y, dataArea, yAxisLocation)
- adjy;
g2.setPaint(getItemPaint(series, item));
PlotOrientation orientation = plot.getOrientation();
if (orientation == PlotOrientation.HORIZONTAL) {
g2.fillRect((int) transY, (int) transX, this.dotHeight,
this.dotWidth);
}
else if (orientation == PlotOrientation.VERTICAL) {
g2.fillRect((int) transX, (int) transY, this.dotWidth,
this.dotHeight);
}
int domainAxisIndex = plot.getDomainAxisIndex(domainAxis);
int rangeAxisIndex = plot.getRangeAxisIndex(rangeAxis);
updateCrosshairValues(crosshairState, x, y, domainAxisIndex,
rangeAxisIndex, transX, transY, orientation);
// collecting the entity info
if (info != null) {
EntityCollection entities = info.getOwner().getEntityCollection();
if (orientation == PlotOrientation.HORIZONTAL) {
Shape area = new Rectangle((int) transY, (int) transX,
this.dotHeight, this.dotWidth);
addEntity(entities, area, dataset, series, item, transY,
transX);
} else if (orientation == PlotOrientation.VERTICAL) {
Shape area = new Rectangle((int) transX, (int) transY,
this.dotWidth, this.dotHeight);
addEntity(entities, area, dataset, series, item, transX,
transY);
}
}
}
}
/**
* 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) {
// if the renderer isn't assigned to a plot, then we don't have a
// dataset...
XYPlot plot = getPlot();
if (plot == null) {
return null;
}
XYDataset dataset = plot.getDataset(datasetIndex);
if (dataset == null) {
return null;
}
LegendItem result = 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 fillPaint = lookupSeriesPaint(series);
result = new LegendItem(label, description, toolTipText, urlText,
getLegendShape(), fillPaint);
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;
}
/**
* Tests this renderer for equality with an arbitrary object. This method
* returns <code>true</code> if and only if:
*
* <ul>
* <li><code>obj</code> is not <code>null</code>;</li>
* <li><code>obj</code> is an instance of <code>XYDotRenderer</code>;</li>
* <li>both renderers have the same attribute values.
* </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 XYDotRenderer)) {
return false;
}
XYDotRenderer that = (XYDotRenderer) obj;
if (this.dotWidth != that.dotWidth) {
return false;
}
if (this.dotHeight != that.dotHeight) {
return false;
}
if (!ShapeUtilities.equal(this.legendShape, that.legendShape)) {
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 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.legendShape = 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.legendShape, stream);
}
}
| 14,237 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
XYBlockRenderer.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/renderer/xy/XYBlockRenderer.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.]
*
* --------------------
* XYBlockRenderer.java
* --------------------
* (C) Copyright 2006-2012, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 05-Jul-2006 : Version 1 (DG);
* 02-Feb-2007 : Added getPaintScale() method (DG);
* 09-Mar-2007 : Fixed cloning (DG);
* 03-Aug-2007 : Fix for bug 1766646 (DG);
* 07-Apr-2008 : Added entity collection code (DG);
* 22-Apr-2008 : Implemented PublicCloneable (DG);
* 16-Jun-2012 : Removed JCommon dependencies (DG);
*
*/
package org.jfree.chart.renderer.xy;
import java.awt.BasicStroke;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.geom.Rectangle2D;
import java.io.Serializable;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.ui.RectangleAnchor;
import org.jfree.chart.util.PublicCloneable;
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.data.Range;
import org.jfree.data.general.DatasetUtilities;
import org.jfree.data.xy.XYDataset;
import org.jfree.data.xy.XYZDataset;
/**
* A renderer that represents data from an {@link XYZDataset} by drawing a
* color block at each (x, y) point, where the color is a function of the
* z-value from the dataset. The example shown here is generated by the
* <code>XYBlockChartDemo1.java</code> program included in the JFreeChart
* demo collection:
* <br><br>
* <img src="../../../../../images/XYBlockRendererSample.png"
* alt="XYBlockRendererSample.png" />
*
* @since 1.0.4
*/
public class XYBlockRenderer extends AbstractXYItemRenderer
implements XYItemRenderer, Cloneable, PublicCloneable, Serializable {
/**
* The block width (defaults to 1.0).
*/
private double blockWidth = 1.0;
/**
* The block height (defaults to 1.0).
*/
private double blockHeight = 1.0;
/**
* The anchor point used to align each block to its (x, y) location. The
* default value is <code>RectangleAnchor.CENTER</code>.
*/
private RectangleAnchor blockAnchor = RectangleAnchor.CENTER;
/** Temporary storage for the x-offset used to align the block anchor. */
private double xOffset;
/** Temporary storage for the y-offset used to align the block anchor. */
private double yOffset;
/** The paint scale. */
private PaintScale paintScale;
/**
* Creates a new <code>XYBlockRenderer</code> instance with default
* attributes.
*/
public XYBlockRenderer() {
updateOffsets();
this.paintScale = new LookupPaintScale();
}
/**
* Returns the block width, in data/axis units.
*
* @return The block width.
*
* @see #setBlockWidth(double)
*/
public double getBlockWidth() {
return this.blockWidth;
}
/**
* Sets the width of the blocks used to represent each data item and
* sends a {@link RendererChangeEvent} to all registered listeners.
*
* @param width the new width, in data/axis units (must be > 0.0).
*
* @see #getBlockWidth()
*/
public void setBlockWidth(double width) {
if (width <= 0.0) {
throw new IllegalArgumentException(
"The 'width' argument must be > 0.0");
}
this.blockWidth = width;
updateOffsets();
fireChangeEvent();
}
/**
* Returns the block height, in data/axis units.
*
* @return The block height.
*
* @see #setBlockHeight(double)
*/
public double getBlockHeight() {
return this.blockHeight;
}
/**
* Sets the height of the blocks used to represent each data item and
* sends a {@link RendererChangeEvent} to all registered listeners.
*
* @param height the new height, in data/axis units (must be > 0.0).
*
* @see #getBlockHeight()
*/
public void setBlockHeight(double height) {
if (height <= 0.0) {
throw new IllegalArgumentException(
"The 'height' argument must be > 0.0");
}
this.blockHeight = height;
updateOffsets();
fireChangeEvent();
}
/**
* Returns the anchor point used to align a block at its (x, y) location.
* The default values is {@link RectangleAnchor#CENTER}.
*
* @return The anchor point (never <code>null</code>).
*
* @see #setBlockAnchor(RectangleAnchor)
*/
public RectangleAnchor getBlockAnchor() {
return this.blockAnchor;
}
/**
* Sets the anchor point used to align a block at its (x, y) location and
* sends a {@link RendererChangeEvent} to all registered listeners.
*
* @param anchor the anchor.
*
* @see #getBlockAnchor()
*/
public void setBlockAnchor(RectangleAnchor anchor) {
if (anchor == null) {
throw new IllegalArgumentException("Null 'anchor' argument.");
}
if (this.blockAnchor.equals(anchor)) {
return; // no change
}
this.blockAnchor = anchor;
updateOffsets();
fireChangeEvent();
}
/**
* Returns the paint scale used by the renderer.
*
* @return The paint scale (never <code>null</code>).
*
* @see #setPaintScale(PaintScale)
* @since 1.0.4
*/
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()
* @since 1.0.4
*/
public void setPaintScale(PaintScale scale) {
if (scale == null) {
throw new IllegalArgumentException("Null 'scale' argument.");
}
this.paintScale = scale;
fireChangeEvent();
}
/**
* Updates the offsets to take into account the block width, height and
* anchor.
*/
private void updateOffsets() {
if (this.blockAnchor.equals(RectangleAnchor.BOTTOM_LEFT)) {
this.xOffset = 0.0;
this.yOffset = 0.0;
}
else if (this.blockAnchor.equals(RectangleAnchor.BOTTOM)) {
this.xOffset = -this.blockWidth / 2.0;
this.yOffset = 0.0;
}
else if (this.blockAnchor.equals(RectangleAnchor.BOTTOM_RIGHT)) {
this.xOffset = -this.blockWidth;
this.yOffset = 0.0;
}
else if (this.blockAnchor.equals(RectangleAnchor.LEFT)) {
this.xOffset = 0.0;
this.yOffset = -this.blockHeight / 2.0;
}
else if (this.blockAnchor.equals(RectangleAnchor.CENTER)) {
this.xOffset = -this.blockWidth / 2.0;
this.yOffset = -this.blockHeight / 2.0;
}
else if (this.blockAnchor.equals(RectangleAnchor.RIGHT)) {
this.xOffset = -this.blockWidth;
this.yOffset = -this.blockHeight / 2.0;
}
else if (this.blockAnchor.equals(RectangleAnchor.TOP_LEFT)) {
this.xOffset = 0.0;
this.yOffset = -this.blockHeight;
}
else if (this.blockAnchor.equals(RectangleAnchor.TOP)) {
this.xOffset = -this.blockWidth / 2.0;
this.yOffset = -this.blockHeight;
}
else if (this.blockAnchor.equals(RectangleAnchor.TOP_RIGHT)) {
this.xOffset = -this.blockWidth;
this.yOffset = -this.blockHeight;
}
}
/**
* 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) {
if (dataset == null) {
return null;
}
Range r = DatasetUtilities.findDomainBounds(dataset, false);
if (r == null) {
return null;
}
return new Range(r.getLowerBound() + this.xOffset,
r.getUpperBound() + this.blockWidth + this.xOffset);
}
/**
* 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) {
if (dataset != null) {
Range r = DatasetUtilities.findRangeBounds(dataset, false);
if (r == null) {
return null;
}
else {
return new Range(r.getLowerBound() + this.yOffset,
r.getUpperBound() + this.blockHeight + this.yOffset);
}
}
else {
return null;
}
}
/**
* 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 z = 0.0;
if (dataset instanceof XYZDataset) {
z = ((XYZDataset) dataset).getZValue(series, item);
}
Paint p = this.paintScale.getPaint(z);
double xx0 = domainAxis.valueToJava2D(x + this.xOffset, dataArea,
plot.getDomainAxisEdge());
double yy0 = rangeAxis.valueToJava2D(y + this.yOffset, dataArea,
plot.getRangeAxisEdge());
double xx1 = domainAxis.valueToJava2D(x + this.blockWidth
+ this.xOffset, dataArea, plot.getDomainAxisEdge());
double yy1 = rangeAxis.valueToJava2D(y + this.blockHeight
+ this.yOffset, dataArea, plot.getRangeAxisEdge());
Rectangle2D block;
PlotOrientation orientation = plot.getOrientation();
if (orientation.equals(PlotOrientation.HORIZONTAL)) {
block = new Rectangle2D.Double(Math.min(yy0, yy1),
Math.min(xx0, xx1), Math.abs(yy1 - yy0),
Math.abs(xx0 - xx1));
}
else {
block = new Rectangle2D.Double(Math.min(xx0, xx1),
Math.min(yy0, yy1), Math.abs(xx1 - xx0),
Math.abs(yy1 - yy0));
}
g2.setPaint(p);
g2.fill(block);
g2.setStroke(new BasicStroke(1.0f));
g2.draw(block);
EntityCollection entities = state.getEntityCollection();
if (entities != null) {
addEntity(entities, block, dataset, series, item, 0.0, 0.0);
}
}
/**
* Tests this <code>XYBlockRenderer</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>XYBlockRenderer</code> (not
* <code>null</code>);</li>
* <li><code>obj</code> has the same field values as this
* <code>XYBlockRenderer</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 XYBlockRenderer)) {
return false;
}
XYBlockRenderer that = (XYBlockRenderer) obj;
if (this.blockHeight != that.blockHeight) {
return false;
}
if (this.blockWidth != that.blockWidth) {
return false;
}
if (!this.blockAnchor.equals(that.blockAnchor)) {
return false;
}
if (!this.paintScale.equals(that.paintScale)) {
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 {
XYBlockRenderer clone = (XYBlockRenderer) super.clone();
if (this.paintScale instanceof PublicCloneable) {
PublicCloneable pc = (PublicCloneable) this.paintScale;
clone.paintScale = (PaintScale) pc.clone();
}
return clone;
}
}
| 14,891 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
XYSplineRenderer.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/renderer/xy/XYSplineRenderer.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.]
*
* ---------------------
* XYSplineRenderer.java
* ---------------------
* (C) Copyright 2007-2013, by Klaus Rheinwald and Contributors.
*
* Original Author: Klaus Rheinwald;
* Contributor(s): Tobias von Petersdorff ([email protected],
* http://www.wam.umd.edu/~petersd/);
* David Gilbert (for Object Refinery Limited);
*
* Changes:
* --------
* 25-Jul-2007 : Version 1, contributed by Klaus Rheinwald (DG);
* 03-Aug-2007 : Added new constructor (KR);
* 25-Oct-2007 : Prevent duplicate control points (KR);
* 19-May-2009 : Fixed FindBugs warnings, patch by Michal Wozniak (DG);
* 17-Jun-2012 : Removed JCommon dependencies (DG);
*
*/
package org.jfree.chart.renderer.xy;
import java.awt.GradientPaint;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.geom.GeneralPath;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import java.util.List;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.ui.RectangleEdge;
import org.jfree.chart.event.RendererChangeEvent;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.PlotRenderingInfo;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.ui.GradientPaintTransformer;
import org.jfree.chart.ui.StandardGradientPaintTransformer;
import org.jfree.chart.util.ObjectUtilities;
import org.jfree.chart.util.ParamChecks;
import org.jfree.data.xy.XYDataset;
/**
* A renderer that connects data points with natural cubic splines 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>XYSplineRendererDemo1.java</code> program included in the JFreeChart
* demo collection:
* <br><br>
* <img src="../../../../../images/XYSplineRendererSample.png"
* alt="XYSplineRendererSample.png" />
*
* @since 1.0.7
*/
public class XYSplineRenderer extends XYLineAndShapeRenderer {
/**
* An enumeration of the fill types for the renderer.
*
* @since 1.0.17
*/
public static enum FillType {
NONE,
TO_ZERO,
TO_LOWER_BOUND,
TO_UPPER_BOUND
}
/**
* Represents state information that applies to a single rendering of
* a chart.
*/
public static class XYSplineState extends State {
/** The area to fill under the curve. */
public GeneralPath fillArea;
/** The points. */
public List<Point2D> points;
/**
* Creates a new state instance.
*
* @param info the plot rendering info.
*/
public XYSplineState(PlotRenderingInfo info) {
super(info);
this.fillArea = new GeneralPath();
this.points = new ArrayList<Point2D>();
}
}
/**
* Resolution of splines (number of line segments between points)
*/
private int precision;
/**
* A flag that can be set to specify
* to fill the area under the spline.
*/
private FillType fillType;
private GradientPaintTransformer gradientPaintTransformer;
/**
* Creates a new instance with the precision attribute defaulting to 5
* and no fill of the area 'under' the spline.
*/
public XYSplineRenderer() {
this(5, FillType.NONE);
}
/**
* Creates a new renderer with the specified precision
* and no fill of the area 'under' (between '0' and) the spline.
*
* @param precision the number of points between data items.
*/
public XYSplineRenderer(int precision) {
this(precision, FillType.NONE);
}
/**
* Creates a new renderer with the specified precision
* and specified fill of the area 'under' (between '0' and) the spline.
*
* @param precision the number of points between data items.
* @param fillType the type of fill beneath the curve (<code>null</code>
* not permitted).
*
* @since 1.0.17
*/
public XYSplineRenderer(int precision, FillType fillType) {
super();
if (precision <= 0) {
throw new IllegalArgumentException("Requires precision > 0.");
}
ParamChecks.nullNotPermitted(fillType, "fillType");
this.precision = precision;
this.fillType = fillType;
this.gradientPaintTransformer = new StandardGradientPaintTransformer();
}
/**
* Returns the resolution of splines.
*
* @return Number of line segments between points.
*
* @see #setPrecision(int)
*/
public int getPrecision() {
return this.precision;
}
/**
* Set the resolution of splines and sends a {@link RendererChangeEvent}
* to all registered listeners.
*
* @param p number of line segments between points (must be > 0).
*
* @see #getPrecision()
*/
public void setPrecision(int p) {
if (p <= 0) {
throw new IllegalArgumentException("Requires p > 0.");
}
this.precision = p;
fireChangeEvent();
}
/**
* Returns the type of fill that the renderer draws beneath the curve.
*
* @return The type of fill (never <code>null</code>).
*
* @see #setFillMode(FillType)
*
* @since 1.0.17
*/
public FillType getFillType() {
return this.fillType;
}
/**
* Set the fill type and sends a {@link RendererChangeEvent}
* to all registered listeners.
*
* @param fillType the fill type (<code>null</code> not permitted).
*
* @see #getFillType()
*
* @since 1.0.17
*/
public void setFillType(FillType fillType) {
this.fillType = fillType;
fireChangeEvent();
}
/**
* Returns the gradient paint transformer, or <code>null</code>.
*
* @return The gradient paint transformer (possibly <code>null</code>).
*
* @since 1.0.17
*/
public GradientPaintTransformer getGradientPaintTransformer() {
return this.gradientPaintTransformer;
}
/**
* Sets the gradient paint transformer and sends a
* {@link RendererChangeEvent} to all registered listeners.
*
* @param gpt the transformer (<code>null</code> permitted).
*
* @since 1.0.17
*/
public void setGradientPaintTransformer(GradientPaintTransformer gpt) {
this.gradientPaintTransformer = gpt;
fireChangeEvent();
}
/**
* 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) {
setDrawSeriesLineAsPath(true);
XYSplineState state = new XYSplineState(info);
state.setProcessVisibleItemsOnly(false);
return state;
}
/**
* 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 xAxis the domain axis.
* @param yAxis the range axis.
* @param dataArea the area within which the data is being drawn.
*/
@Override
protected void drawPrimaryLineAsPath(XYItemRendererState state,
Graphics2D g2, XYPlot plot, XYDataset dataset, int pass,
int series, int item, ValueAxis xAxis, ValueAxis yAxis,
Rectangle2D dataArea) {
XYSplineState s = (XYSplineState) state;
RectangleEdge xAxisLocation = plot.getDomainAxisEdge();
RectangleEdge yAxisLocation = plot.getRangeAxisEdge();
// get the data points
double x1 = dataset.getXValue(series, item);
double y1 = dataset.getYValue(series, item);
double transX1 = xAxis.valueToJava2D(x1, dataArea, xAxisLocation);
double transY1 = yAxis.valueToJava2D(y1, dataArea, yAxisLocation);
// collect points
if (!Double.isNaN(transX1) && !Double.isNaN(transY1)) {
Point2D p = plot.getOrientation() == PlotOrientation.HORIZONTAL
? new Point2D.Float((float) transY1, (float) transX1)
: new Point2D.Float((float) transX1, (float) transY1);
if (!s.points.contains(p))
s.points.add(p);
}
if (item == dataset.getItemCount(series) - 1) { // construct path
if (s.points.size() > 1) {
Point2D origin;
if (this.fillType == FillType.TO_ZERO) {
float xz = (float) xAxis.valueToJava2D(0, dataArea,
yAxisLocation);
float yz = (float) yAxis.valueToJava2D(0, dataArea,
yAxisLocation);
origin = plot.getOrientation() == PlotOrientation.HORIZONTAL
? new Point2D.Float(yz, xz)
: new Point2D.Float(xz, yz);
} else if (this.fillType == FillType.TO_LOWER_BOUND) {
float xlb = (float) xAxis.valueToJava2D(
xAxis.getLowerBound(), dataArea, xAxisLocation);
float ylb = (float) yAxis.valueToJava2D(
yAxis.getLowerBound(), dataArea, yAxisLocation);
origin = plot.getOrientation() == PlotOrientation.HORIZONTAL
? new Point2D.Float(ylb, xlb)
: new Point2D.Float(xlb, ylb);
} else {// fillType == TO_UPPER_BOUND
float xub = (float) xAxis.valueToJava2D(
xAxis.getUpperBound(), dataArea, xAxisLocation);
float yub = (float) yAxis.valueToJava2D(
yAxis.getUpperBound(), dataArea, yAxisLocation);
origin = plot.getOrientation() == PlotOrientation.HORIZONTAL
? new Point2D.Float(yub, xub)
: new Point2D.Float(xub, yub);
}
// we need at least two points to draw something
Point2D cp0 = s.points.get(0);
s.seriesPath.moveTo(cp0.getX(), cp0.getY());
if (this.fillType != FillType.NONE) {
if (plot.getOrientation() == PlotOrientation.HORIZONTAL) {
s.fillArea.moveTo(origin.getX(), cp0.getY());
} else {
s.fillArea.moveTo(cp0.getX(), origin.getY());
}
s.fillArea.lineTo(cp0.getX(), cp0.getY());
}
if (s.points.size() == 2) {
// we need at least 3 points to spline. Draw simple line
// for two points
Point2D cp1 = s.points.get(1);
if (this.fillType != FillType.NONE) {
s.fillArea.lineTo(cp1.getX(), cp1.getY());
s.fillArea.lineTo(cp1.getX(), origin.getY());
s.fillArea.closePath();
}
s.seriesPath.lineTo(cp1.getX(), cp1.getY());
} else {
// construct spline
int np = s.points.size(); // number of points
float[] d = new float[np]; // Newton form coefficients
float[] x = new float[np]; // x-coordinates of nodes
float y, oldy;
float t, oldt;
float[] a = new float[np];
float t1;
float t2;
float[] h = new float[np];
for (int i = 0; i < np; i++) {
Point2D.Float cpi = (Point2D.Float) s.points.get(i);
x[i] = cpi.x;
d[i] = cpi.y;
}
for (int i = 1; i <= np - 1; i++)
h[i] = x[i] - x[i - 1];
float[] sub = new float[np - 1];
float[] diag = new float[np - 1];
float[] sup = new float[np - 1];
for (int i = 1; i <= np - 2; i++) {
diag[i] = (h[i] + h[i + 1]) / 3;
sup[i] = h[i + 1] / 6;
sub[i] = h[i] / 6;
a[i] = (d[i + 1] - d[i]) / h[i + 1]
- (d[i] - d[i - 1]) / h[i];
}
solveTridiag(sub, diag, sup, a, np - 2);
// note that a[0]=a[np-1]=0
oldt = x[0];
oldy = d[0];
for (int i = 1; i <= np - 1; i++) {
// loop over intervals between nodes
for (int j = 1; j <= this.precision; j++) {
t1 = (h[i] * j) / this.precision;
t2 = h[i] - t1;
y = ((-a[i - 1] / 6 * (t2 + h[i]) * t1 + d[i - 1])
* t2 + (-a[i] / 6 * (t1 + h[i]) * t2
+ d[i]) * t1) / h[i];
t = x[i - 1] + t1;
s.seriesPath.lineTo(t, y);
if (this.fillType != FillType.NONE) {
s.fillArea.lineTo(t, y);
}
}
}
}
// Add last point @ y=0 for fillPath and close path
if (this.fillType != FillType.NONE) {
if (plot.getOrientation() == PlotOrientation.HORIZONTAL) {
s.fillArea.lineTo(origin.getX(), s.points.get(
s.points.size() - 1).getY());
} else {
s.fillArea.lineTo(s.points.get(
s.points.size() - 1).getX(), origin.getY());
}
s.fillArea.closePath();
}
// fill under the curve...
if (this.fillType != FillType.NONE) {
Paint fp = getSeriesFillPaint(series);
if (this.gradientPaintTransformer != null
&& fp instanceof GradientPaint) {
GradientPaint gp = this.gradientPaintTransformer
.transform((GradientPaint) fp, s.fillArea);
g2.setPaint(gp);
} else {
g2.setPaint(fp);
}
g2.fill(s.fillArea);
s.fillArea.reset();
}
// then draw the line...
drawFirstPassShape(g2, pass, series, item, s.seriesPath);
}
// reset points vector
s.points = new ArrayList<Point2D>();
}
}
private void solveTridiag(float[] sub, float[] diag, float[] sup,
float[] b, int n) {
/* solve linear system with tridiagonal n by n matrix a
using Gaussian elimination *without* pivoting
where a(i,i-1) = sub[i] for 2<=i<=n
a(i,i) = diag[i] for 1<=i<=n
a(i,i+1) = sup[i] for 1<=i<=n-1
(the values sub[1], sup[n] are ignored)
right hand side vector b[1:n] is overwritten with solution
NOTE: 1...n is used in all arrays, 0 is unused */
int i;
/* factorization and forward substitution */
for (i = 2; i <= n; i++) {
sub[i] /= diag[i - 1];
diag[i] -= sub[i] * sup[i - 1];
b[i] -= sub[i] * b[i - 1];
}
b[n] /= diag[n];
for (i = n - 1; i >= 1; i--)
b[i] = (b[i] - sup[i] * b[i + 1]) / diag[i];
}
/**
* 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 XYSplineRenderer)) {
return false;
}
XYSplineRenderer that = (XYSplineRenderer) obj;
if (this.precision != that.precision) {
return false;
}
if (this.fillType != that.fillType) {
return false;
}
if (!ObjectUtilities.equal(this.gradientPaintTransformer,
that.gradientPaintTransformer)) {
return false;
}
return super.equals(obj);
}
}
| 18,921 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
DefaultXYItemRenderer.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/renderer/xy/DefaultXYItemRenderer.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.]
*
* --------------------------
* DefaultXYItemRenderer.java
* --------------------------
* (C) Copyright 2003-2008, by Object Refinery Limited and Contributors.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 23-Jul-2003 : Version 1 (DG);
* 22-Feb-2005 : Now extends XYLineAndShapeRenderer (DG);
*
*/
package org.jfree.chart.renderer.xy;
import java.io.Serializable;
/**
* A default renderer for the {@link org.jfree.chart.plot.XYPlot} class. This
* is an alias for the {@link XYLineAndShapeRenderer} class.
*/
public class DefaultXYItemRenderer extends XYLineAndShapeRenderer
implements Serializable {
/** For serialization. */
static final long serialVersionUID = 3450423530996888074L;
// no new methods
}
| 2,067 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
XYItemRendererState.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/renderer/xy/XYItemRendererState.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.]
*
* ------------------------
* XYItemRendererState.java
* ------------------------
* (C) Copyright 2003-2008, by Object Refinery Limited and Contributors.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): Ulrich Voigt;
* Greg Darke;
*
* Changes:
* --------
* 07-Oct-2003 : Version 1 (DG);
* 27-Jan-2004 : Added workingLine attribute (DG);
* ------------- JFREECHART 1.0.x ---------------------------------------------
* 04-May-2007 : Added processVisibleItemsOnly flag (DG);
* 09-Jul-2008 : Added start/endSeriesPass() methods - see patch 1997549 by
* Ulrich Voigt (DG);
* 19-Sep-2008 : Added first and last item indices, based on patch by Greg
* Darke (DG);
*
*/
package org.jfree.chart.renderer.xy;
import java.awt.geom.Line2D;
import org.jfree.chart.plot.PlotRenderingInfo;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.RendererState;
import org.jfree.data.xy.XYDataset;
/**
* The state for an {@link XYItemRenderer}.
*/
public class XYItemRendererState extends RendererState {
/**
* The first item in the series that will be displayed.
*
* @since 1.0.11
*/
private int firstItemIndex;
/**
* The last item in the current series that will be displayed.
*
* @since 1.0.11
*/
private int lastItemIndex;
/**
* A line object that the renderer can reuse to save instantiating a lot
* of objects.
*/
public Line2D workingLine;
/**
* A flag that controls whether the plot should pass ALL data items to the
* renderer, or just the items that will be visible.
*
* @since 1.0.6
*/
private boolean processVisibleItemsOnly;
/**
* Creates a new state.
*
* @param info the plot rendering info.
*/
public XYItemRendererState(PlotRenderingInfo info) {
super(info);
this.workingLine = new Line2D.Double();
this.processVisibleItemsOnly = true;
}
/**
* Returns the flag that controls whether the plot passes all data
* items in each series to the renderer, or just the visible items. The
* default value is <code>true</code>.
*
* @return A boolean.
*
* @since 1.0.6
*
* @see #setProcessVisibleItemsOnly(boolean)
*/
public boolean getProcessVisibleItemsOnly() {
return this.processVisibleItemsOnly;
}
/**
* Sets the flag that controls whether the plot passes all data
* items in each series to the renderer, or just the visible items.
*
* @param flag the new flag value.
*
* @since 1.0.6
*/
public void setProcessVisibleItemsOnly(boolean flag) {
this.processVisibleItemsOnly = flag;
}
/**
* Returns the first item index (this is updated with each call to
* {@link #startSeriesPass(XYDataset, int, int, int, int, int)}.
*
* @return The first item index.
*
* @since 1.0.11
*/
public int getFirstItemIndex() {
return this.firstItemIndex;
}
/**
* Returns the last item index (this is updated with each call to
* {@link #startSeriesPass(XYDataset, int, int, int, int, int)}.
*
* @return The last item index.
*
* @since 1.0.11
*/
public int getLastItemIndex() {
return this.lastItemIndex;
}
/**
* This method is called by the {@link XYPlot} when it starts a pass
* through the (visible) items in a series. The default implementation
* records the first and last item indices - override this method to
* implement additional specialised behaviour.
*
* @param dataset the dataset.
* @param series the series index.
* @param firstItem the index of the first item in the series.
* @param lastItem the index of the last item in the series.
* @param pass the pass index.
* @param passCount the number of passes.
*
* @see #endSeriesPass(XYDataset, int, int, int, int, int)
*
* @since 1.0.11
*/
public void startSeriesPass(XYDataset dataset, int series, int firstItem,
int lastItem, int pass, int passCount) {
this.firstItemIndex = firstItem;
this.lastItemIndex = lastItem;
}
/**
* This method is called by the {@link XYPlot} when it ends a pass
* through the (visible) items in a series. The default implementation
* does nothing, but you can override this method to implement specialised
* behaviour.
*
* @param dataset the dataset.
* @param series the series index.
* @param firstItem the index of the first item in the series.
* @param lastItem the index of the last item in the series.
* @param pass the pass index.
* @param passCount the number of passes.
*
* @see #startSeriesPass(XYDataset, int, int, int, int, int)
*
* @since 1.0.11
*/
public void endSeriesPass(XYDataset dataset, int series, int firstItem,
int lastItem, int pass, int passCount) {
// do nothing...this is just a hook for subclasses
}
}
| 6,399 | 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/xy/package-info.java | /**
* Plug-in renderers for the {@link org.jfree.chart.plot.XYPlot} class.
*/
package org.jfree.chart.renderer.xy;
| 117 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
SamplingXYLineRenderer.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/renderer/xy/SamplingXYLineRenderer.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.]
*
* ---------------------------
* SamplingXYLineRenderer.java
* ---------------------------
* (C) Copyright 2008-2012, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes:
* --------
* 02-Oct-2008 : Version 1 (DG);
* 28-Apr-2009 : Fixed bug in legend shape display, and deprecated
* getLegendLine() and setLegendLine() - these methods
* are unnecessary because a mechanism already exists in the
* superclass for specifying a custom legend shape (DG);
* 17-Jun-2012 : Removed JCommon dependencies (DG);
*
*/
package org.jfree.chart.renderer.xy;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.geom.GeneralPath;
import java.awt.geom.Line2D;
import java.awt.geom.PathIterator;
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.PublicCloneable;
import org.jfree.chart.util.ShapeUtilities;
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.xy.XYDataset;
/**
* A renderer that draws line charts. The renderer doesn't necessarily plot
* every data item - instead, it tries to plot only those data items that
* make a difference to the visual output (the other data items are skipped).
* This renderer is designed for use with the {@link XYPlot} class.
*
* @since 1.0.13
*/
public class SamplingXYLineRenderer extends AbstractXYItemRenderer
implements XYItemRenderer, Cloneable, PublicCloneable, Serializable {
/** The shape that is used to represent a line in the legend. */
private transient Shape legendLine;
/**
* Creates a new renderer.
*/
public SamplingXYLineRenderer() {
this.legendLine = new Line2D.Double(-7.0, 0.0, 7.0, 0.0);
setDefaultLegendShape(this.legendLine);
setTreatLegendShapeAsLine(true);
}
/**
* 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;
}
/**
* 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. */
GeneralPath seriesPath;
/**
* A second path that draws vertical intervals to cover any extreme
* values.
*/
GeneralPath intervalPath;
/**
* The minimum change in the x-value needed to trigger an update to
* the seriesPath.
*/
double dX = 1.0;
/** The last x-coordinate visited by the seriesPath. */
double lastX;
/** The initial y-coordinate for the current x-coordinate. */
double openY = 0.0;
/** The highest y-coordinate for the current x-coordinate. */
double highY = 0.0;
/** The lowest y-coordinate for the current x-coordinate. */
double lowY = 0.0;
/** The final y-coordinate for the current x-coordinate. */
double closeY = 0.0;
/**
* A flag that indicates if the last (x, y) point was 'good'
* (non-null).
*/
boolean lastPointGood;
/**
* Creates a new state instance.
*
* @param info the plot rendering info.
*/
public State(PlotRenderingInfo info) {
super(info);
}
/**
* 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.intervalPath.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) {
double dpi = 72;
// Integer dpiVal = (Integer) g2.getRenderingHint(HintKey.DPI);
// if (dpiVal != null) {
// dpi = dpiVal.intValue();
// }
State state = new State(info);
state.seriesPath = new GeneralPath();
state.intervalPath = new GeneralPath();
state.dX = 72.0 / dpi;
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;
}
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.lastPointGood) {
if ((Math.abs(x - s.lastX) > s.dX)) {
s.seriesPath.lineTo(x, y);
if (s.lowY < s.highY) {
s.intervalPath.moveTo((float) s.lastX, (float) s.lowY);
s.intervalPath.lineTo((float) s.lastX, (float) s.highY);
}
s.lastX = x;
s.openY = y;
s.highY = y;
s.lowY = y;
s.closeY = y;
}
else {
s.highY = Math.max(s.highY, y);
s.lowY = Math.min(s.lowY, y);
s.closeY = y;
}
}
else {
s.seriesPath.moveTo(x, y);
s.lastX = x;
s.openY = y;
s.highY = y;
s.lowY = y;
s.closeY = y;
}
s.lastPointGood = true;
}
else {
s.lastPointGood = false;
}
// if this is the last item, draw the path ...
if (item == s.getLastItemIndex()) {
// draw path
PathIterator pi = s.seriesPath.getPathIterator(null);
int count = 0;
while (!pi.isDone()) {
count++;
pi.next();
}
g2.setStroke(getItemStroke(series, item));
g2.setPaint(getItemPaint(series, item));
g2.draw(s.seriesPath);
g2.draw(s.intervalPath);
}
}
/**
* Returns a clone of the renderer.
*
* @return A clone.
*
* @throws CloneNotSupportedException if the clone cannot be created.
*/
@Override
public Object clone() throws CloneNotSupportedException {
SamplingXYLineRenderer clone = (SamplingXYLineRenderer) super.clone();
if (this.legendLine != null) {
clone.legendLine = ShapeUtilities.clone(this.legendLine);
}
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 SamplingXYLineRenderer)) {
return false;
}
if (!super.equals(obj)) {
return false;
}
SamplingXYLineRenderer that = (SamplingXYLineRenderer) obj;
if (!ShapeUtilities.equal(this.legendLine, that.legendLine)) {
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);
}
} | 13,196 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
StackedXYBarRenderer.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/renderer/xy/StackedXYBarRenderer.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.]
*
* -------------------------
* StackedXYBarRenderer.java
* -------------------------
* (C) Copyright 2004-2012, by Andreas Schroeder and Contributors.
*
* Original Author: Andreas Schroeder;
* Contributor(s): David Gilbert (for Object Refinery Limited);
*
* Changes
* -------
* 01-Apr-2004 : Version 1 (AS);
* 15-Jul-2004 : Switched getX() with getXValue() and getY() with
* getYValue() (DG);
* 15-Aug-2004 : Added drawBarOutline to control draw/don't-draw bar
* outlines (BN);
* 10-Sep-2004 : drawBarOutline attribute is now inherited from XYBarRenderer
* and double primitives are retrieved from the dataset rather
* than Number objects (DG);
* 07-Jan-2005 : Updated for method name change in DatasetUtilities (DG);
* 25-Jan-2005 : Modified to handle negative values correctly (DG);
* ------------- JFREECHART 1.0.x ---------------------------------------------
* 06-Dec-2006 : Added support for GradientPaint (DG);
* 15-Mar-2007 : Added renderAsPercentages option (DG);
* 24-Jun-2008 : Added new barPainter mechanism (DG);
* 23-Sep-2008 : Check shadow visibility before drawing shadow (DG);
* 28-May-2009 : Fixed bar positioning with inverted domain axis (DG);
* 07-Act-2011 : Fix for Bug #3035289: Patch #3035325 (MH);
* 17-Jun-2012 : Removed JCommon dependencies (DG);
*
*/
package org.jfree.chart.renderer.xy;
import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.ui.RectangleEdge;
import org.jfree.chart.ui.TextAnchor;
import org.jfree.chart.entity.EntityCollection;
import org.jfree.chart.event.RendererChangeEvent;
import org.jfree.chart.labels.ItemLabelAnchor;
import org.jfree.chart.labels.ItemLabelPosition;
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.general.DatasetUtilities;
import org.jfree.data.xy.IntervalXYDataset;
import org.jfree.data.xy.TableXYDataset;
import org.jfree.data.xy.XYDataset;
/**
* A bar renderer that displays the series items stacked.
* The dataset used together with this renderer must be a
* {@link org.jfree.data.xy.IntervalXYDataset} and a
* {@link org.jfree.data.xy.TableXYDataset}. For example, the
* dataset class {@link org.jfree.data.xy.CategoryTableXYDataset}
* implements both interfaces.
*
* The example shown here is generated by the
* <code>StackedXYBarChartDemo2.java</code> program included in the
* JFreeChart demo collection:
* <br><br>
* <img src="../../../../../images/StackedXYBarRendererSample.png"
* alt="StackedXYBarRendererSample.png" />
*/
public class StackedXYBarRenderer extends XYBarRenderer {
/** For serialization. */
private static final long serialVersionUID = -7049101055533436444L;
/** A flag that controls whether the bars display values or percentages. */
private boolean renderAsPercentages;
/**
* Creates a new renderer.
*/
public StackedXYBarRenderer() {
this(0.0);
}
/**
* Creates a new renderer.
*
* @param margin the percentual amount of the bars that are cut away.
*/
public StackedXYBarRenderer(double margin) {
super(margin);
this.renderAsPercentages = false;
// 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)
*
* @since 1.0.5
*/
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()
*
* @since 1.0.5
*/
public void setRenderAsPercentages(boolean asPercentages) {
this.renderAsPercentages = asPercentages;
fireChangeEvent();
}
/**
* Returns <code>3</code> to indicate that this renderer requires three
* passes for drawing (shadows are drawn in the first pass, the bars in the
* second, and item labels are drawn in the third pass so that
* they always appear in front of all the bars).
*
* @return <code>2</code>.
*/
@Override
public int getPassCount() {
return 3;
}
/**
* Initialises the renderer and returns a state object that should be
* passed to all subsequent calls to the drawItem() method. Here there is
* nothing to do.
*
* @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) {
return new XYBarRendererState(info);
}
/**
* 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) {
if (this.renderAsPercentages) {
return new Range(0.0, 1.0);
}
else {
return DatasetUtilities.findStackedRangeBounds(
(TableXYDataset) dataset);
}
}
else {
return null;
}
}
/**
* 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 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;
}
if (!(dataset instanceof IntervalXYDataset
&& dataset instanceof TableXYDataset)) {
String message = "dataset (type " + dataset.getClass().getName()
+ ") has wrong type:";
boolean and = false;
if (!IntervalXYDataset.class.isAssignableFrom(dataset.getClass())) {
message += " it is no IntervalXYDataset";
and = true;
}
if (!TableXYDataset.class.isAssignableFrom(dataset.getClass())) {
if (and) {
message += " and";
}
message += " it is no TableXYDataset";
}
throw new IllegalArgumentException(message);
}
IntervalXYDataset intervalDataset = (IntervalXYDataset) dataset;
double value = intervalDataset.getYValue(series, item);
if (Double.isNaN(value)) {
return;
}
// if we are rendering the values as percentages, we need to calculate
// the total for the current item. Unfortunately here we end up
// repeating the calculation more times than is strictly necessary -
// hopefully I'll come back to this and find a way to add the
// total(s) to the renderer state. The other problem is we implicitly
// assume the dataset has no negative values...perhaps that can be
// fixed too.
double total = 0.0;
if (this.renderAsPercentages) {
total = DatasetUtilities.calculateStackTotal(
(TableXYDataset) dataset, item);
value = value / total;
}
double positiveBase = 0.0;
double negativeBase = 0.0;
for (int i = 0; i < series; i++) {
double v = dataset.getYValue(i, item);
if (!Double.isNaN(v) && isSeriesVisible(i)) {
if (this.renderAsPercentages) {
v = v / total;
}
if (v > 0) {
positiveBase = positiveBase + v;
}
else {
negativeBase = negativeBase + v;
}
}
}
double translatedBase;
double translatedValue;
RectangleEdge edgeR = plot.getRangeAxisEdge();
if (value > 0.0) {
translatedBase = rangeAxis.valueToJava2D(positiveBase, dataArea,
edgeR);
translatedValue = rangeAxis.valueToJava2D(positiveBase + value,
dataArea, edgeR);
}
else {
translatedBase = rangeAxis.valueToJava2D(negativeBase, dataArea,
edgeR);
translatedValue = rangeAxis.valueToJava2D(negativeBase + value,
dataArea, edgeR);
}
RectangleEdge edgeD = plot.getDomainAxisEdge();
double startX = intervalDataset.getStartXValue(series, item);
if (Double.isNaN(startX)) {
return;
}
double translatedStartX = domainAxis.valueToJava2D(startX, dataArea,
edgeD);
double endX = intervalDataset.getEndXValue(series, item);
if (Double.isNaN(endX)) {
return;
}
double translatedEndX = domainAxis.valueToJava2D(endX, dataArea, edgeD);
double translatedWidth = Math.max(1, Math.abs(translatedEndX
- translatedStartX));
double translatedHeight = Math.abs(translatedValue - translatedBase);
if (getMargin() > 0.0) {
double cut = translatedWidth * getMargin();
translatedWidth = translatedWidth - cut;
translatedStartX = translatedStartX + cut / 2;
}
Rectangle2D bar = null;
PlotOrientation orientation = plot.getOrientation();
if (orientation == PlotOrientation.HORIZONTAL) {
bar = new Rectangle2D.Double(Math.min(translatedBase,
translatedValue), Math.min(translatedEndX,
translatedStartX), translatedHeight, translatedWidth);
}
else if (orientation == PlotOrientation.VERTICAL) {
bar = new Rectangle2D.Double(Math.min(translatedStartX,
translatedEndX), Math.min(translatedBase, translatedValue),
translatedWidth, translatedHeight);
}
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;
}
}
if (pass == 0) {
if (getShadowsVisible()) {
getBarPainter().paintBarShadow(g2, this, series, item, bar,
barBase, false);
}
}
else if (pass == 1) {
getBarPainter().paintBar(g2, this, series, item, bar, barBase);
// 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());
}
}
}
else if (pass == 2) {
// handle item label drawing, now that we know all the bars have
// been drawn...
if (isItemLabelVisible(series, item)) {
XYItemLabelGenerator generator = getItemLabelGenerator(series,
item);
drawItemLabel(g2, dataset, series, item, 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 StackedXYBarRenderer)) {
return false;
}
StackedXYBarRenderer that = (StackedXYBarRenderer) obj;
if (this.renderAsPercentages != that.renderAsPercentages) {
return false;
}
return super.equals(obj);
}
/**
* Returns a hash code for this instance.
*
* @return A hash code.
*/
@Override
public int hashCode() {
int result = super.hashCode();
result = result * 37 + (this.renderAsPercentages ? 1 : 0);
return result;
}
}
| 16,429 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
DeviationRenderer.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/renderer/xy/DeviationRenderer.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.]
*
* ----------------------
* DeviationRenderer.java
* ----------------------
* (C) Copyright 2007-2012, by Object Refinery Limited and Contributors.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 21-Feb-2007 : Version 1 (DG);
* 04-May-2007 : Set processVisibleItemsOnly flag to false (DG);
* 11-Apr-2008 : New override for findRangeBounds() (DG);
* 27-Mar-2009 : Updated findRangeBounds() to call new inherited method (DG);
* 17-Jun-2012 : Removed JCommon dependencies (DG);
*
*/
package org.jfree.chart.renderer.xy;
import java.awt.AlphaComposite;
import java.awt.Composite;
import java.awt.Graphics2D;
import java.awt.geom.GeneralPath;
import java.awt.geom.Rectangle2D;
import java.util.List;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.ui.RectangleEdge;
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.data.Range;
import org.jfree.data.xy.IntervalXYDataset;
import org.jfree.data.xy.XYDataset;
/**
* A specialised subclass of the {@link XYLineAndShapeRenderer} that requires
* an {@link IntervalXYDataset} and represents the y-interval by shading an
* area behind the y-values on the chart.
* The example shown here is generated by the
* <code>DeviationRendererDemo1.java</code> program included in the
* JFreeChart demo collection:
* <br><br>
* <img src="../../../../../images/DeviationRendererSample.png"
* alt="DeviationRendererSample.png" />
*
* @since 1.0.5
*/
public class DeviationRenderer extends XYLineAndShapeRenderer {
/**
* A state object that is passed to each call to <code>drawItem</code>.
*/
public static class State extends XYLineAndShapeRenderer.State {
/**
* A list of coordinates for the upper y-values in the current series
* (after translation into Java2D space).
*/
public List<double[]> upperCoordinates;
/**
* A list of coordinates for the lower y-values in the current series
* (after translation into Java2D space).
*/
public List<double[]> lowerCoordinates;
/**
* Creates a new state instance.
*
* @param info the plot rendering info.
*/
public State(PlotRenderingInfo info) {
super(info);
this.lowerCoordinates = new java.util.ArrayList<double[]>();
this.upperCoordinates = new java.util.ArrayList<double[]>();
}
}
/** The alpha transparency for the interval shading. */
private float alpha;
/**
* Creates a new renderer that displays lines and shapes for the data
* items, as well as the shaded area for the y-interval.
*/
public DeviationRenderer() {
this(true, true);
}
/**
* Creates a new renderer.
*
* @param lines show lines between data items?
* @param shapes show a shape for each data item?
*/
public DeviationRenderer(boolean lines, boolean shapes) {
super(lines, shapes);
super.setDrawSeriesLineAsPath(true);
this.alpha = 0.5f;
}
/**
* Returns the alpha transparency for the background shading.
*
* @return The alpha transparency.
*
* @see #setAlpha(float)
*/
public float getAlpha() {
return this.alpha;
}
/**
* Sets the alpha transparency for the background shading, and sends a
* {@link RendererChangeEvent} to all registered listeners.
*
* @param alpha the alpha (in the range 0.0f to 1.0f).
*
* @see #getAlpha()
*/
public void setAlpha(float alpha) {
if (alpha < 0.0f || alpha > 1.0f) {
throw new IllegalArgumentException(
"Requires 'alpha' in the range 0.0 to 1.0.");
}
this.alpha = alpha;
fireChangeEvent();
}
/**
* This method is overridden so that this flag cannot be changed---it is
* set to <code>true</code> for this renderer.
*
* @param flag ignored.
*/
@Override
public void setDrawSeriesLineAsPath(boolean flag) {
// ignore
}
/**
* 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 and returns a state object that can be passed to each
* invocation of the {@link #drawItem} method.
*
* @param g2 the graphics target.
* @param dataArea the data area.
* @param plot the plot.
* @param dataset the dataset.
* @param info the plot rendering info.
*
* @return A newly initialised state object.
*/
@Override
public XYItemRendererState initialise(Graphics2D g2, Rectangle2D dataArea,
XYPlot plot, XYDataset dataset, PlotRenderingInfo info) {
State state = new State(info);
state.seriesPath = new GeneralPath();
state.setProcessVisibleItemsOnly(false);
return state;
}
/**
* Returns the number of passes (through the dataset) used by this
* renderer.
*
* @return <code>3</code>.
*/
@Override
public int getPassCount() {
return 3;
}
/**
* Returns <code>true</code> if this is the pass where the shapes are
* drawn.
*
* @param pass the pass index.
*
* @return A boolean.
*
* @see #isLinePass(int)
*/
@Override
protected boolean isItemPass(int pass) {
return (pass == 2);
}
/**
* Returns <code>true</code> if this is the pass where the lines are
* drawn.
*
* @param pass the pass index.
*
* @return A boolean.
*
* @see #isItemPass(int)
*/
@Override
protected boolean isLinePass(int pass) {
return (pass == 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 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 shading
if (pass == 0) {
IntervalXYDataset intervalDataset = (IntervalXYDataset) dataset;
State drState = (State) state;
double x = intervalDataset.getXValue(series, item);
double yLow = intervalDataset.getStartYValue(series, item);
double yHigh = intervalDataset.getEndYValue(series, item);
RectangleEdge xAxisLocation = plot.getDomainAxisEdge();
RectangleEdge yAxisLocation = plot.getRangeAxisEdge();
double xx = domainAxis.valueToJava2D(x, dataArea, xAxisLocation);
double yyLow = rangeAxis.valueToJava2D(yLow, dataArea,
yAxisLocation);
double yyHigh = rangeAxis.valueToJava2D(yHigh, dataArea,
yAxisLocation);
PlotOrientation orientation = plot.getOrientation();
if (orientation == PlotOrientation.HORIZONTAL) {
drState.lowerCoordinates.add(new double[] {yyLow, xx});
drState.upperCoordinates.add(new double[] {yyHigh, xx});
}
else if (orientation == PlotOrientation.VERTICAL) {
drState.lowerCoordinates.add(new double[] {xx, yyLow});
drState.upperCoordinates.add(new double[] {xx, yyHigh});
}
if (item == (dataset.getItemCount(series) - 1)) {
// last item in series, draw the lot...
// set up the alpha-transparency...
Composite originalComposite = g2.getComposite();
g2.setComposite(AlphaComposite.getInstance(
AlphaComposite.SRC_OVER, this.alpha));
g2.setPaint(getItemFillPaint(series, item));
GeneralPath area = new GeneralPath(GeneralPath.WIND_NON_ZERO,
drState.lowerCoordinates.size()
+ drState.upperCoordinates.size());
double[] coords = drState.lowerCoordinates.get(0);
area.moveTo((float) coords[0], (float) coords[1]);
for (int i = 1; i < drState.lowerCoordinates.size(); i++) {
coords = drState.lowerCoordinates.get(i);
area.lineTo((float) coords[0], (float) coords[1]);
}
int count = drState.upperCoordinates.size();
coords = drState.upperCoordinates.get(count - 1);
area.lineTo((float) coords[0], (float) coords[1]);
for (int i = count - 2; i >= 0; i--) {
coords = drState.upperCoordinates.get(i);
area.lineTo((float) coords[0], (float) coords[1]);
}
area.closePath();
g2.fill(area);
g2.setComposite(originalComposite);
drState.lowerCoordinates.clear();
drState.upperCoordinates.clear();
}
}
if (isLinePass(pass)) {
// the following code handles the line for the y-values...it's
// all done by code in the super class
if (item == 0) {
State s = (State) state;
s.seriesPath.reset();
s.setLastPointGood(false);
}
if (getItemLineVisible(series, item)) {
drawPrimaryLineAsPath(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);
}
}
/**
* 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 DeviationRenderer)) {
return false;
}
DeviationRenderer that = (DeviationRenderer) obj;
if (this.alpha != that.alpha) {
return false;
}
return super.equals(obj);
}
}
| 13,573 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
StackedXYAreaRenderer.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/renderer/xy/StackedXYAreaRenderer.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.]
*
* --------------------------
* StackedXYAreaRenderer.java
* --------------------------
* (C) Copyright 2003-2012, by Richard Atkinson and Contributors.
*
* Original Author: Richard Atkinson;
* Contributor(s): Christian W. Zuckschwerdt;
* David Gilbert (for Object Refinery Limited);
*
* Changes:
* --------
* 27-Jul-2003 : Initial version (RA);
* 30-Jul-2003 : Modified entity constructor (CZ);
* 18-Aug-2003 : Now handles null values (RA);
* 20-Aug-2003 : Implemented Cloneable, PublicCloneable and Serializable (DG);
* 22-Sep-2003 : Changed to be a two pass renderer with optional shape Paint
* and Stroke (RA);
* 07-Oct-2003 : Added renderer state (DG);
* 10-Feb-2004 : Updated state object and changed drawItem() method to make
* overriding easier (DG);
* 25-Feb-2004 : Replaced CrosshairInfo with CrosshairState. Renamed
* XYToolTipGenerator --> XYItemLabelGenerator (DG);
* 15-Jul-2004 : Switched getX() with getXValue() and getY() with
* getYValue() (DG);
* 10-Sep-2004 : Removed getRangeType() method (DG);
* 11-Nov-2004 : Now uses ShapeUtilities to translate shapes (DG);
* 06-Jan-2005 : Override equals() (DG);
* 07-Jan-2005 : Update for method name changes in DatasetUtilities (DG);
* 28-Mar-2005 : Use getXValue() and getYValue() from dataset (DG);
* 06-Jun-2005 : Fixed null pointer exception, plus problems with equals() and
* serialization (DG);
* ------------- JFREECHART 1.0.x ---------------------------------------------
* 10-Nov-2006 : Fixed bug 1593156, NullPointerException with line
* plotting (DG);
* 02-Feb-2007 : Fixed bug 1649686, crosshairs don't stack y-values (DG);
* 06-Feb-2007 : Fixed bug 1086307, crosshairs with multiple axes (DG);
* 22-Mar-2007 : Fire change events in setShapePaint() and setShapeStroke()
* methods (DG);
* 20-Apr-2007 : Updated getLegendItem() for renderer change (DG);
* 17-Jun-2012 : Removed JCommon dependencies (DG);
*
*/
package org.jfree.chart.renderer.xy;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.Point;
import java.awt.Polygon;
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.Stack;
import org.jfree.chart.axis.ValueAxis;
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.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.Range;
import org.jfree.data.general.DatasetUtilities;
import org.jfree.data.xy.TableXYDataset;
import org.jfree.data.xy.XYDataset;
/**
* A stacked area renderer for the {@link XYPlot} class.
* <br><br>
* The example shown here is generated by the
* <code>StackedXYAreaRendererDemo1.java</code> program included in the
* JFreeChart demo collection:
* <br><br>
* <img src="../../../../../images/StackedXYAreaRendererSample.png"
* alt="StackedXYAreaRendererSample.png" />
* <br><br>
* SPECIAL NOTE: This renderer does not currently handle negative data values
* correctly. This should get fixed at some point, but the current workaround
* is to use the {@link StackedXYAreaRenderer2} class instead.
*/
public class StackedXYAreaRenderer extends XYAreaRenderer
implements Cloneable, PublicCloneable, Serializable {
/** For serialization. */
private static final long serialVersionUID = 5217394318178570889L;
/**
* A state object for use by this renderer.
*/
static class StackedXYAreaRendererState extends XYItemRendererState {
/** The area for the current series. */
private Polygon seriesArea;
/** The line. */
private Line2D line;
/** The points from the last series. */
private Stack<Point> lastSeriesPoints;
/** The points for the current series. */
private Stack<Point> currentSeriesPoints;
/**
* Creates a new state for the renderer.
*
* @param info the plot rendering info.
*/
public StackedXYAreaRendererState(PlotRenderingInfo info) {
super(info);
this.seriesArea = null;
this.line = new Line2D.Double();
this.lastSeriesPoints = new Stack<Point>();
this.currentSeriesPoints = new Stack<Point>();
}
/**
* Returns the series area.
*
* @return The series area.
*/
public Polygon getSeriesArea() {
return this.seriesArea;
}
/**
* Sets the series area.
*
* @param area the area.
*/
public void setSeriesArea(Polygon area) {
this.seriesArea = area;
}
/**
* Returns the working line.
*
* @return The working line.
*/
public Line2D getLine() {
return this.line;
}
/**
* Returns the current series points.
*
* @return The current series points.
*/
public Stack<Point> getCurrentSeriesPoints() {
return this.currentSeriesPoints;
}
/**
* Sets the current series points.
*
* @param points the points.
*/
public void setCurrentSeriesPoints(Stack<Point> points) {
this.currentSeriesPoints = points;
}
/**
* Returns the last series points.
*
* @return The last series points.
*/
public Stack getLastSeriesPoints() {
return this.lastSeriesPoints;
}
/**
* Sets the last series points.
*
* @param points the points.
*/
public void setLastSeriesPoints(Stack<Point> points) {
this.lastSeriesPoints = points;
}
}
/**
* Custom Paint for drawing all shapes, if null defaults to series shapes
*/
private transient Paint shapePaint = null;
/**
* Custom Stroke for drawing all shapes, if null defaults to series
* strokes.
*/
private transient Stroke shapeStroke = null;
/**
* Creates a new renderer.
*/
public StackedXYAreaRenderer() {
this(AREA);
}
/**
* Constructs a new renderer.
*
* @param type the type of the renderer.
*/
public StackedXYAreaRenderer(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 labelGenerator the tool tip generator to use (<code>null</code>
* is none).
* @param urlGenerator the URL generator (<code>null</code> permitted).
*/
public StackedXYAreaRenderer(int type, XYToolTipGenerator labelGenerator,
XYURLGenerator urlGenerator) {
super(type, labelGenerator, urlGenerator);
}
/**
* Returns the paint used for rendering shapes, or <code>null</code> if
* using series paints.
*
* @return The paint (possibly <code>null</code>).
*
* @see #setShapePaint(Paint)
*/
public Paint getShapePaint() {
return this.shapePaint;
}
/**
* Sets the paint for rendering shapes and sends a
* {@link RendererChangeEvent} to all registered listeners.
*
* @param shapePaint the paint (<code>null</code> permitted).
*
* @see #getShapePaint()
*/
public void setShapePaint(Paint shapePaint) {
this.shapePaint = shapePaint;
fireChangeEvent();
}
/**
* Returns the stroke used for rendering shapes, or <code>null</code> if
* using series strokes.
*
* @return The stroke (possibly <code>null</code>).
*
* @see #setShapeStroke(Stroke)
*/
public Stroke getShapeStroke() {
return this.shapeStroke;
}
/**
* Sets the stroke for rendering shapes and sends a
* {@link RendererChangeEvent} to all registered listeners.
*
* @param shapeStroke the stroke (<code>null</code> permitted).
*
* @see #getShapeStroke()
*/
public void setShapeStroke(Stroke shapeStroke) {
this.shapeStroke = shapeStroke;
fireChangeEvent();
}
/**
* 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.
*
* @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 that should be passed to subsequent calls to the
* drawItem() method.
*/
@Override
public XYItemRendererState initialise(Graphics2D g2,
Rectangle2D dataArea,
XYPlot plot,
XYDataset data,
PlotRenderingInfo info) {
XYItemRendererState state = new StackedXYAreaRendererState(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 the number of passes required by the renderer.
*
* @return 2.
*/
@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> permitted).
*
* @return The range ([0.0, 0.0] if the dataset contains no values, and
* <code>null</code> if the dataset is <code>null</code>).
*
* @throws ClassCastException if <code>dataset</code> is not an instance
* of {@link TableXYDataset}.
*/
@Override
public Range findRangeBounds(XYDataset dataset) {
if (dataset != null) {
return DatasetUtilities.findStackedRangeBounds(
(TableXYDataset) dataset);
}
else {
return null;
}
}
/**
* 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.
*
* @throws ClassCastException if <code>state</code> is not an instance of
* <code>StackedXYAreaRendererState</code> or <code>dataset</code>
* is not an instance of {@link TableXYDataset}.
*/
@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();
StackedXYAreaRendererState areaState
= (StackedXYAreaRendererState) state;
// Get the item count for the series, so that we can know which is the
// end of the series.
TableXYDataset tdataset = (TableXYDataset) dataset;
int itemCount = tdataset.getItemCount();
// get the data point...
double x1 = dataset.getXValue(series, item);
double y1 = dataset.getYValue(series, item);
boolean nullPoint = false;
if (Double.isNaN(y1)) {
y1 = 0.0;
nullPoint = true;
}
// Get height adjustment based on stack and translate to Java2D values
double ph1 = getPreviousHeight(tdataset, series, item);
double transX1 = domainAxis.valueToJava2D(x1, dataArea,
plot.getDomainAxisEdge());
double transY1 = rangeAxis.valueToJava2D(y1 + ph1, dataArea,
plot.getRangeAxisEdge());
// Get series Paint and Stroke
Paint seriesPaint = getItemPaint(series, item);
Paint seriesFillPaint = seriesPaint;
if (getUseFillPaint()) {
seriesFillPaint = getItemFillPaint(series, item);
}
Stroke seriesStroke = getItemStroke(series, item);
if (pass == 0) {
// On first pass render the areas, line and outlines
if (item == 0) {
// Create a new Area for the series
areaState.setSeriesArea(new Polygon());
areaState.setLastSeriesPoints(
areaState.getCurrentSeriesPoints());
areaState.setCurrentSeriesPoints(new Stack<Point>());
// start from previous height (ph1)
double transY2 = rangeAxis.valueToJava2D(ph1, dataArea,
plot.getRangeAxisEdge());
// The first point is (x, 0)
if (orientation == PlotOrientation.VERTICAL) {
areaState.getSeriesArea().addPoint((int) transX1,
(int) transY2);
}
else if (orientation == PlotOrientation.HORIZONTAL) {
areaState.getSeriesArea().addPoint((int) transY2,
(int) transX1);
}
}
// Add each point to Area (x, y)
if (orientation == PlotOrientation.VERTICAL) {
Point point = new Point((int) transX1, (int) transY1);
areaState.getSeriesArea().addPoint((int) point.getX(),
(int) point.getY());
areaState.getCurrentSeriesPoints().push(point);
}
else if (orientation == PlotOrientation.HORIZONTAL) {
areaState.getSeriesArea().addPoint((int) transY1,
(int) transX1);
}
if (getPlotLines()) {
if (item > 0) {
// get the previous data point...
double x0 = dataset.getXValue(series, item - 1);
double y0 = dataset.getYValue(series, item - 1);
double ph0 = getPreviousHeight(tdataset, series, item - 1);
double transX0 = domainAxis.valueToJava2D(x0, dataArea,
plot.getDomainAxisEdge());
double transY0 = rangeAxis.valueToJava2D(y0 + ph0,
dataArea, plot.getRangeAxisEdge());
if (orientation == PlotOrientation.VERTICAL) {
areaState.getLine().setLine(transX0, transY0, transX1,
transY1);
}
else if (orientation == PlotOrientation.HORIZONTAL) {
areaState.getLine().setLine(transY0, transX0, transY1,
transX1);
}
g2.setPaint(seriesPaint);
g2.setStroke(seriesStroke);
g2.draw(areaState.getLine());
}
}
// 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)) {
double transY2 = rangeAxis.valueToJava2D(ph1, dataArea,
plot.getRangeAxisEdge());
if (orientation == PlotOrientation.VERTICAL) {
// Add the last point (x,0)
areaState.getSeriesArea().addPoint((int) transX1,
(int) transY2);
}
else if (orientation == PlotOrientation.HORIZONTAL) {
// Add the last point (x,0)
areaState.getSeriesArea().addPoint((int) transY2,
(int) transX1);
}
// Add points from last series to complete the base of the
// polygon
if (series != 0) {
Stack points = areaState.getLastSeriesPoints();
while (!points.empty()) {
Point point = (Point) points.pop();
areaState.getSeriesArea().addPoint((int) point.getX(),
(int) point.getY());
}
}
// Fill the polygon
g2.setPaint(seriesFillPaint);
g2.setStroke(seriesStroke);
g2.fill(areaState.getSeriesArea());
// Draw an outline around the Area.
if (isOutline()) {
g2.setStroke(lookupSeriesOutlineStroke(series));
g2.setPaint(lookupSeriesOutlinePaint(series));
g2.draw(areaState.getSeriesArea());
}
}
int domainAxisIndex = plot.getDomainAxisIndex(domainAxis);
int rangeAxisIndex = plot.getRangeAxisIndex(rangeAxis);
updateCrosshairValues(crosshairState, x1, ph1 + y1, domainAxisIndex,
rangeAxisIndex, transX1, transY1, orientation);
}
else if (pass == 1) {
// On second pass render shapes and collect entity and tooltip
// information
Shape shape = null;
if (getPlotShapes()) {
shape = getItemShape(series, item);
if (plot.getOrientation() == PlotOrientation.VERTICAL) {
shape = ShapeUtilities.createTranslatedShape(shape,
transX1, transY1);
}
else if (plot.getOrientation() == PlotOrientation.HORIZONTAL) {
shape = ShapeUtilities.createTranslatedShape(shape,
transY1, transX1);
}
if (!nullPoint) {
if (getShapePaint() != null) {
g2.setPaint(getShapePaint());
}
else {
g2.setPaint(seriesPaint);
}
if (getShapeStroke() != null) {
g2.setStroke(getShapeStroke());
}
else {
g2.setStroke(seriesStroke);
}
g2.draw(shape);
}
}
else {
if (plot.getOrientation() == PlotOrientation.VERTICAL) {
shape = new Rectangle2D.Double(transX1 - 3, transY1 - 3,
6.0, 6.0);
}
else if (plot.getOrientation() == PlotOrientation.HORIZONTAL) {
shape = new Rectangle2D.Double(transY1 - 3, transX1 - 3,
6.0, 6.0);
}
}
// collect entity and tool tip information...
if (state.getInfo() != null) {
EntityCollection entities = state.getEntityCollection();
if (entities != null && shape != null && !nullPoint) {
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(shape, dataset,
series, item, tip, url);
entities.add(entity);
}
}
}
}
/**
* Calculates the stacked value of the all series up to, but not including
* <code>series</code> for the specified item. It returns 0.0 if
* <code>series</code> is the first series, i.e. 0.
*
* @param dataset the dataset.
* @param series the series.
* @param index the index.
*
* @return The cumulative value for all series' values up to but excluding
* <code>series</code> for <code>index</code>.
*/
protected double getPreviousHeight(TableXYDataset dataset,
int series, int index) {
double result = 0.0;
for (int i = 0; i < series; i++) {
double value = dataset.getYValue(i, index);
if (!Double.isNaN(value)) {
result += value;
}
}
return result;
}
/**
* Tests the 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 StackedXYAreaRenderer) || !super.equals(obj)) {
return false;
}
StackedXYAreaRenderer that = (StackedXYAreaRenderer) obj;
if (!PaintUtilities.equal(this.shapePaint, that.shapePaint)) {
return false;
}
if (!ObjectUtilities.equal(this.shapeStroke, that.shapeStroke)) {
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 {
return super.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.shapePaint = SerialUtilities.readPaint(stream);
this.shapeStroke = 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.shapePaint, stream);
SerialUtilities.writeStroke(this.shapeStroke, stream);
}
}
| 25,703 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
StackedXYAreaRenderer2.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/renderer/xy/StackedXYAreaRenderer2.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 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.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.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.Range;
import org.jfree.data.xy.TableXYDataset;
import org.jfree.data.xy.XYDataset;
/**
* 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 StackedXYAreaRenderer2 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 StackedXYAreaRenderer2() {
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 StackedXYAreaRenderer2(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;
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();
}
}
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) {
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.clone();
}
else {
double yleft = (y0 + y1) / 2.0 + stackLeft[0];
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();
}
float transStackRight = (float) rangeAxis.valueToJava2D(
adjStackRight[0], dataArea, edge1);
// RIGHT POLYGON
if (y2 >= 0.0) {
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();
}
else {
double yright = (y1 + y2) / 2.0 + stackRight[0];
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();
}
}
// 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 StackedXYAreaRenderer2)) {
return false;
}
StackedXYAreaRenderer2 that = (StackedXYAreaRenderer2) 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();
}
}
| 21,427 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
GradientXYBarPainter.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/renderer/xy/GradientXYBarPainter.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.]
*
* -------------------------
* GradientXYBarPainter.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);
* 22-Feb-2009 : Fixed bug drawing outlines (DG);
* 17-Jun-2012 : Removed JCommon dependencies (DG);
*
*/
package org.jfree.chart.renderer.xy;
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 XYBarPainter} interface that uses several
* gradient fills to enrich the appearance of the bars.
*
* @since 1.0.11
*/
public class GradientXYBarPainter implements XYBarPainter, 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 GradientXYBarPainter() {
this(0.10, 0.20, 0.80);
}
/**
* Creates a new instance.
*
* @param g1 the division between regions 1 and 2.
* @param g2 the division between regions 2 and 3.
* @param g3 the division between regions 3 and 4.
*/
public GradientXYBarPainter(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, XYBarRenderer 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].getMaxX(), 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()) {
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, XYBarRenderer 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(Color.GRAY);
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 GradientXYBarPainter)) {
return false;
}
GradientXYBarPainter that = (GradientXYBarPainter) 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,764 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
WindItemRenderer.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/renderer/xy/WindItemRenderer.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.]
*
* ---------------------
* WindItemRenderer.java
* ---------------------
* (C) Copyright 2001-2012, by Achilleus Mantzios and Contributors.
*
* Original Author: Achilleus Mantzios;
* Contributor(s): David Gilbert (for Object Refinery Limited);
*
* Changes
* -------
* 06-Feb-2002 : Version 1, based on code contributed by Achilleus
* Mantzios (DG);
* 28-Mar-2002 : Added a property change listener mechanism so that renderers
* no longer need to be immutable. Changed StrictMath --> Math
* to retain JDK1.2 compatibility (DG);
* 09-Apr-2002 : Changed return type of the drawItem method to void, reflecting
* the change in the XYItemRenderer method (DG);
* 01-Oct-2002 : Fixed errors reported by Checkstyle (DG);
* 21-Jan-2003 : Added new constructor (DG);
* 25-Mar-2003 : Implemented Serializable (DG);
* 01-May-2003 : Modified drawItem() method signature (DG);
* 20-Aug-2003 : Implemented Cloneable and PublicCloneable (DG);
* 16-Sep-2003 : Changed ChartRenderingInfo --> PlotRenderingInfo (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 ---------------------------------------------
* 02-Feb-2007 : Removed author tags from all over JFreeChart sources (DG);
* 17-Jun-2012 : Removed JCommon dependencies (DG);
*
*/
package org.jfree.chart.renderer.xy;
import java.awt.Color;
import java.awt.Font;
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.axis.ValueAxis;
import org.jfree.chart.ui.RectangleEdge;
import org.jfree.chart.util.PublicCloneable;
import org.jfree.chart.plot.CrosshairState;
import org.jfree.chart.plot.PlotRenderingInfo;
import org.jfree.chart.plot.XYPlot;
import org.jfree.data.xy.WindDataset;
import org.jfree.data.xy.XYDataset;
/**
* A specialised renderer for displaying wind intensity/direction data.
* The example shown here is generated by the <code>WindChartDemo1.java</code>
* program included in the JFreeChart demo collection:
* <br><br>
* <img src="../../../../../images/WindItemRendererSample.png"
* alt="WindItemRendererSample.png" />
*/
public class WindItemRenderer extends AbstractXYItemRenderer
implements XYItemRenderer, Cloneable, PublicCloneable, Serializable {
/** For serialization. */
private static final long serialVersionUID = 8078914101916976844L;
/**
* Creates a new renderer.
*/
public WindItemRenderer() {
super();
}
/**
* Draws the visual representation of a single data item.
*
* @param g2 the graphics device.
* @param state the renderer state.
* @param plotArea the area within which the plot is being drawn.
* @param info optional information collection.
* @param plot the plot (can be used to obtain standard color
* information etc).
* @param domainAxis the horizontal axis.
* @param rangeAxis the 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 plotArea,
PlotRenderingInfo info,
XYPlot plot,
ValueAxis domainAxis,
ValueAxis rangeAxis,
XYDataset dataset,
int series,
int item,
CrosshairState crosshairState,
int pass) {
WindDataset windData = (WindDataset) dataset;
Paint seriesPaint = getItemPaint(series, item);
Stroke seriesStroke = getItemStroke(series, item);
g2.setPaint(seriesPaint);
g2.setStroke(seriesStroke);
// get the data point...
Number x = windData.getX(series, item);
Number windDir = windData.getWindDirection(series, item);
Number wforce = windData.getWindForce(series, item);
double windForce = wforce.doubleValue();
double wdirt = Math.toRadians(windDir.doubleValue() * (-30.0) - 90.0);
double ax1, ax2, ay1, ay2, rax2, ray2;
RectangleEdge domainAxisLocation = plot.getDomainAxisEdge();
RectangleEdge rangeAxisLocation = plot.getRangeAxisEdge();
ax1 = domainAxis.valueToJava2D(x.doubleValue(), plotArea,
domainAxisLocation);
ay1 = rangeAxis.valueToJava2D(0.0, plotArea, rangeAxisLocation);
rax2 = x.doubleValue() + (windForce * Math.cos(wdirt) * 8000000.0);
ray2 = windForce * Math.sin(wdirt);
ax2 = domainAxis.valueToJava2D(rax2, plotArea, domainAxisLocation);
ay2 = rangeAxis.valueToJava2D(ray2, plotArea, rangeAxisLocation);
int diri = windDir.intValue();
int forcei = wforce.intValue();
String dirforce = diri + "-" + forcei;
Line2D line = new Line2D.Double(ax1, ay1, ax2, ay2);
g2.draw(line);
g2.setPaint(Color.BLUE);
g2.setFont(new Font("Dialog", 1, 9));
g2.drawString(dirforce, (float) ax1, (float) ay1);
g2.setPaint(seriesPaint);
g2.setStroke(seriesStroke);
double alx2, aly2, arx2, ary2;
double ralx2, raly2, rarx2, rary2;
double aldir = Math.toRadians(windDir.doubleValue()
* (-30.0) - 90.0 - 5.0);
ralx2 = wforce.doubleValue() * Math.cos(aldir) * 8000000 * 0.8
+ x.doubleValue();
raly2 = wforce.doubleValue() * Math.sin(aldir) * 0.8;
alx2 = domainAxis.valueToJava2D(ralx2, plotArea, domainAxisLocation);
aly2 = rangeAxis.valueToJava2D(raly2, plotArea, rangeAxisLocation);
line = new Line2D.Double(alx2, aly2, ax2, ay2);
g2.draw(line);
double ardir = Math.toRadians(windDir.doubleValue()
* (-30.0) - 90.0 + 5.0);
rarx2 = wforce.doubleValue() * Math.cos(ardir) * 8000000 * 0.8
+ x.doubleValue();
rary2 = wforce.doubleValue() * Math.sin(ardir) * 0.8;
arx2 = domainAxis.valueToJava2D(rarx2, plotArea, domainAxisLocation);
ary2 = rangeAxis.valueToJava2D(rary2, plotArea, rangeAxisLocation);
line = new Line2D.Double(arx2, ary2, ax2, ay2);
g2.draw(line);
}
/**
* 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();
}
}
| 8,277 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
HighLowRenderer.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/renderer/xy/HighLowRenderer.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.]
*
* --------------------
* HighLowRenderer.java
* --------------------
* (C) Copyright 2001-2012, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): Richard Atkinson;
* Christian W. Zuckschwerdt;
*
* Changes
* -------
* 13-Dec-2001 : Version 1 (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 (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);
* 05-Aug-2002 : Small modification to drawItem method to support URLs for
* HTML image maps (RA);
* 25-Mar-2003 : Implemented Serializable (DG);
* 01-May-2003 : Modified drawItem() method signature (DG);
* 30-Jul-2003 : Modified entity constructor (CZ);
* 31-Jul-2003 : Deprecated constructor (DG);
* 20-Aug-2003 : Implemented Cloneable and PublicCloneable (DG);
* 16-Sep-2003 : Changed ChartRenderingInfo --> PlotRenderingInfo (DG);
* 29-Jan-2004 : Fixed bug (882392) when rendering with
* PlotOrientation.HORIZONTAL (DG);
* 25-Feb-2004 : Replaced CrosshairInfo with CrosshairState. Renamed
* XYToolTipGenerator --> XYItemLabelGenerator (DG);
* 15-Jul-2004 : Switched getX() with getXValue() and getY() with
* getYValue() (DG);
* 01-Nov-2005 : Added optional openTickPaint and closeTickPaint settings (DG);
* ------------- JFREECHART 1.0.0 ---------------------------------------------
* 06-Jul-2006 : Replace dataset methods getX() --> getXValue() (DG);
* 08-Apr-2008 : Added findRangeBounds() override (DG);
* 29-Apr-2008 : Added tickLength field (DG);
* 25-Sep-2008 : Check for non-null entity collection (DG);
* 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.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.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.general.DatasetUtilities;
import org.jfree.data.xy.OHLCDataset;
import org.jfree.data.xy.XYDataset;
/**
* A renderer that draws high/low/open/close markers on an {@link XYPlot}
* (requires a {@link OHLCDataset}). This renderer does not include code to
* calculate the crosshair point for the plot.
*
* The example shown here is generated by the
* <code>HighLowChartDemo1.java</code> program included in the JFreeChart Demo
* Collection:
* <br><br>
* <img src="../../../../../images/HighLowRendererSample.png"
* alt="HighLowRendererSample.png" />
*/
public class HighLowRenderer extends AbstractXYItemRenderer
implements XYItemRenderer, Cloneable, PublicCloneable, Serializable {
/** For serialization. */
private static final long serialVersionUID = -8135673815876552516L;
/** A flag that controls whether the open ticks are drawn. */
private boolean drawOpenTicks;
/** A flag that controls whether the close ticks are drawn. */
private boolean drawCloseTicks;
/**
* The paint used for the open ticks (if <code>null</code>, the series
* paint is used instead).
*/
private transient Paint openTickPaint;
/**
* The paint used for the close ticks (if <code>null</code>, the series
* paint is used instead).
*/
private transient Paint closeTickPaint;
/**
* The tick length (in Java2D units).
*
* @since 1.0.10
*/
private double tickLength;
/**
* The default constructor.
*/
public HighLowRenderer() {
super();
this.drawOpenTicks = true;
this.drawCloseTicks = true;
this.tickLength = 2.0;
}
/**
* Returns the flag that controls whether open ticks are drawn.
*
* @return A boolean.
*
* @see #getDrawCloseTicks()
* @see #setDrawOpenTicks(boolean)
*/
public boolean getDrawOpenTicks() {
return this.drawOpenTicks;
}
/**
* Sets the flag that controls whether open ticks are drawn, and sends a
* {@link RendererChangeEvent} to all registered listeners.
*
* @param draw the flag.
*
* @see #getDrawOpenTicks()
*/
public void setDrawOpenTicks(boolean draw) {
this.drawOpenTicks = draw;
fireChangeEvent();
}
/**
* Returns the flag that controls whether close ticks are drawn.
*
* @return A boolean.
*
* @see #getDrawOpenTicks()
* @see #setDrawCloseTicks(boolean)
*/
public boolean getDrawCloseTicks() {
return this.drawCloseTicks;
}
/**
* Sets the flag that controls whether close ticks are drawn, and sends a
* {@link RendererChangeEvent} to all registered listeners.
*
* @param draw the flag.
*
* @see #getDrawCloseTicks()
*/
public void setDrawCloseTicks(boolean draw) {
this.drawCloseTicks = draw;
fireChangeEvent();
}
/**
* Returns the paint used to draw the ticks for the open values.
*
* @return The paint used to draw the ticks for the open values (possibly
* <code>null</code>).
*
* @see #setOpenTickPaint(Paint)
*/
public Paint getOpenTickPaint() {
return this.openTickPaint;
}
/**
* Sets the paint used to draw the ticks for the open values and sends a
* {@link RendererChangeEvent} to all registered listeners. If you set
* this to <code>null</code> (the default), the series paint is used
* instead.
*
* @param paint the paint (<code>null</code> permitted).
*
* @see #getOpenTickPaint()
*/
public void setOpenTickPaint(Paint paint) {
this.openTickPaint = paint;
fireChangeEvent();
}
/**
* Returns the paint used to draw the ticks for the close values.
*
* @return The paint used to draw the ticks for the close values (possibly
* <code>null</code>).
*
* @see #setCloseTickPaint(Paint)
*/
public Paint getCloseTickPaint() {
return this.closeTickPaint;
}
/**
* Sets the paint used to draw the ticks for the close values and sends a
* {@link RendererChangeEvent} to all registered listeners. If you set
* this to <code>null</code> (the default), the series paint is used
* instead.
*
* @param paint the paint (<code>null</code> permitted).
*
* @see #getCloseTickPaint()
*/
public void setCloseTickPaint(Paint paint) {
this.closeTickPaint = paint;
fireChangeEvent();
}
/**
* Returns the tick length (in Java2D units).
*
* @return The tick length.
*
* @since 1.0.10
*
* @see #setTickLength(double)
*/
public double getTickLength() {
return this.tickLength;
}
/**
* Sets the tick length (in Java2D units) and sends a
* {@link RendererChangeEvent} to all registered listeners.
*
* @param length the length.
*
* @since 1.0.10
*
* @see #getTickLength()
*/
public void setTickLength(double length) {
this.tickLength = length;
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) {
if (dataset != null) {
return DatasetUtilities.findRangeBounds(dataset, true);
}
else {
return null;
}
}
/**
* 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 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) {
double x = dataset.getXValue(series, item);
if (!domainAxis.getRange().contains(x)) {
return; // the x value is not within the axis range
}
double xx = domainAxis.valueToJava2D(x, dataArea,
plot.getDomainAxisEdge());
// setup for collecting optional entity info...
Shape entityArea = null;
EntityCollection entities = null;
if (info != null) {
entities = info.getOwner().getEntityCollection();
}
PlotOrientation orientation = plot.getOrientation();
RectangleEdge location = plot.getRangeAxisEdge();
Paint itemPaint = getItemPaint(series, item);
Stroke itemStroke = getItemStroke(series, item);
g2.setPaint(itemPaint);
g2.setStroke(itemStroke);
if (dataset instanceof OHLCDataset) {
OHLCDataset hld = (OHLCDataset) dataset;
double yHigh = hld.getHighValue(series, item);
double yLow = hld.getLowValue(series, item);
if (!Double.isNaN(yHigh) && !Double.isNaN(yLow)) {
double yyHigh = rangeAxis.valueToJava2D(yHigh, dataArea,
location);
double yyLow = rangeAxis.valueToJava2D(yLow, dataArea,
location);
if (orientation == PlotOrientation.HORIZONTAL) {
g2.draw(new Line2D.Double(yyLow, xx, yyHigh, xx));
entityArea = new Rectangle2D.Double(Math.min(yyLow, yyHigh),
xx - 1.0, Math.abs(yyHigh - yyLow), 2.0);
}
else if (orientation == PlotOrientation.VERTICAL) {
g2.draw(new Line2D.Double(xx, yyLow, xx, yyHigh));
entityArea = new Rectangle2D.Double(xx - 1.0,
Math.min(yyLow, yyHigh), 2.0,
Math.abs(yyHigh - yyLow));
}
}
double delta = getTickLength();
if (domainAxis.isInverted()) {
delta = -delta;
}
if (getDrawOpenTicks()) {
double yOpen = hld.getOpenValue(series, item);
if (!Double.isNaN(yOpen)) {
double yyOpen = rangeAxis.valueToJava2D(yOpen, dataArea,
location);
if (this.openTickPaint != null) {
g2.setPaint(this.openTickPaint);
}
else {
g2.setPaint(itemPaint);
}
if (orientation == PlotOrientation.HORIZONTAL) {
g2.draw(new Line2D.Double(yyOpen, xx + delta, yyOpen,
xx));
}
else if (orientation == PlotOrientation.VERTICAL) {
g2.draw(new Line2D.Double(xx - delta, yyOpen, xx,
yyOpen));
}
}
}
if (getDrawCloseTicks()) {
double yClose = hld.getCloseValue(series, item);
if (!Double.isNaN(yClose)) {
double yyClose = rangeAxis.valueToJava2D(
yClose, dataArea, location);
if (this.closeTickPaint != null) {
g2.setPaint(this.closeTickPaint);
}
else {
g2.setPaint(itemPaint);
}
if (orientation == PlotOrientation.HORIZONTAL) {
g2.draw(new Line2D.Double(yyClose, xx, yyClose,
xx - delta));
}
else if (orientation == PlotOrientation.VERTICAL) {
g2.draw(new Line2D.Double(xx, yyClose, xx + delta,
yyClose));
}
}
}
}
else {
// not a HighLowDataset, so just draw a line connecting this point
// with the previous point...
if (item > 0) {
double x0 = dataset.getXValue(series, item - 1);
double y0 = dataset.getYValue(series, item - 1);
double y = dataset.getYValue(series, item);
if (Double.isNaN(x0) || Double.isNaN(y0) || Double.isNaN(y)) {
return;
}
double xx0 = domainAxis.valueToJava2D(x0, dataArea,
plot.getDomainAxisEdge());
double yy0 = rangeAxis.valueToJava2D(y0, dataArea, location);
double yy = rangeAxis.valueToJava2D(y, dataArea, location);
if (orientation == PlotOrientation.HORIZONTAL) {
g2.draw(new Line2D.Double(yy0, xx0, yy, xx));
}
else if (orientation == PlotOrientation.VERTICAL) {
g2.draw(new Line2D.Double(xx0, yy0, xx, yy));
}
}
}
if (entities != null) {
addEntity(entities, entityArea, 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 {
return super.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 (this == obj) {
return true;
}
if (!(obj instanceof HighLowRenderer)) {
return false;
}
HighLowRenderer that = (HighLowRenderer) obj;
if (this.drawOpenTicks != that.drawOpenTicks) {
return false;
}
if (this.drawCloseTicks != that.drawCloseTicks) {
return false;
}
if (!PaintUtilities.equal(this.openTickPaint, that.openTickPaint)) {
return false;
}
if (!PaintUtilities.equal(this.closeTickPaint, that.closeTickPaint)) {
return false;
}
if (this.tickLength != that.tickLength) {
return false;
}
if (!super.equals(obj)) {
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.openTickPaint = SerialUtilities.readPaint(stream);
this.closeTickPaint = 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.openTickPaint, stream);
SerialUtilities.writePaint(this.closeTickPaint, stream);
}
}
| 18,673 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
YIntervalRenderer.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/renderer/xy/YIntervalRenderer.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.]
*
* ----------------------
* YIntervalRenderer.java
* ----------------------
* (C) Copyright 2002-2012, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 05-Nov-2002 : Version 1 (DG);
* 25-Mar-2003 : Implemented Serializable (DG);
* 01-May-2003 : Modified drawItem() method signature (DG);
* 20-Aug-2003 : Implemented Cloneable and PublicCloneable (DG);
* 16-Sep-2003 : Changed ChartRenderingInfo --> PlotRenderingInfo (DG);
* 25-Feb-2004 : Replaced CrosshairInfo with CrosshairState (DG);
* 27-Sep-2004 : Access double values from dataset (DG);
* 11-Nov-2004 : Now uses ShapeUtilities to translate shapes (DG);
* 11-Apr-2008 : New override for findRangeBounds() (DG);
* 26-May-2008 : Added item label support (DG);
* 27-Mar-2009 : Updated findRangeBounds() (DG);
* 16-Jun-2012 : Removed JCommon dependencies (DG);
*
*/
package org.jfree.chart.renderer.xy;
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.Serializable;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.ui.RectangleEdge;
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.labels.ItemLabelPosition;
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.chart.text.TextUtilities;
import org.jfree.data.Range;
import org.jfree.data.xy.IntervalXYDataset;
import org.jfree.data.xy.XYDataset;
/**
* A renderer that draws a line connecting the start and end Y values for an
* {@link XYPlot}. The example shown here is generated by the
* <code>YIntervalRendererDemo1.java</code> program included in the JFreeChart
* demo collection:
* <br><br>
* <img src="../../../../../images/YIntervalRendererSample.png"
* alt="YIntervalRendererSample.png" />
*/
public class YIntervalRenderer extends AbstractXYItemRenderer
implements XYItemRenderer, Cloneable, PublicCloneable, Serializable {
/** For serialization. */
private static final long serialVersionUID = -2951586537224143260L;
/**
* An additional item label generator. If this is non-null, the item
* label generated will be displayed near the lower y-value at the
* position given by getNegativeItemLabelPosition().
*
* @since 1.0.10
*/
private XYItemLabelGenerator additionalItemLabelGenerator;
/**
* The default constructor.
*/
public YIntervalRenderer() {
super();
this.additionalItemLabelGenerator = null;
}
/**
* Returns the generator for the item labels that appear near the lower
* y-value.
*
* @return The generator (possibly <code>null</code>).
*
* @see #setAdditionalItemLabelGenerator(XYItemLabelGenerator)
*
* @since 1.0.10
*/
public XYItemLabelGenerator getAdditionalItemLabelGenerator() {
return this.additionalItemLabelGenerator;
}
/**
* Sets the generator for the item labels that appear near the lower
* y-value and sends a {@link RendererChangeEvent} to all registered
* listeners. If this is set to <code>null</code>, no item labels will be
* drawn.
*
* @param generator the generator (<code>null</code> permitted).
*
* @see #getAdditionalItemLabelGenerator()
*
* @since 1.0.10
*/
public void setAdditionalItemLabelGenerator(
XYItemLabelGenerator generator) {
this.additionalItemLabelGenerator = generator;
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);
}
/**
* 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 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 (ignored here).
*/
@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...
EntityCollection entities = null;
if (info != null) {
entities = info.getOwner().getEntityCollection();
}
IntervalXYDataset intervalDataset = (IntervalXYDataset) dataset;
double x = intervalDataset.getXValue(series, item);
double yLow = intervalDataset.getStartYValue(series, item);
double yHigh = intervalDataset.getEndYValue(series, item);
RectangleEdge xAxisLocation = plot.getDomainAxisEdge();
RectangleEdge yAxisLocation = plot.getRangeAxisEdge();
double xx = domainAxis.valueToJava2D(x, dataArea, xAxisLocation);
double yyLow = rangeAxis.valueToJava2D(yLow, dataArea, yAxisLocation);
double yyHigh = rangeAxis.valueToJava2D(yHigh, dataArea, yAxisLocation);
Paint p = getItemPaint(series, item);
Stroke s = getItemStroke(series, item);
Line2D line = null;
Shape shape = getItemShape(series, item);
Shape top = null;
Shape bottom = null;
PlotOrientation orientation = plot.getOrientation();
if (orientation == PlotOrientation.HORIZONTAL) {
line = new Line2D.Double(yyLow, xx, yyHigh, xx);
top = ShapeUtilities.createTranslatedShape(shape, yyHigh, xx);
bottom = ShapeUtilities.createTranslatedShape(shape, yyLow, xx);
}
else if (orientation == PlotOrientation.VERTICAL) {
line = new Line2D.Double(xx, yyLow, xx, yyHigh);
top = ShapeUtilities.createTranslatedShape(shape, xx, yyHigh);
bottom = ShapeUtilities.createTranslatedShape(shape, xx, yyLow);
}
g2.setPaint(p);
g2.setStroke(s);
g2.draw(line);
g2.fill(top);
g2.fill(bottom);
// for item labels, we have a special case because there is the
// possibility to draw (a) the regular item label near to just the
// upper y-value, or (b) the regular item label near the upper y-value
// PLUS an additional item label near the lower y-value.
if (isItemLabelVisible(series, item)) {
drawItemLabel(g2, orientation, dataset, series, item, xx, yyHigh,
false);
drawAdditionalItemLabel(g2, orientation, dataset, series, item,
xx, yyLow);
}
// add an entity for the item...
if (entities != null) {
addEntity(entities, line.getBounds(), dataset, series, item, 0.0,
0.0);
}
}
/**
* 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).
*/
private void drawAdditionalItemLabel(Graphics2D g2,
PlotOrientation orientation, XYDataset dataset, int series,
int item, double x, double y) {
if (this.additionalItemLabelGenerator == null) {
return;
}
Font labelFont = getItemLabelFont(series, item);
Paint paint = getItemLabelPaint(series, item);
g2.setFont(labelFont);
g2.setPaint(paint);
String label = this.additionalItemLabelGenerator.generateLabel(dataset,
series, item);
ItemLabelPosition position = getNegativeItemLabelPosition(series, item);
Point2D anchorPoint = calculateLabelAnchorPoint(
position.getItemLabelAnchor(), x, y, orientation);
TextUtilities.drawRotatedString(label, g2,
(float) anchorPoint.getX(), (float) anchorPoint.getY(),
position.getTextAnchor(), position.getAngle(),
position.getRotationAnchor());
}
/**
* 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 YIntervalRenderer)) {
return false;
}
YIntervalRenderer that = (YIntervalRenderer) obj;
if (!ObjectUtilities.equal(this.additionalItemLabelGenerator,
that.additionalItemLabelGenerator)) {
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();
}
}
| 11,899 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
StandardXYBarPainter.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/renderer/xy/StandardXYBarPainter.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.]
*
* -------------------------
* StandardXYBarPainter.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.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 XYBarPainter} interface that preserves the
* behaviour of bar painting that existed prior to the introduction of the
* {@link XYBarPainter} interface.
*
* @see GradientXYBarPainter
*
* @since 1.0.11
*/
public class StandardXYBarPainter implements XYBarPainter, Serializable {
/**
* Creates a new instance.
*/
public StandardXYBarPainter() {
}
/**
* 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, XYBarRenderer 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, XYBarRenderer 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(Color.GRAY);
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 StandardXYBarPainter)) {
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,039 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
XYStepRenderer.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/renderer/xy/XYStepRenderer.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.]
*
* -------------------
* XYStepRenderer.java
* -------------------
* (C) Copyright 2002-2013, by Roger Studner and Contributors.
*
* Original Author: Roger Studner;
* Contributor(s): David Gilbert (for Object Refinery Limited);
* Matthias Rose;
* Gerald Struck (fix for bug 1569094);
* Ulrich Voigt (patch 1874890);
* Martin Hoeller (contribution to patch 1874890);
*
* Changes
* -------
* 13-May-2002 : Version 1, contributed by Roger Studner (DG);
* 25-Jun-2002 : Updated import statements (DG);
* 22-Jul-2002 : Added check for null data items (DG);
* 25-Mar-2003 : Implemented Serializable (DG);
* 01-May-2003 : Modified drawItem() method signature (DG);
* 20-Aug-2003 : Implemented Cloneable and PublicCloneable (DG);
* 16-Sep-2003 : Changed ChartRenderingInfo --> PlotRenderingInfo (DG);
* 28-Oct-2003 : Added tooltips, code contributed by Matthias Rose
* (RFE 824857) (DG);
* 10-Feb-2004 : Removed working line (use line from state object instead) (DG);
* 25-Feb-2004 : Replaced CrosshairInfo with CrosshairState. Renamed
* XYToolTipGenerator --> XYItemLabelGenerator (DG);
* 19-Jan-2005 : Now accesses only primitives from dataset (DG);
* 15-Mar-2005 : Fix silly bug in drawItem() method (DG);
* 19-Sep-2005 : Extend XYLineAndShapeRenderer (fixes legend shapes), added
* support for series visibility, and use getDefaultEntityRadius()
* for entity hotspot size (DG);
* ------------- JFREECHART 1.0.x ---------------------------------------------
* 15-Jun-2006 : Added basic support for item labels (DG);
* 11-Oct-2006 : Fixed rendering with horizontal orientation (see bug 1569094),
* thanks to Gerald Struck (DG);
* 06-Feb-2007 : Fixed bug 1086307, crosshairs with multiple axes (DG);
* 14-Feb-2008 : Applied patch 1874890 by Ulrich Voigt (with contribution from
* Martin Hoeller) (DG);
* 14-May-2008 : Call addEntity() in drawItem() (DG);
* 24-Sep-2008 : Fixed bug 2113627 by utilising second pass to draw item
* labels (DG);
* 17-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.Serializable;
import org.jfree.chart.HashUtilities;
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.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;
/**
* Line/Step item renderer for an {@link XYPlot}. This class draws lines
* between data points, only allowing horizontal or vertical lines (steps).
* The example shown here is generated by the
* <code>XYStepRendererDemo1.java</code> program included in the JFreeChart
* demo collection:
* <br><br>
* <img src="../../../../../images/XYStepRendererSample.png"
* alt="XYStepRendererSample.png" />
*/
public class XYStepRenderer extends XYLineAndShapeRenderer
implements XYItemRenderer, Cloneable, PublicCloneable, Serializable {
/** For serialization. */
private static final long serialVersionUID = -8918141928884796108L;
/**
* The factor (from 0.0 to 1.0) that determines the position of the
* step.
*
* @since 1.0.10.
*/
private double stepPoint = 1.0d;
/**
* Constructs a new renderer with no tooltip or URL generation.
*/
public XYStepRenderer() {
this(null, null);
}
/**
* Constructs a new renderer with the specified tool tip and URL
* generators.
*
* @param toolTipGenerator the item label generator (<code>null</code>
* permitted).
* @param urlGenerator the URL generator (<code>null</code> permitted).
*/
public XYStepRenderer(XYToolTipGenerator toolTipGenerator,
XYURLGenerator urlGenerator) {
super();
setDefaultToolTipGenerator(toolTipGenerator);
setURLGenerator(urlGenerator);
setBaseShapesVisible(false);
}
/**
* 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.10
*/
public double getStepPoint() {
return this.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.10
*/
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();
}
/**
* 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 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) {
// do nothing if item is not visible
if (!getItemVisible(series, item)) {
return;
}
PlotOrientation orientation = plot.getOrientation();
Paint seriesPaint = getItemPaint(series, item);
Stroke seriesStroke = getItemStroke(series, item);
g2.setPaint(seriesPaint);
g2.setStroke(seriesStroke);
// get the data point...
double x1 = dataset.getXValue(series, item);
double y1 = dataset.getYValue(series, item);
RectangleEdge xAxisLocation = plot.getDomainAxisEdge();
RectangleEdge yAxisLocation = plot.getRangeAxisEdge();
double transX1 = domainAxis.valueToJava2D(x1, dataArea, xAxisLocation);
double transY1 = (Double.isNaN(y1) ? Double.NaN
: rangeAxis.valueToJava2D(y1, dataArea, yAxisLocation));
if (pass == 0 && item > 0) {
// get the previous data point...
double x0 = dataset.getXValue(series, item - 1);
double y0 = dataset.getYValue(series, item - 1);
double transX0 = domainAxis.valueToJava2D(x0, dataArea,
xAxisLocation);
double transY0 = (Double.isNaN(y0) ? Double.NaN
: rangeAxis.valueToJava2D(y0, dataArea, yAxisLocation));
if (orientation == PlotOrientation.HORIZONTAL) {
if (transY0 == transY1) {
// this represents the situation
// for drawing a horizontal bar.
drawLine(g2, state.workingLine, transY0, transX0, transY1,
transX1);
}
else { //this handles the need to perform a 'step'.
// calculate the step point
double transXs = transX0 + (getStepPoint()
* (transX1 - transX0));
drawLine(g2, state.workingLine, transY0, transX0, transY0,
transXs);
drawLine(g2, state.workingLine, transY0, transXs, transY1,
transXs);
drawLine(g2, state.workingLine, transY1, transXs, transY1,
transX1);
}
}
else if (orientation == PlotOrientation.VERTICAL) {
if (transY0 == transY1) { // this represents the situation
// for drawing a horizontal bar.
drawLine(g2, state.workingLine, transX0, transY0, transX1,
transY1);
}
else { //this handles the need to perform a 'step'.
// calculate the step point
double transXs = transX0 + (getStepPoint()
* (transX1 - transX0));
drawLine(g2, state.workingLine, transX0, transY0, transXs,
transY0);
drawLine(g2, state.workingLine, transXs, transY0, transXs,
transY1);
drawLine(g2, state.workingLine, transXs, transY1, transX1,
transY1);
}
}
// submit this data item as a candidate for the crosshair point
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, null, dataset, series, item, transX1,
transY1);
}
}
if (pass == 1) {
// draw the item label if there is one...
if (isItemLabelVisible(series, item)) {
double xx = transX1;
double yy = transY1;
if (orientation == PlotOrientation.HORIZONTAL) {
xx = transY1;
yy = transX1;
}
drawItemLabel(g2, orientation, dataset, series, item, xx, yy,
(y1 < 0.0));
}
}
}
/**
* A utility method that draws a line but only if none of the coordinates
* are NaN values.
*
* @param g2 the graphics target.
* @param line the line object.
* @param x0 the x-coordinate for the starting point of the line.
* @param y0 the y-coordinate for the starting point of the line.
* @param x1 the x-coordinate for the ending point of the line.
* @param y1 the y-coordinate for the ending point of the line.
*/
private void drawLine(Graphics2D g2, Line2D line, double x0, double y0,
double x1, double y1) {
if (Double.isNaN(x0) || Double.isNaN(x1) || Double.isNaN(y0)
|| Double.isNaN(y1)) {
return;
}
line.setLine(x0, y0, x1, y1);
g2.draw(line);
}
/**
* 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 XYLineAndShapeRenderer)) {
return false;
}
XYStepRenderer that = (XYStepRenderer) obj;
if (this.stepPoint != that.stepPoint) {
return false;
}
return super.equals(obj);
}
/**
* Returns a hash code for this instance.
*
* @return A hash code.
*/
@Override
public int hashCode() {
return HashUtilities.hashCode(super.hashCode(), this.stepPoint);
}
/**
* 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,161 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
XYBubbleRenderer.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/renderer/xy/XYBubbleRenderer.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.]
*
* ---------------------
* XYBubbleRenderer.java
* ---------------------
* (C) Copyright 2003-2012, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): Christian W. Zuckschwerdt;
*
* Changes
* -------
* 28-Jan-2003 : Version 1 (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);
* 10-Feb-2004 : Small change to drawItem() method to make cut-and-paste
* overriding easier (DG);
* 15-Jul-2004 : Switched getZ() and getZValue() methods (DG);
* 19-Jan-2005 : Now accesses only primitives from dataset (DG);
* 28-Feb-2005 : Modify renderer to use circles in legend (DG);
* 17-Mar-2005 : Fixed bug in bubble bounds calculation (DG);
* 20-Apr-2005 : Use generators for legend tooltips and URLs (DG);
* ------------- JFREECHART 1.0.x ---------------------------------------------
* 13-Dec-2005 : Added support for item labels (bug 1373371) (DG);
* 20-Jan-2006 : Check flag for drawing item labels (DG);
* 21-Sep-2006 : Respect the outline paint and stroke settings (DG);
* 24-Jan-2007 : Added new equals() override (DG);
* 06-Feb-2007 : Fixed bug 1086307, crosshairs with multiple axes (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);
* 13-Jun-2007 : Fixed seriesVisibility bug (DG);
* 17-Jun-2008 : Apply legend shape, font and paint attributes (DG);
* 17-Jun-2012 : Remove 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.Ellipse2D;
import java.awt.geom.Rectangle2D;
import org.jfree.chart.LegendItem;
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.plot.CrosshairState;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.PlotRenderingInfo;
import org.jfree.chart.plot.XYPlot;
import org.jfree.data.xy.XYDataset;
import org.jfree.data.xy.XYZDataset;
/**
* A renderer that draws a circle at each data point with a diameter that is
* determined by the z-value in the dataset (the renderer requires the dataset
* to be an instance of {@link XYZDataset}. The example shown here
* is generated by the <code>XYBubbleChartDemo1.java</code> program
* included in the JFreeChart demo collection:
* <br><br>
* <img src="../../../../../images/XYBubbleRendererSample.png"
* alt="XYBubbleRendererSample.png" />
*/
public class XYBubbleRenderer extends AbstractXYItemRenderer
implements XYItemRenderer, PublicCloneable {
/** For serialization. */
public static final long serialVersionUID = -5221991598674249125L;
/**
* A constant to specify that the bubbles drawn by this renderer should be
* scaled on both axes (see {@link #XYBubbleRenderer(int)}).
*/
public static final int SCALE_ON_BOTH_AXES = 0;
/**
* A constant to specify that the bubbles drawn by this renderer should be
* scaled on the domain axis (see {@link #XYBubbleRenderer(int)}).
*/
public static final int SCALE_ON_DOMAIN_AXIS = 1;
/**
* A constant to specify that the bubbles drawn by this renderer should be
* scaled on the range axis (see {@link #XYBubbleRenderer(int)}).
*/
public static final int SCALE_ON_RANGE_AXIS = 2;
/** Controls how the width and height of the bubble are scaled. */
private int scaleType;
/**
* Constructs a new renderer.
*/
public XYBubbleRenderer() {
this(SCALE_ON_BOTH_AXES);
}
/**
* Constructs a new renderer with the specified type of scaling.
*
* @param scaleType the type of scaling (must be one of:
* {@link #SCALE_ON_BOTH_AXES}, {@link #SCALE_ON_DOMAIN_AXIS},
* {@link #SCALE_ON_RANGE_AXIS}).
*/
public XYBubbleRenderer(int scaleType) {
super();
if (scaleType < 0 || scaleType > 2) {
throw new IllegalArgumentException("Invalid 'scaleType'.");
}
this.scaleType = scaleType;
setDefaultLegendShape(new Ellipse2D.Double(-4.0, -4.0, 8.0, 8.0));
}
/**
* Returns the scale type that was set when the renderer was constructed.
*
* @return The scale type (one of: {@link #SCALE_ON_BOTH_AXES},
* {@link #SCALE_ON_DOMAIN_AXIS}, {@link #SCALE_ON_RANGE_AXIS}).
*/
public int getScaleType() {
return this.scaleType;
}
/**
* 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 (an {@link XYZDataset} is expected).
* @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) {
// return straight away if the item is not visible
if (!getItemVisible(series, item)) {
return;
}
PlotOrientation orientation = plot.getOrientation();
// get the data point...
double x = dataset.getXValue(series, item);
double y = dataset.getYValue(series, item);
double z = Double.NaN;
if (dataset instanceof XYZDataset) {
XYZDataset xyzData = (XYZDataset) dataset;
z = xyzData.getZValue(series, item);
}
if (!Double.isNaN(z)) {
RectangleEdge domainAxisLocation = plot.getDomainAxisEdge();
RectangleEdge rangeAxisLocation = plot.getRangeAxisEdge();
double transX = domainAxis.valueToJava2D(x, dataArea,
domainAxisLocation);
double transY = rangeAxis.valueToJava2D(y, dataArea,
rangeAxisLocation);
double transDomain = 0.0;
double transRange = 0.0;
double zero;
switch(getScaleType()) {
case SCALE_ON_DOMAIN_AXIS:
zero = domainAxis.valueToJava2D(0.0, dataArea,
domainAxisLocation);
transDomain = domainAxis.valueToJava2D(z, dataArea,
domainAxisLocation) - zero;
transRange = transDomain;
break;
case SCALE_ON_RANGE_AXIS:
zero = rangeAxis.valueToJava2D(0.0, dataArea,
rangeAxisLocation);
transRange = zero - rangeAxis.valueToJava2D(z, dataArea,
rangeAxisLocation);
transDomain = transRange;
break;
default:
double zero1 = domainAxis.valueToJava2D(0.0, dataArea,
domainAxisLocation);
double zero2 = rangeAxis.valueToJava2D(0.0, dataArea,
rangeAxisLocation);
transDomain = domainAxis.valueToJava2D(z, dataArea,
domainAxisLocation) - zero1;
transRange = zero2 - rangeAxis.valueToJava2D(z, dataArea,
rangeAxisLocation);
}
transDomain = Math.abs(transDomain);
transRange = Math.abs(transRange);
Ellipse2D circle = null;
if (orientation == PlotOrientation.VERTICAL) {
circle = new Ellipse2D.Double(transX - transDomain / 2.0,
transY - transRange / 2.0, transDomain, transRange);
}
else if (orientation == PlotOrientation.HORIZONTAL) {
circle = new Ellipse2D.Double(transY - transRange / 2.0,
transX - transDomain / 2.0, transRange, transDomain);
}
g2.setPaint(getItemPaint(series, item));
g2.fill(circle);
g2.setStroke(getItemOutlineStroke(series, item));
g2.setPaint(getItemOutlinePaint(series, item));
g2.draw(circle);
if (isItemLabelVisible(series, item)) {
if (orientation == PlotOrientation.VERTICAL) {
drawItemLabel(g2, orientation, dataset, series, item,
transX, transY, false);
}
else if (orientation == PlotOrientation.HORIZONTAL) {
drawItemLabel(g2, orientation, dataset, series, item,
transY, transX, false);
}
}
// add an entity if this info is being collected
EntityCollection entities = null;
if (info != null) {
entities = info.getOwner().getEntityCollection();
if (entities != null && circle.intersects(dataArea)) {
addEntity(entities, circle, dataset, series, item,
circle.getCenterX(), circle.getCenterY());
}
}
int domainAxisIndex = plot.getDomainAxisIndex(domainAxis);
int rangeAxisIndex = plot.getRangeAxisIndex(rangeAxis);
updateCrosshairValues(crosshairState, x, y, domainAxisIndex,
rangeAxisIndex, transX, transY, orientation);
}
}
/**
* Returns a legend item for the specified series. The default method
* is overridden so that the legend displays circles for all 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) {
LegendItem result = null;
XYPlot plot = getPlot();
if (plot == null) {
return 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);
Paint paint = lookupSeriesPaint(series);
Paint outlinePaint = lookupSeriesOutlinePaint(series);
Stroke outlineStroke = lookupSeriesOutlineStroke(series);
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.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 XYBubbleRenderer)) {
return false;
}
XYBubbleRenderer that = (XYBubbleRenderer) obj;
if (this.scaleType != that.scaleType) {
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,765 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.