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 |
---|---|---|---|---|---|---|---|---|---|---|---|
GradientPaintTransformer.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/ui/GradientPaintTransformer.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.]
*
* -----------------------------
* GradientPaintTransformer.java
* -----------------------------
* (C) Copyright 2003-2012, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* $Id: GradientPaintTransformer.java,v 1.4 2007/04/03 12:34:13 mungady Exp $
*
* Changes
* -------
* 28-Oct-2003 : Version 1 (DG);
* 16-Jun-2012 : Moved from JCommon to JFreeChart (DG);
*
*/
package org.jfree.chart.ui;
import java.awt.GradientPaint;
import java.awt.Shape;
/**
* The interface for a class that can transform a <code>GradientPaint</code> to
* fit an arbitrary shape.
*/
public interface GradientPaintTransformer {
/**
* Transforms a <code>GradientPaint</code> instance to fit some target
* shape. Classes that implement this method typically return a new
* instance of <code>GradientPaint</code>.
*
* @param paint the original paint (not <code>null</code>).
* @param target the reference area (not <code>null</code>).
*
* @return A transformed paint.
*/
public GradientPaint transform(GradientPaint paint, Shape target);
}
| 2,394 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
Layer.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/ui/Layer.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.]
*
* ----------
* Layer.java
* ----------
* (C) Copyright 2003-2013, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes:
* --------
* 17-Sep-2003 : Version 1 (DG);
* 16-Jun-2012 : Moved from JCommon to JFreeChart (DG);
*
*/
package org.jfree.chart.ui;
/**
* Used to indicate either the foreground or background layer.
*/
public enum Layer {
/** Foreground. */
FOREGROUND("Layer.FOREGROUND"),
/** Background. */
BACKGROUND("Layer.BACKGROUND");
/** The name. */
private String name;
/**
* Private constructor.
*
* @param name the name.
*/
private Layer(final String name) {
this.name = name;
}
/**
* Returns a string representing the object.
*
* @return The string.
*/
@Override
public String toString() {
return this.name;
}
}
| 2,158 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
PaintSample.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/ui/PaintSample.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.]
*
* ----------------
* PaintSample.java
* ----------------
* (C) Copyright 2000-2012, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes (from 26-Oct-2001)
* --------------------------
* 26-Oct-2001 : Changed package to com.jrefinery.ui.*;
* 14-Oct-2002 : Fixed errors reported by Checkstyle (DG);
* 17-Jun-2012 : Moved from JCommon to JFreeChart (DG);
*
*/
package org.jfree.chart.ui;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Insets;
import java.awt.Paint;
import java.awt.geom.Rectangle2D;
import javax.swing.JComponent;
/**
* A panel that displays a paint sample.
*/
public class PaintSample extends JComponent {
/** The paint. */
private Paint paint;
/** The preferred size of the component. */
private Dimension preferredSize;
/**
* Standard constructor - builds a paint sample.
*
* @param paint the paint to display.
*/
public PaintSample(final Paint paint) {
this.paint = paint;
this.preferredSize = new Dimension(80, 12);
}
/**
* Returns the current Paint object being displayed in the panel.
*
* @return the paint.
*/
public Paint getPaint() {
return this.paint;
}
/**
* Sets the Paint object being displayed in the panel.
*
* @param paint the paint.
*/
public void setPaint(final Paint paint) {
this.paint = paint;
repaint();
}
/**
* Returns the preferred size of the component.
*
* @return the preferred size.
*/
@Override
public Dimension getPreferredSize() {
return this.preferredSize;
}
/**
* Fills the component with the current Paint.
*
* @param g the graphics device.
*/
@Override
public void paintComponent(final Graphics g) {
final Graphics2D g2 = (Graphics2D) g;
final Dimension size = getSize();
final Insets insets = getInsets();
final double xx = insets.left;
final double yy = insets.top;
final double ww = size.getWidth() - insets.left - insets.right - 1;
final double hh = size.getHeight() - insets.top - insets.bottom - 1;
final Rectangle2D area = new Rectangle2D.Double(xx, yy, ww, hh);
g2.setPaint(this.paint);
g2.fill(area);
g2.setPaint(Color.BLACK);
g2.draw(area);
}
}
| 3,742 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
HorizontalAlignment.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/ui/HorizontalAlignment.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.]
*
* ------------------------
* HorizontalAlignment.java
* ------------------------
* (C) Copyright 2004-2012, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes:
* --------
* 08-Jan-2004 : Version 1 (DG);
* 12-Jun-2012 : Moved from JCommon to JFreeChart (DG);
*
*/
package org.jfree.chart.ui;
/**
* An enumeration of the horizontal alignment types (<code>LEFT</code>,
* <code>RIGHT</code> and <code>CENTER</code>).
*/
public enum HorizontalAlignment {
/** Left alignment. */
LEFT("HorizontalAlignment.LEFT"),
/** Right alignment. */
RIGHT("HorizontalAlignment.RIGHT"),
/** Center alignment. */
CENTER("HorizontalAlignment.CENTER");
/** The name. */
private String name;
/**
* Private constructor.
*
* @param name the name.
*/
private HorizontalAlignment(final String name) {
this.name = name;
}
/**
* Returns a string representing the object.
*
* @return The string.
*/
@Override
public String toString() {
return this.name;
}
}
| 2,373 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
Drawable.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/ui/Drawable.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.]
*
* -------------
* Drawable.java
* -------------
* (C) Copyright 2002-2012, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes (from 30-May-2002)
* --------------------------
* 25-Jun-2002 : Version 1 (DG);
* 14-Jun-2012 : Moved from JCommon to JFreeChart (DG);
*
*/
package org.jfree.chart.ui;
import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;
/**
* An interface for an object that can draw itself within an area on a Graphics2D.
*
* @author David Gilbert
*/
public interface Drawable {
/**
* Draws the object.
*
* @param g2 the graphics device.
* @param area the area inside which the object should be drawn.
*/
public void draw(Graphics2D g2, Rectangle2D area);
}
| 2,041 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
Size2D.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/ui/Size2D.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.]
*
* -----------
* Size2D.java
* -----------
* (C) Copyright 2000-2012, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes (from 26-Oct-2001)
* --------------------------
* 26-Oct-2001 : Changed package to com.jrefinery.ui.*;
* 14-Oct-2002 : Fixed errors reported by Checkstyle (DG);
* 10-Nov-2004 : Added default constructor, added setWidth() and setHeight()
* methods, added equals() method, implemented Cloneable,
* PublicCloneable and Serializable (DG);
* 02-Feb-2005 : Added toString() method (DG);
* 16-Jun-2012 : Moved from JCommon to JFreeChart (DG);
*
*/
package org.jfree.chart.ui;
import java.io.Serializable;
import org.jfree.chart.util.PublicCloneable;
/**
* A simple class for representing the dimensions of an object. It would be
* better to use <code>Dimension2D</code>, but this class is broken on various
* JDK releases (particularly JDK 1.3.1, refer to bugs 4189446 and 4976448 on
* the Java bug parade).
*/
public class Size2D implements Cloneable, PublicCloneable, Serializable {
/** For serialization. */
private static final long serialVersionUID = 2558191683786418168L;
/** The width. */
public double width;
/** The height. */
public double height;
/**
* Creates a new instance with zero width and height.
*/
public Size2D() {
this(0.0, 0.0);
}
/**
* Creates a new instance with the specified width and height.
*
* @param width the width.
* @param height the height.
*/
public Size2D(final double width, final double height) {
this.width = width;
this.height = height;
}
/**
* Returns the width.
*
* @return The width.
*/
public double getWidth() {
return this.width;
}
/**
* Sets the width.
*
* @param width the width.
*/
public void setWidth(final double width) {
this.width = width;
}
/**
* Returns the height.
*
* @return The height.
*/
public double getHeight() {
return this.height;
}
/**
* Sets the height.
*
* @param height the height.
*/
public void setHeight(final double height) {
this.height = height;
}
/**
* Returns a string representation of this instance, mostly used for
* debugging purposes.
*
* @return A string.
*/
@Override
public String toString() {
return "Size2D[width=" + this.width + ", height=" + this.height + "]";
}
/**
* Compares this instance for equality with an arbitrary object.
*
* @param obj the object (<code>null</code> permitted).
*
* @return A boolean.
*/
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof Size2D)) {
return false;
}
final Size2D that = (Size2D) obj;
if (this.width != that.width) {
return false;
}
if (this.height != that.height) {
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 {
return super.clone();
}
}
| 4,747 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
FontChooserPanel.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/ui/FontChooserPanel.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.]
*
* ---------------------
* FontChooserPanel.java
* ---------------------
* (C) Copyright 2000-2012, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): Arnaud Lelievre;
*
* $Id: FontChooserPanel.java,v 1.6 2008/12/18 09:57:32 mungady Exp $
*
* Changes (from 26-Oct-2001)
* --------------------------
* 26-Oct-2001 : Changed package to com.jrefinery.ui.*;
* 14-Oct-2002 : Fixed errors reported by Checkstyle (DG);
* 08-Sep-2003 : Added internationalization via use of properties resourceBundle (RFE 690236) (AL);
* 21-Feb-2004 : The FontParameter of the constructor was never used (TM);
* 18-Dec-2008 : Use ResourceBundleWrapper - see JFreeChart patch 1607918 by
* Jess Thrysoee (DG);
* 15-Jun-2012 : Moved from JCommon to JFreeChart (DG);
*
*/
package org.jfree.chart.ui;
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.GraphicsEnvironment;
import java.awt.GridLayout;
import java.util.ResourceBundle;
import javax.swing.BorderFactory;
import javax.swing.JCheckBox;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ListModel;
import org.jfree.chart.util.ResourceBundleWrapper;
/**
* A panel for choosing a font from the available system fonts - still a bit of
* a hack at the moment, but good enough for demonstration applications.
*/
public class FontChooserPanel extends JPanel {
private static final long serialVersionUID = 1L;
/** The font sizes that can be selected. */
public static final String[] SIZES = {"9", "10", "11", "12", "14", "16",
"18", "20", "22", "24", "28", "36", "48", "72"};
/** The list of fonts. */
private JList fontlist;
/** The list of sizes. */
private JList sizelist;
/** The checkbox that indicates whether the font is bold. */
private JCheckBox bold;
/** The checkbox that indicates whether or not the font is italic. */
private JCheckBox italic;
/** The resourceBundle for the localization. */
protected static ResourceBundle localizationResources =
ResourceBundleWrapper.getBundle("org.jfree.ui.LocalizationBundle");
/**
* Standard constructor - builds a FontChooserPanel initialised with the
* specified font.
*
* @param font the initial font to display.
*/
public FontChooserPanel(final Font font) {
final GraphicsEnvironment g
= GraphicsEnvironment.getLocalGraphicsEnvironment();
final String[] fonts = g.getAvailableFontFamilyNames();
setLayout(new BorderLayout());
final JPanel right = new JPanel(new BorderLayout());
final JPanel fontPanel = new JPanel(new BorderLayout());
fontPanel.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createEtchedBorder(),
localizationResources.getString("Font")));
this.fontlist = new JList(fonts);
final JScrollPane fontpane = new JScrollPane(this.fontlist);
fontpane.setBorder(BorderFactory.createEtchedBorder());
fontPanel.add(fontpane);
add(fontPanel);
final JPanel sizePanel = new JPanel(new BorderLayout());
sizePanel.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createEtchedBorder(),
localizationResources.getString("Size")));
this.sizelist = new JList(SIZES);
final JScrollPane sizepane = new JScrollPane(this.sizelist);
sizepane.setBorder(BorderFactory.createEtchedBorder());
sizePanel.add(sizepane);
final JPanel attributes = new JPanel(new GridLayout(1, 2));
this.bold = new JCheckBox(localizationResources.getString("Bold"));
this.italic = new JCheckBox(localizationResources.getString("Italic"));
attributes.add(this.bold);
attributes.add(this.italic);
attributes.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createEtchedBorder(),
localizationResources.getString("Attributes")));
right.add(sizePanel, BorderLayout.CENTER);
right.add(attributes, BorderLayout.SOUTH);
add(right, BorderLayout.EAST);
setSelectedFont(font);
}
/**
* Returns a Font object representing the selection in the panel.
*
* @return the font.
*/
public Font getSelectedFont() {
return new Font(getSelectedName(), getSelectedStyle(),
getSelectedSize());
}
/**
* Returns the selected name.
*
* @return the name.
*/
public String getSelectedName() {
return (String) this.fontlist.getSelectedValue();
}
/**
* Returns the selected style.
*
* @return the style.
*/
public int getSelectedStyle() {
if (this.bold.isSelected() && this.italic.isSelected()) {
return Font.BOLD + Font.ITALIC;
}
if (this.bold.isSelected()) {
return Font.BOLD;
}
if (this.italic.isSelected()) {
return Font.ITALIC;
}
else {
return Font.PLAIN;
}
}
/**
* Returns the selected size.
*
* @return the size.
*/
public int getSelectedSize() {
final String selected = (String) this.sizelist.getSelectedValue();
if (selected != null) {
return Integer.parseInt(selected);
}
else {
return 10;
}
}
/**
* Initializes the contents of the dialog from the given font
* object.
*
* @param font the font from which to read the properties.
*/
public void setSelectedFont (final Font font) {
if (font == null) {
throw new NullPointerException();
}
this.bold.setSelected(font.isBold());
this.italic.setSelected(font.isItalic());
final String fontName = font.getName();
ListModel model = this.fontlist.getModel();
this.fontlist.clearSelection();
for (int i = 0; i < model.getSize(); i++) {
if (fontName.equals(model.getElementAt(i))) {
this.fontlist.setSelectedIndex(i);
break;
}
}
final String fontSize = String.valueOf(font.getSize());
model = this.sizelist.getModel();
this.sizelist.clearSelection();
for (int i = 0; i < model.getSize(); i++) {
if (fontSize.equals(model.getElementAt(i))) {
this.sizelist.setSelectedIndex(i);
break;
}
}
}
}
| 7,905 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
ApplicationFrame.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/ui/ApplicationFrame.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.]
*
* ---------------------
* ApplicationFrame.java
* ---------------------
* (C) Copyright 2000-2012, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes (from 30-May-2002)
* --------------------------
* 30-May-2002 : Added title (DG);
* 13-Oct-2002 : Fixed errors reported by Checkstyle (DG);
* 14-Jun-2012 : Moved from JCommon to JFreeChart (DG);
*/
package org.jfree.chart.ui;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.JFrame;
/**
* A base class for creating the main frame for simple applications. The frame listens for
* window closing events, and responds by shutting down the JVM. This is OK for small demo
* applications...for more serious applications, you'll want to use something more robust.
*/
public class ApplicationFrame extends JFrame implements WindowListener {
private static final long serialVersionUID = 1L;
/**
* Constructs a new application frame.
*
* @param title the frame title.
*/
public ApplicationFrame(final String title) {
super(title);
addWindowListener(this);
}
public ApplicationFrame() {
}
/**
* Listens for the main window closing, and shuts down the application.
*
* @param event information about the window event.
*/
@Override
public void windowClosing(final WindowEvent event) {
if (event.getWindow() == this) {
dispose();
System.exit(0);
}
}
/**
* Required for WindowListener interface, but not used by this class.
*
* @param event information about the window event.
*/
@Override
public void windowClosed(final WindowEvent event) {
// ignore
}
/**
* Required for WindowListener interface, but not used by this class.
*
* @param event information about the window event.
*/
@Override
public void windowActivated(final WindowEvent event) {
// ignore
}
/**
* Required for WindowListener interface, but not used by this class.
*
* @param event information about the window event.
*/
@Override
public void windowDeactivated(final WindowEvent event) {
// ignore
}
/**
* Required for WindowListener interface, but not used by this class.
*
* @param event information about the window event.
*/
@Override
public void windowDeiconified(final WindowEvent event) {
// ignore
}
/**
* Required for WindowListener interface, but not used by this class.
*
* @param event information about the window event.
*/
@Override
public void windowIconified(final WindowEvent event) {
// ignore
}
/**
* Required for WindowListener interface, but not used by this class.
*
* @param event information about the window event.
*/
@Override
public void windowOpened(final WindowEvent event) {
// ignore
}
}
| 4,310 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
RectangleAnchor.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/ui/RectangleAnchor.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.]
*
* --------------------
* RectangleAnchor.java
* --------------------
* (C) Copyright 2003-2012, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes:
* --------
* 31-Oct-2003 (DG);
* 01-Apr-2004 : Changed java.awt.geom.Dimension2D to org.jfree.ui.Size2D
* because of JDK bug 4976448 which persists on JDK 1.3.1 (DG);
* 21-Jan-2005 : Changed return type of coordinates() method (DG);
* 16-Jun-2012 : Moved from JCommon to JFreeChart (DG);
*
*/
package org.jfree.chart.ui;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
/**
* Used to indicate an anchor point for a rectangle.
*/
public enum RectangleAnchor {
/** Center. */
CENTER("RectangleAnchor.CENTER"),
/** Top. */
TOP("RectangleAnchor.TOP"),
/** Top-Left. */
TOP_LEFT("RectangleAnchor.TOP_LEFT"),
/** Top-Right. */
TOP_RIGHT("RectangleAnchor.TOP_RIGHT"),
/** Bottom. */
BOTTOM("RectangleAnchor.BOTTOM"),
/** Bottom-Left. */
BOTTOM_LEFT("RectangleAnchor.BOTTOM_LEFT"),
/** Bottom-Right. */
BOTTOM_RIGHT("RectangleAnchor.BOTTOM_RIGHT"),
/** Left. */
LEFT("RectangleAnchor.LEFT"),
/** Right. */
RIGHT("RectangleAnchor.RIGHT");
/** The name. */
private String name;
/**
* Private constructor.
*
* @param name the name.
*/
private RectangleAnchor(final String name) {
this.name = name;
}
/**
* Returns a string representing the object.
*
* @return The string.
*/
@Override
public String toString() {
return this.name;
}
/**
* Returns the (x, y) coordinates of the specified anchor.
*
* @param rectangle the rectangle.
* @param anchor the anchor.
*
* @return The (x, y) coordinates.
*/
public static Point2D coordinates(final Rectangle2D rectangle,
final RectangleAnchor anchor) {
Point2D result = new Point2D.Double();
if (anchor == RectangleAnchor.CENTER) {
result.setLocation(rectangle.getCenterX(), rectangle.getCenterY());
}
else if (anchor == RectangleAnchor.TOP) {
result.setLocation(rectangle.getCenterX(), rectangle.getMinY());
}
else if (anchor == RectangleAnchor.BOTTOM) {
result.setLocation(rectangle.getCenterX(), rectangle.getMaxY());
}
else if (anchor == RectangleAnchor.LEFT) {
result.setLocation(rectangle.getMinX(), rectangle.getCenterY());
}
else if (anchor == RectangleAnchor.RIGHT) {
result.setLocation(rectangle.getMaxX(), rectangle.getCenterY());
}
else if (anchor == RectangleAnchor.TOP_LEFT) {
result.setLocation(rectangle.getMinX(), rectangle.getMinY());
}
else if (anchor == RectangleAnchor.TOP_RIGHT) {
result.setLocation(rectangle.getMaxX(), rectangle.getMinY());
}
else if (anchor == RectangleAnchor.BOTTOM_LEFT) {
result.setLocation(rectangle.getMinX(), rectangle.getMaxY());
}
else if (anchor == RectangleAnchor.BOTTOM_RIGHT) {
result.setLocation(rectangle.getMaxX(), rectangle.getMaxY());
}
return result;
}
/**
* Creates a new rectangle with the specified dimensions that is aligned to
* the given anchor point <code>(anchorX, anchorY)</code>.
*
* @param dimensions the dimensions (<code>null</code> not permitted).
* @param anchorX the x-anchor.
* @param anchorY the y-anchor.
* @param anchor the anchor (<code>null</code> not permitted).
*
* @return A rectangle.
*/
public static Rectangle2D createRectangle(final Size2D dimensions,
final double anchorX,
final double anchorY,
final RectangleAnchor anchor) {
Rectangle2D result = null;
final double w = dimensions.getWidth();
final double h = dimensions.getHeight();
if (anchor == RectangleAnchor.CENTER) {
result = new Rectangle2D.Double(
anchorX - w / 2.0, anchorY - h / 2.0, w, h
);
}
else if (anchor == RectangleAnchor.TOP) {
result = new Rectangle2D.Double(
anchorX - w / 2.0, anchorY - h / 2.0, w, h
);
}
else if (anchor == RectangleAnchor.BOTTOM) {
result = new Rectangle2D.Double(
anchorX - w / 2.0, anchorY - h / 2.0, w, h
);
}
else if (anchor == RectangleAnchor.LEFT) {
result = new Rectangle2D.Double(
anchorX, anchorY - h / 2.0, w, h
);
}
else if (anchor == RectangleAnchor.RIGHT) {
result = new Rectangle2D.Double(
anchorX - w, anchorY - h / 2.0, w, h
);
}
else if (anchor == RectangleAnchor.TOP_LEFT) {
result = new Rectangle2D.Double(
anchorX - w / 2.0, anchorY - h / 2.0, w, h
);
}
else if (anchor == RectangleAnchor.TOP_RIGHT) {
result = new Rectangle2D.Double(
anchorX - w / 2.0, anchorY - h / 2.0, w, h
);
}
else if (anchor == RectangleAnchor.BOTTOM_LEFT) {
result = new Rectangle2D.Double(
anchorX - w / 2.0, anchorY - h / 2.0, w, h
);
}
else if (anchor == RectangleAnchor.BOTTOM_RIGHT) {
result = new Rectangle2D.Double(
anchorX - w / 2.0, anchorY - h / 2.0, w, h
);
}
return result;
}
}
| 7,071 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
StrokeChooserPanel.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/ui/StrokeChooserPanel.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.]
*
* -----------------------
* StrokeChooserPanel.java
* -----------------------
* (C) Copyright 2000-2012, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): Dirk Zeitz;
*
* Changes (from 26-Oct-2001)
* --------------------------
* 26-Oct-2001 : Changed package to com.jrefinery.ui.*;
* 14-Oct-2002 : Fixed errors reported by Checkstyle (DG);
* 16-Mar-2004 : Fix for focus problems (DZ);
* 27-Feb-2009 : Fixed bug 2612649, NullPointerException (DG);
* 17-Jun-2012 : Moved from JCommon to JFreeChart (DG);
*
*/
package org.jfree.chart.ui;
import java.awt.BorderLayout;
import java.awt.Stroke;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JPanel;
/**
* A component for choosing a stroke from a list of available strokes. This
* class needs work.
*/
public class StrokeChooserPanel extends JPanel {
/** A combo for selecting the stroke. */
private JComboBox selector;
/**
* Creates a panel containing a combo-box that allows the user to select
* one stroke from a list of available strokes.
*
* @param current the current stroke sample.
* @param available an array of 'available' stroke samples.
*/
public StrokeChooserPanel(StrokeSample current, StrokeSample[] available) {
setLayout(new BorderLayout());
// we've changed the behaviour here to populate the combo box
// with Stroke objects directly - ideally we'd change the signature
// of the constructor too...maybe later.
DefaultComboBoxModel model = new DefaultComboBoxModel();
for (StrokeSample anAvailable : available) {
model.addElement(anAvailable.getStroke());
}
this.selector = new JComboBox(model);
this.selector.setSelectedItem(current.getStroke());
this.selector.setRenderer(new StrokeSample(null));
add(this.selector);
// Changes due to focus problems!! DZ
this.selector.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent evt) {
getSelector().transferFocus();
}
});
}
/**
* Returns the selector component.
*
* @return Returns the selector.
*/
protected final JComboBox getSelector() {
return this.selector;
}
/**
* Returns the selected stroke.
*
* @return The selected stroke (possibly <code>null</code>).
*/
public Stroke getSelectedStroke() {
return (Stroke) this.selector.getSelectedItem();
}
}
| 3,949 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
FontDisplayField.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/ui/FontDisplayField.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.]
*
* ---------------------
* FontDisplayField.java
* ---------------------
* (C) Copyright 2000-2014, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): Arnaud Lelievre;
*
* Changes (from 26-Oct-2001)
* ----------------------------------
* 26-Oct-2001 : Changed package to com.jrefinery.ui.*;
* 14-Oct-2002 : Fixed errors reported by Checkstyle (DG);
* 08-Sep-2003 : Added internationalization via use of properties
* resourceBundle (RFE 690236) (AL);
* 18-Dec-2008 : Use ResourceBundleWrapper - see JFreeChart patch 1607918 by
* Jess Thrysoee (DG);
*
*/
package org.jfree.chart.ui;
import java.awt.Font;
import java.util.ResourceBundle;
import javax.swing.JTextField;
import org.jfree.chart.util.ResourceBundleWrapper;
/**
* A field for displaying a font selection. The display field itself is
* read-only, to the developer must provide another mechanism to allow the
* user to change the font.
*/
public class FontDisplayField extends JTextField {
private static final long serialVersionUID = 1L;
/** The current font. */
private Font displayFont;
/** The resourceBundle for the localization. */
protected static final ResourceBundle localizationResources =
ResourceBundleWrapper.getBundle("org.jfree.chart.ui.LocalizationBundle");
/**
* Standard constructor - builds a FontDescriptionField initialised with
* the specified font.
*
* @param font the font.
*/
public FontDisplayField(Font font) {
super("");
setDisplayFont(font);
setEnabled(false);
}
/**
* Returns the current font.
*
* @return the font.
*/
public Font getDisplayFont() {
return this.displayFont;
}
/**
* Sets the font.
*
* @param font the font.
*/
public void setDisplayFont(Font font) {
this.displayFont = font;
setText(fontToString(this.displayFont));
}
/**
* Returns a string representation of the specified font.
*
* @param font the font.
*
* @return a string describing the font.
*/
private String fontToString(Font font) {
if (font != null) {
return font.getFontName() + ", " + font.getSize();
}
else {
return localizationResources.getString("No_Font_Selected");
}
}
}
| 3,676 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
StrokeSample.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/ui/StrokeSample.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.]
*
* -----------------
* StrokeSample.java
* -----------------
* (C) Copyright 2000-2012, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes (from 26-Oct-2001)
* --------------------------
* 26-Oct-2001 : Changed package to com.jrefinery.ui.*;
* 14-Oct-2002 : Fixed errors reported by Checkstyle (DG);
* 21-Mar-2003 : Fixed null pointer exception, bug 705126 (DG);
* 16-Jun-2012 : Moved from JCommon to JFreeChart (DG);
*
*/
package org.jfree.chart.ui;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Insets;
import java.awt.RenderingHints;
import java.awt.Stroke;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import javax.swing.JComponent;
import javax.swing.JList;
import javax.swing.ListCellRenderer;
/**
* A panel that displays a stroke sample.
*/
public class StrokeSample extends JComponent implements ListCellRenderer {
private static final long serialVersionUID = 1L;
/** The stroke being displayed (may be null). */
private Stroke stroke;
/** The preferred size of the component. */
private Dimension preferredSize;
/**
* Creates a StrokeSample for the specified stroke.
*
* @param stroke the sample stroke (<code>null</code> permitted).
*/
public StrokeSample(final Stroke stroke) {
this.stroke = stroke;
this.preferredSize = new Dimension(80, 18);
setPreferredSize(this.preferredSize);
}
/**
* Returns the current Stroke object being displayed.
*
* @return The stroke (possibly <code>null</code>).
*/
public Stroke getStroke() {
return this.stroke;
}
/**
* Sets the stroke object being displayed and repaints the component.
*
* @param stroke the stroke (<code>null</code> permitted).
*/
public void setStroke(final Stroke stroke) {
this.stroke = stroke;
repaint();
}
/**
* Returns the preferred size of the component.
*
* @return the preferred size of the component.
*/
@Override
public Dimension getPreferredSize() {
return this.preferredSize;
}
/**
* Draws a line using the sample stroke.
*
* @param g the graphics device.
*/
@Override
public void paintComponent(final Graphics g) {
final Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
final Dimension size = getSize();
final Insets insets = getInsets();
final double xx = insets.left;
final double yy = insets.top;
final double ww = size.getWidth() - insets.left - insets.right;
final double hh = size.getHeight() - insets.top - insets.bottom;
// calculate point one
final Point2D one = new Point2D.Double(xx + 6, yy + hh / 2);
// calculate point two
final Point2D two = new Point2D.Double(xx + ww - 6, yy + hh / 2);
// draw a circle at point one
final Ellipse2D circle1 = new Ellipse2D.Double(one.getX() - 5,
one.getY() - 5, 10, 10);
final Ellipse2D circle2 = new Ellipse2D.Double(two.getX() - 6,
two.getY() - 5, 10, 10);
// draw a circle at point two
g2.draw(circle1);
g2.fill(circle1);
g2.draw(circle2);
g2.fill(circle2);
// draw a line connecting the points
final Line2D line = new Line2D.Double(one, two);
if (this.stroke != null) {
g2.setStroke(this.stroke);
g2.draw(line);
}
}
/**
* Returns a list cell renderer for the stroke, so the sample can be
* displayed in a list or combo.
*
* @param list the list.
* @param value the value.
* @param index the index.
* @param isSelected selected?
* @param cellHasFocus focussed?
*
* @return the component for rendering.
*/
@Override
public Component getListCellRendererComponent(JList list, Object value,
int index, boolean isSelected, boolean cellHasFocus) {
if (value instanceof Stroke) {
setStroke((Stroke) value);
}
else {
setStroke(null);
}
return this;
}
}
| 5,672 | 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/imagemap/package-info.java | /**
* Classes, including {@link org.jfree.chart.imagemap.ImageMapUtilities}, for creating HTML image maps.
*/
package org.jfree.chart.imagemap;
| 146 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
StandardToolTipTagFragmentGenerator.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/imagemap/StandardToolTipTagFragmentGenerator.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.]
*
* ----------------------------------------
* StandardToolTipTagFragmentGenerator.java
* ----------------------------------------
* (C) Copyright 2003-2008, by Richard Atkinson and Contributors.
*
* Original Author: Richard Atkinson;
* Contributors: David Gilbert (for Object Refinery Limited);
*
* Changes
* -------
* 12-Aug-2003 : Version 1 (RA);
* 04-Dec-2007 : Escape tool tip text to fix bug 1400917 (DG);
*
*/
package org.jfree.chart.imagemap;
/**
* Generates tooltips using the HTML title attribute for image map area tags.
*/
public class StandardToolTipTagFragmentGenerator
implements ToolTipTagFragmentGenerator {
/**
* Creates a new instance.
*/
public StandardToolTipTagFragmentGenerator() {
super();
}
/**
* Generates a tooltip string to go in an HTML image map.
*
* @param toolTipText the tooltip.
*
* @return The formatted HTML area tag attribute(s).
*/
@Override
public String generateToolTipFragment(String toolTipText) {
return " title=\"" + ImageMapUtilities.htmlEscape(toolTipText)
+ "\" alt=\"\"";
}
}
| 2,376 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
ToolTipTagFragmentGenerator.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/imagemap/ToolTipTagFragmentGenerator.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.]
*
* --------------------------------
* ToolTipTagFragmentGenerator.java
* --------------------------------
* (C) Copyright 2003-2008, by Richard Atkinson and Contributors.
*
* Original Author: Richard Atkinson;
*
* Changes
* -------
* 12-Aug-2003 : Version 1 (RA);
* 05-Dec-2007 : Updated API docs (DG);
*
*/
package org.jfree.chart.imagemap;
/**
* Interface for generating the tooltip fragment of an HTML image map area tag.
* The fragment should be <code>XHTML 1.0</code> compliant.
*/
public interface ToolTipTagFragmentGenerator {
/**
* Generates a tooltip string to go in an HTML image map. To allow for
* varying standards compliance among browsers, this method is expected
* to return an 'alt' attribute IN ADDITION TO whatever it does to create
* the tooltip (often a 'title' attribute).
* <br><br>
* Note that the <code>toolTipText</code> may have been generated from
* user-defined data, so care should be taken to filter/escape any
* characters that may corrupt the HTML tag.
*
* @param toolTipText the tooltip.
*
* @return The formatted HTML area tag attribute(s).
*/
public String generateToolTipFragment(String toolTipText);
}
| 2,459 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
URLTagFragmentGenerator.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/imagemap/URLTagFragmentGenerator.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.]
*
* ----------------------------
* URLTagFragmentGenerator.java
* ----------------------------
* (C) Copyright 2003-2008, by Richard Atkinson and Contributors.
*
* Original Author: Richard Atkinson;
*
* Changes
* -------
* 12-Aug-2003 : Version 1 (RA);
* 13-Dec-2007 : Updated API docs (DG);
*
*/
package org.jfree.chart.imagemap;
import org.jfree.chart.urls.CategoryURLGenerator;
import org.jfree.chart.urls.PieURLGenerator;
import org.jfree.chart.urls.XYURLGenerator;
import org.jfree.chart.urls.XYZURLGenerator;
/**
* Interface for generating the URL fragment of an HTML image map area tag.
*/
public interface URLTagFragmentGenerator {
/**
* Generates a URL string to go in an HTML image map.
* <br><br>
* Note that the <code>urlText</code> will be created by a URL generator
* (such as {@link CategoryURLGenerator}, {@link PieURLGenerator},
* {@link XYURLGenerator} or {@link XYZURLGenerator}) and that generator is
* responsible for ensuring that the URL text is correctly escaped.
*
* @param urlText the URL text (fully escaped).
*
* @return The formatted HTML area tag attribute(s).
*/
public String generateURLFragment(String urlText);
}
| 2,454 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
DynamicDriveToolTipTagFragmentGenerator.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/imagemap/DynamicDriveToolTipTagFragmentGenerator.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.]
*
* --------------------------------------------
* DynamicDriveToolTipTagFragmentGenerator.java
* --------------------------------------------
* (C) Copyright 2003-2009, by Richard Atkinson and Contributors.
*
* Original Author: Richard Atkinson;
* Contributors: David Gilbert (for Object Refinery Limited);
* Fawad Halim - bug 2690293;
*
* Changes
* -------
* 12-Aug-2003 : Version 1 (RA);
* 04-Dec-2007 : Escape tool tip text to fix bug 1400917 (DG);
* 19-Mar-2009 : Escape apostrophes - see bug 2690293 with fix by FH (DG);
*
*/
package org.jfree.chart.imagemap;
/**
* Generates tooltips using the Dynamic Drive DHTML Tip Message
* library (http://www.dynamicdrive.com).
*/
public class DynamicDriveToolTipTagFragmentGenerator
implements ToolTipTagFragmentGenerator {
/** The title, empty string not to display */
protected String title = "";
/** The style number */
protected int style = 1;
/**
* Blank constructor.
*/
public DynamicDriveToolTipTagFragmentGenerator() {
super();
}
/**
* Creates a new generator with specific title and style settings.
*
* @param title title for use in all tooltips, use empty String not to
* display a title.
* @param style style number, see http://www.dynamicdrive.com for more
* information.
*/
public DynamicDriveToolTipTagFragmentGenerator(String title, int style) {
this.title = title;
this.style = style;
}
/**
* Generates a tooltip string to go in an HTML image map.
*
* @param toolTipText the tooltip.
*
* @return The formatted HTML area tag attribute(s).
*/
@Override
public String generateToolTipFragment(String toolTipText) {
return " onMouseOver=\"return stm(['"
+ ImageMapUtilities.javascriptEscape(this.title) + "','"
+ ImageMapUtilities.javascriptEscape(toolTipText) + "'],Style["
+ this.style + "]);\"" + " onMouseOut=\"return htm();\"";
}
}
| 3,304 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
OverLIBToolTipTagFragmentGenerator.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/imagemap/OverLIBToolTipTagFragmentGenerator.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.]
*
* ---------------------------------------
* OverLibToolTipTagFragmentGenerator.java
* ---------------------------------------
* (C) Copyright 2003-2009, by Richard Atkinson and Contributors.
*
* Original Author: Richard Atkinson;
* Contributors: David Gilbert (for Object Refinery Limited);
* Fawad Halim - bug 2690293;
*
* Changes
* -------
* 12-Aug-2003 : Version 1 (RA);
* 04-Dec-2007 : Escape tool tip text to fix bug 1400917 (DG);
* 19-Mar-2009 : Escape apostrophes - see bug 2690293 with fix by FH (DG);
*
*/
package org.jfree.chart.imagemap;
/**
* Generates tooltips using the OverLIB library
* (http://www.bosrup.com/web/overlib/).
*/
public class OverLIBToolTipTagFragmentGenerator
implements ToolTipTagFragmentGenerator {
/**
* Creates a new instance.
*/
public OverLIBToolTipTagFragmentGenerator() {
super();
}
/**
* Generates a tooltip string to go in an HTML image map.
*
* @param toolTipText the tooltip text.
*
* @return The formatted HTML area tag attribute(s).
*/
@Override
public String generateToolTipFragment(String toolTipText) {
return " onMouseOver=\"return overlib('"
+ ImageMapUtilities.javascriptEscape(toolTipText)
+ "');\" onMouseOut=\"return nd();\"";
}
}
| 2,580 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
ImageMapUtilities.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/imagemap/ImageMapUtilities.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.]
*
* ----------------------
* ImageMapUtilities.java
* ----------------------
* (C) Copyright 2004-2012, by Richard Atkinson and Contributors.
*
* Original Author: Richard Atkinson;
* Contributor(s): David Gilbert (for Object Refinery Limited);
* Fawad Halim - bug 2690293;
*
* Changes
* -------
* 02-Aug-2004 : Initial version (RA);
* 13-Jan-2005 : Renamed ImageMapUtilities (DG);
* 19-Jan-2005 : Reversed order of tags for chart entities to get correct
* layering (DG);
* ------------- JFREECHART 1.0.x ---------------------------------------------
* 06-Feb-2006 : API doc updates (DG);
* 04-Dec-2007 : Added htmlEscape() method, and escape 'name' in
* getImageMap() (DG);
* 19-Mar-2009 : Added javascriptEscape() method - see bug 2690293 by FH (DG);
* 25-Mar-2009 : Reimplemented javascriptEscape() (DG);
* 17-Jun-2012 : Removed JCommon dependencies (DG);
*
*/
package org.jfree.chart.imagemap;
import java.io.IOException;
import java.io.PrintWriter;
import org.jfree.chart.ChartRenderingInfo;
import org.jfree.chart.util.StringUtils;
import org.jfree.chart.entity.ChartEntity;
import org.jfree.chart.entity.EntityCollection;
/**
* Collection of utility methods related to producing image maps.
* Functionality was originally in {@link org.jfree.chart.ChartUtilities}.
*/
public class ImageMapUtilities {
/**
* 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).
*
* @throws java.io.IOException if there are any I/O errors.
*/
public static void writeImageMap(PrintWriter writer, String name,
ChartRenderingInfo info) throws IOException {
// defer argument checking...
ImageMapUtilities.writeImageMap(writer, name, info,
new StandardToolTipTagFragmentGenerator(),
new StandardURLTagFragmentGenerator());
}
/**
* 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 java.io.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 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 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 java.io.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 image map element that complies with the XHTML 1.0
* specification.
*
* @param name the map name (<code>null</code> not permitted).
* @param info the chart rendering info (<code>null</code> not permitted).
*
* @return The map element.
*/
public static String getImageMap(String name, ChartRenderingInfo info) {
return ImageMapUtilities.getImageMap(name, info,
new StandardToolTipTagFragmentGenerator(),
new StandardURLTagFragmentGenerator());
}
/**
* Creates an image map element that complies with the XHTML 1.0
* specification.
*
* @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) {
StringBuilder sb = new StringBuilder();
sb.append("<map id=\"" + htmlEscape(name) + "\" name=\""
+ htmlEscape(name) + "\">");
sb.append(StringUtils.getLineSeparator());
EntityCollection entities = info.getEntityCollection();
if (entities != null) {
int count = entities.getEntityCount();
for (int i = count - 1; i >= 0; i--) {
ChartEntity entity = entities.getEntity(i);
if (entity.getToolTipText() != null
|| entity.getURLText() != null) {
String area = entity.getImageMapAreaTag(
toolTipTagFragmentGenerator,
urlTagFragmentGenerator);
if (area.length() > 0) {
sb.append(area);
sb.append(StringUtils.getLineSeparator());
}
}
}
}
sb.append("</map>");
return sb.toString();
}
/**
* Returns a string that is equivalent to the input string, but with
* special characters converted to HTML escape sequences.
*
* @param input the string to escape (<code>null</code> not permitted).
*
* @return A string with characters escaped.
*
* @since 1.0.9
*/
public static String htmlEscape(String input) {
if (input == null) {
throw new IllegalArgumentException("Null 'input' argument.");
}
StringBuilder result = new StringBuilder();
int length = input.length();
for (int i = 0; i < length; i++) {
char c = input.charAt(i);
if (c == '&') {
result.append("&");
}
else if (c == '\"') {
result.append(""");
}
else if (c == '<') {
result.append("<");
}
else if (c == '>') {
result.append(">");
}
else if (c == '\'') {
result.append("'");
}
else if (c == '\\') {
result.append("\");
}
else {
result.append(c);
}
}
return result.toString();
}
/**
* Returns a string that is equivalent to the input string, but with
* special characters converted to JavaScript escape sequences.
*
* @param input the string to escape (<code>null</code> not permitted).
*
* @return A string with characters escaped.
*
* @since 1.0.13
*/
public static String javascriptEscape(String input) {
if (input == null) {
throw new IllegalArgumentException("Null 'input' argument.");
}
StringBuilder result = new StringBuilder();
int length = input.length();
for (int i = 0; i < length; i++) {
char c = input.charAt(i);
if (c == '\"') {
result.append("\\\"");
}
else if (c == '\'') {
result.append("\\'");
}
else if (c == '\\') {
result.append("\\\\");
}
else {
result.append(c);
}
}
return result.toString();
}
}
| 10,552 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
StandardURLTagFragmentGenerator.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/imagemap/StandardURLTagFragmentGenerator.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.]
*
* ------------------------------------
* StandardURLTagFragmentGenerator.java
* ------------------------------------
* (C) Copyright 2003-2008, by Richard Atkinson and Contributors.
*
* Original Author: Richard Atkinson;
* Contributors: David Gilbert (for Object Refinery Limited);
*
* Changes
* -------
* 12-Aug-2003 : Version 1 (RA);
* 04-Dec-2007 : Encode URL text to fix bug 1400917 (DG);
* 13-Dec-2007 : Revert change from 04-Dec-2007 (DG);
*
*/
package org.jfree.chart.imagemap;
/**
* Generates URLs using the HTML href attribute for image map area tags.
*/
public class StandardURLTagFragmentGenerator
implements URLTagFragmentGenerator {
/**
* Creates a new instance.
*/
public StandardURLTagFragmentGenerator() {
super();
}
/**
* Generates a URL string to go in an HTML image map.
*
* @param urlText the URL text (fully escaped).
*
* @return The formatted text
*/
@Override
public String generateURLFragment(String urlText) {
// the URL text should already have been escaped by the URL generator
return " href=\"" + urlText + "\"";
}
}
| 2,396 | 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/resources/package-info.java | /**
* Localised resources for the JFreeChart class library.
*/
package org.jfree.chart.resources;
| 100 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
JFreeChartResources.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/resources/JFreeChartResources.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.]
*
* ------------------------
* JFreeChartResources.java
* ------------------------
* (C) Copyright 2002-2012, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
*/
package org.jfree.chart.resources;
import java.util.ListResourceBundle;
/**
* Localised resources for JFreeChart.
*/
public class JFreeChartResources extends ListResourceBundle {
/**
* Returns the array of strings in the resource bundle.
*
* @return The resources.
*/
public Object[][] getContents() {
return CONTENTS;
}
/** The resources to be localised. */
private static final Object[][] CONTENTS = {
{"project.name", "JFreeChart-FSE"},
{"project.version", "<pre-release>"},
{"project.info", "http://www.jfree.org/jfreechart/index.html"},
{"project.copyright",
"(C)opyright 2000-2012, by Object Refinery Limited and Contributors"}
};
}
| 2,215 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
NumberComparator.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/axis/NumberComparator.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.]
*
* (C) Copyright 2012, by Michael Clarke and Contributors.
*
* Original Author: Michael Clarke;
*
*/
package org.jfree.chart.axis;
import java.io.Serializable;
import java.util.Comparator;
public class NumberComparator implements Comparator<Number>, Serializable {
@Override
public int compare(Number o1, Number o2) {
if (o1 == null) {
if (o2 == null) {
return 0;
}
return 1;
}
if (o2 == null) {
return -1;
}
return ((Double) o1.doubleValue()).compareTo(o2.doubleValue());
}
}
| 1,825 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
TickUnit.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/axis/TickUnit.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.]
*
* -------------
* TickUnit.java
* -------------
* (C) Copyright 2001-2008, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 19-Dec-2001 : Added standard header (DG);
* 01-May-2002 : Changed the unit size from Number to double (DG);
* 26-Sep-2002 : Fixed errors reported by Checkstyle (DG);
* 08-Nov-2002 : Moved to new package com.jrefinery.chart.axis (DG);
* 26-Mar-2003 : Implemented Serializable (DG);
* 05-Sep-2005 : Implemented hashCode(), thanks to Thomas Morgner (DG);
* 02-Aug-2007 : Added minorTickCount attribute (DG);
*
*/
package org.jfree.chart.axis;
import java.io.Serializable;
/**
* Base class representing a tick unit. This determines the spacing of the
* tick marks on an axis.
* <P>
* This class (and any subclasses) should be immutable, the reason being that
* ORDERED collections of tick units are maintained and if one instance can be
* changed, it may destroy the order of the collection that it belongs to.
* In addition, if the implementations are immutable, they can belong to
* multiple collections.
*
* @see ValueAxis
*/
public abstract class TickUnit implements Comparable<TickUnit>, Serializable {
/** For serialization. */
private static final long serialVersionUID = 510179855057013974L;
/** The size of the tick unit. */
private double size;
/**
* The number of minor ticks.
*
* @since 1.0.7
*/
private int minorTickCount;
/**
* Constructs a new tick unit.
*
* @param size the tick unit size.
*/
public TickUnit(double size) {
this.size = size;
}
/**
* Constructs a new tick unit.
*
* @param size the tick unit size.
* @param minorTickCount the minor tick count.
*
* @since 1.0.7
*/
public TickUnit(double size, int minorTickCount) {
this.size = size;
this.minorTickCount = minorTickCount;
}
/**
* Returns the size of the tick unit.
*
* @return The size of the tick unit.
*/
public double getSize() {
return this.size;
}
/**
* Returns the minor tick count.
*
* @return The minor tick count.
*
* @since 1.0.7
*/
public int getMinorTickCount() {
return this.minorTickCount;
}
/**
* Converts the supplied value to a string.
* <P>
* Subclasses may implement special formatting by overriding this method.
*
* @param value the data value.
*
* @return Value as string.
*/
public String valueToString(double value) {
return String.valueOf(value);
}
/**
* Compares this tick unit to an arbitrary object.
*
* @param other the object to compare against.
*
* @return <code>1</code> if the size of the other object is less than this,
* <code>0</code> if both have the same size and <code>-1</code> this
* size is less than the others.
*/
@Override
public int compareTo(TickUnit other) {
if (this.size > other.getSize()) {
return 1;
}
else if (this.size < other.getSize()) {
return -1;
}
else {
return 0;
}
}
/**
* Tests this unit for equality with another object.
*
* @param obj the object.
*
* @return <code>true</code> or <code>false</code>.
*/
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof TickUnit)) {
return false;
}
TickUnit that = (TickUnit) obj;
if (this.size != that.size) {
return false;
}
if (this.minorTickCount != that.minorTickCount) {
return false;
}
return true;
}
/**
* Returns a hash code for this instance.
*
* @return A hash code.
*/
@Override
public int hashCode() {
long temp = this.size != +0.0d ? Double.doubleToLongBits(this.size)
: 0L;
return (int) (temp ^ (temp >>> 32));
}
}
| 5,437 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
ExtendedCategoryAxis.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/axis/ExtendedCategoryAxis.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.]
*
* -------------------------
* ExtendedCategoryAxis.java
* -------------------------
* (C) Copyright 2003-2012, by Object Refinery Limited and Contributors.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 07-Nov-2003 : Version 1 (DG);
* 07-Jan-2004 : Updated the createLabel() method (DG);
* 29-Jan-2004 : Added paint attribute (DG);
* ------------- JFREECHART 1.0.x ---------------------------------------------
* 21-Mar-2007 : Implemented equals(), clone() and fixed serialization (DG);
* 17-Jun-2012 : Removed JCommon dependencies (DG);
*
*/
package org.jfree.chart.axis;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.HashMap;
import java.util.Map;
import org.jfree.chart.ui.RectangleEdge;
import org.jfree.chart.util.PaintUtilities;
import org.jfree.chart.event.AxisChangeEvent;
import org.jfree.chart.text.TextBlock;
import org.jfree.chart.text.TextFragment;
import org.jfree.chart.text.TextLine;
import org.jfree.chart.util.SerialUtilities;
/**
* An extended version of the {@link CategoryAxis} class that supports
* sublabels on the axis.
*/
public class ExtendedCategoryAxis extends CategoryAxis {
/** For serialization. */
static final long serialVersionUID = -3004429093959826567L;
/** Storage for the sublabels. */
private Map<Comparable, String> sublabels;
/** The sublabel font. */
private Font sublabelFont;
/** The sublabel paint. */
private transient Paint sublabelPaint;
/**
* Creates a new axis.
*
* @param label the axis label.
*/
public ExtendedCategoryAxis(String label) {
super(label);
this.sublabels = new HashMap<Comparable, String>();
this.sublabelFont = new Font("SansSerif", Font.PLAIN, 10);
this.sublabelPaint = Color.BLACK;
}
/**
* Returns the font for the sublabels.
*
* @return The font (never <code>null</code>).
*
* @see #setSubLabelFont(Font)
*/
public Font getSubLabelFont() {
return this.sublabelFont;
}
/**
* Sets the font for the sublabels and sends an {@link AxisChangeEvent} to
* all registered listeners.
*
* @param font the font (<code>null</code> not permitted).
*
* @see #getSubLabelFont()
*/
public void setSubLabelFont(Font font) {
if (font == null) {
throw new IllegalArgumentException("Null 'font' argument.");
}
this.sublabelFont = font;
notifyListeners(new AxisChangeEvent(this));
}
/**
* Returns the paint for the sublabels.
*
* @return The paint (never <code>null</code>).
*
* @see #setSubLabelPaint(Paint)
*/
public Paint getSubLabelPaint() {
return this.sublabelPaint;
}
/**
* Sets the paint for the sublabels and sends an {@link AxisChangeEvent}
* to all registered listeners.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getSubLabelPaint()
*/
public void setSubLabelPaint(Paint paint) {
if (paint == null) {
throw new IllegalArgumentException("Null 'paint' argument.");
}
this.sublabelPaint = paint;
notifyListeners(new AxisChangeEvent(this));
}
/**
* Adds a sublabel for a category.
*
* @param category the category.
* @param label the label.
*/
public void addSubLabel(Comparable category, String label) {
this.sublabels.put(category, label);
}
/**
* Overrides the default behaviour by adding the sublabel to the text
* block that is used for the category label.
*
* @param category the category.
* @param width the width (not used yet).
* @param edge the location of the axis.
* @param g2 the graphics device.
*
* @return A label.
*/
@Override
protected TextBlock createLabel(Comparable category, float width,
RectangleEdge edge, Graphics2D g2) {
TextBlock label = super.createLabel(category, width, edge, g2);
String s = this.sublabels.get(category);
if (s != null) {
if (edge == RectangleEdge.TOP || edge == RectangleEdge.BOTTOM) {
TextLine line = new TextLine(s, this.sublabelFont,
this.sublabelPaint);
label.addLine(line);
}
else if (edge == RectangleEdge.LEFT
|| edge == RectangleEdge.RIGHT) {
TextLine line = label.getLastLine();
if (line != null) {
line.addFragment(new TextFragment(" " + s,
this.sublabelFont, this.sublabelPaint));
}
}
}
return label;
}
/**
* Tests this axis 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 ExtendedCategoryAxis)) {
return false;
}
ExtendedCategoryAxis that = (ExtendedCategoryAxis) obj;
if (!this.sublabelFont.equals(that.sublabelFont)) {
return false;
}
if (!PaintUtilities.equal(this.sublabelPaint, that.sublabelPaint)) {
return false;
}
if (!this.sublabels.equals(that.sublabels)) {
return false;
}
return super.equals(obj);
}
/**
* Returns a clone of this axis.
*
* @return A clone.
*
* @throws CloneNotSupportedException if there is a problem cloning.
*/
@Override
public Object clone() throws CloneNotSupportedException {
ExtendedCategoryAxis clone = (ExtendedCategoryAxis) super.clone();
clone.sublabels = new HashMap<Comparable, String>(this.sublabels);
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.sublabelPaint, 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.sublabelPaint = SerialUtilities.readPaint(stream);
}
}
| 8,240 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
AxisLabelLocation.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/axis/AxisLabelLocation.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.]
*
* ----------------------
* AxisLabelLocation.java
* ----------------------
* (C) Copyright 2013, by Object Refinery Limited and Contributors.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes:
* --------
* 05-Aug-2013 : Version 1 (DG);
*
*/
package org.jfree.chart.axis;
import java.awt.geom.Rectangle2D;
import org.jfree.chart.ui.TextAnchor;
/**
* Used to indicate the location of an axis label on a 2D plot.
*/
public enum AxisLabelLocation {
/** Axis label at the top. */
HIGH_END("HIGH_END"),
/** Axis label at the middle. */
MIDDLE("MIDDLE"),
/** Axis label at the bottom. */
LOW_END("LOW_END");
/** The name. */
private String name;
/**
* Private constructor.
*
* @param name the name.
*/
private AxisLabelLocation(String name) {
this.name = name;
}
/**
* Returns a string representing the object.
*
* @return The string.
*/
@Override
public String toString() {
return this.name;
}
public double labelLocationX(Rectangle2D dataArea) {
if (this == LOW_END) {
return dataArea.getMinX();
}
if (this == MIDDLE) {
return dataArea.getCenterX();
}
if (this == HIGH_END) {
return dataArea.getMaxX();
}
throw new IllegalStateException("Unrecognised AxisLabelLocation.");
}
public double labelLocationY(Rectangle2D dataArea) {
if (this == LOW_END) {
return dataArea.getMaxY();
}
if (this == MIDDLE) {
return dataArea.getCenterY();
}
if (this == HIGH_END) {
return dataArea.getMinY();
}
throw new IllegalStateException("Unrecognised AxisLabelLocation.");
}
public TextAnchor labelAnchorH() {
if (this == HIGH_END) {
return TextAnchor.CENTER_RIGHT;
}
if (this == MIDDLE) {
return TextAnchor.CENTER;
}
if (this == LOW_END) {
return TextAnchor.CENTER_LEFT;
}
throw new RuntimeException("Unexpected AxisLabelLocation: " + this);
}
public TextAnchor labelAnchorV() {
if (this == HIGH_END) {
return TextAnchor.CENTER_RIGHT;
}
if (this == MIDDLE) {
return TextAnchor.CENTER;
}
if (this == LOW_END) {
return TextAnchor.CENTER_LEFT;
}
throw new RuntimeException("Unexpected AxisLabelLocation: " + this);
}
}
| 3,824 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
PeriodAxisLabelInfo.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/axis/PeriodAxisLabelInfo.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.]
*
* ------------------------
* PeriodAxisLabelInfo.java
* ------------------------
* (C) Copyright 2004-2013, by Object Refinery Limited and Contributors.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 01-Jun-2004 : Version 1 (DG);
* 23-Feb-2005 : Replaced Spacer with RectangleInsets (DG);
* 01-Mar-2005 : Modified constructors to accept DateFormat (DG);
* 20-May-2005 : Added default constants and null argument checks in the
* constructor (DG);
* 02-Mar-2009 : Updated createInstance to use locale (DG);
* 17-Jun-2012 : Removed JCommon dependencies (DG);
*
*/
package org.jfree.chart.axis;
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.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import org.jfree.chart.ui.RectangleInsets;
import org.jfree.chart.util.ParamChecks;
import org.jfree.chart.util.SerialUtilities;
import org.jfree.data.time.RegularTimePeriod;
/**
* A record that contains information for one "band" of date labels in
* a {@link PeriodAxis}.
*/
public class PeriodAxisLabelInfo implements Serializable {
/** For serialization. */
private static final long serialVersionUID = 5710451740920277357L;
/** The default insets. */
public static final RectangleInsets DEFAULT_INSETS
= new RectangleInsets(2, 2, 2, 2);
/** The default font. */
public static final Font DEFAULT_FONT
= new Font("SansSerif", Font.PLAIN, 10);
/** The default label paint. */
public static final Paint DEFAULT_LABEL_PAINT = Color.BLACK;
/** The default divider stroke. */
public static final Stroke DEFAULT_DIVIDER_STROKE = new BasicStroke(0.5f);
/** The default divider paint. */
public static final Paint DEFAULT_DIVIDER_PAINT = Color.GRAY;
/** The subclass of {@link RegularTimePeriod} to use for this band. */
private Class<? extends RegularTimePeriod> periodClass;
/** Controls the gaps around the band. */
private RectangleInsets padding;
/** The date formatter. */
private DateFormat dateFormat;
/** The label font. */
private Font labelFont;
/** The label paint. */
private transient Paint labelPaint;
/** A flag that controls whether or not dividers are visible. */
private boolean drawDividers;
/** The stroke used to draw the dividers. */
private transient Stroke dividerStroke;
/** The paint used to draw the dividers. */
private transient Paint dividerPaint;
/**
* Creates a new instance.
*
* @param periodClass the subclass of {@link RegularTimePeriod} to use
* (<code>null</code> not permitted).
* @param dateFormat the date format (<code>null</code> not permitted).
*/
public PeriodAxisLabelInfo(Class<? extends RegularTimePeriod> periodClass,
DateFormat dateFormat) {
this(periodClass, dateFormat, DEFAULT_INSETS, DEFAULT_FONT,
DEFAULT_LABEL_PAINT, true, DEFAULT_DIVIDER_STROKE,
DEFAULT_DIVIDER_PAINT);
}
/**
* Creates a new instance.
*
* @param periodClass the subclass of {@link RegularTimePeriod} to use
* (<code>null</code> not permitted).
* @param dateFormat the date format (<code>null</code> not permitted).
* @param padding controls the space around the band (<code>null</code>
* not permitted).
* @param labelFont the label font (<code>null</code> not permitted).
* @param labelPaint the label paint (<code>null</code> not permitted).
* @param drawDividers a flag that controls whether dividers are drawn.
* @param dividerStroke the stroke used to draw the dividers
* (<code>null</code> not permitted).
* @param dividerPaint the paint used to draw the dividers
* (<code>null</code> not permitted).
*/
public PeriodAxisLabelInfo(Class<? extends RegularTimePeriod> periodClass,
DateFormat dateFormat, RectangleInsets padding, Font labelFont,
Paint labelPaint, boolean drawDividers, Stroke dividerStroke,
Paint dividerPaint) {
ParamChecks.nullNotPermitted(periodClass, "periodClass");
ParamChecks.nullNotPermitted(dateFormat, "dateFormat");
ParamChecks.nullNotPermitted(padding, "padding");
ParamChecks.nullNotPermitted(labelFont, "labelFont");
ParamChecks.nullNotPermitted(labelPaint, "labelPaint");
ParamChecks.nullNotPermitted(dividerStroke, "dividerStroke");
ParamChecks.nullNotPermitted(dividerPaint, "dividerPaint");
this.periodClass = periodClass;
this.dateFormat = (DateFormat) dateFormat.clone();
this.padding = padding;
this.labelFont = labelFont;
this.labelPaint = labelPaint;
this.drawDividers = drawDividers;
this.dividerStroke = dividerStroke;
this.dividerPaint = dividerPaint;
}
/**
* Returns the subclass of {@link RegularTimePeriod} that should be used
* to generate the date labels.
*
* @return The class.
*/
public Class getPeriodClass() {
return this.periodClass;
}
/**
* Returns a copy of the date formatter.
*
* @return A copy of the date formatter (never <code>null</code>).
*/
public DateFormat getDateFormat() {
return (DateFormat) this.dateFormat.clone();
}
/**
* Returns the padding for the band.
*
* @return The padding.
*/
public RectangleInsets getPadding() {
return this.padding;
}
/**
* Returns the label font.
*
* @return The label font (never <code>null</code>).
*/
public Font getLabelFont() {
return this.labelFont;
}
/**
* Returns the label paint.
*
* @return The label paint.
*/
public Paint getLabelPaint() {
return this.labelPaint;
}
/**
* Returns a flag that controls whether or not dividers are drawn.
*
* @return A flag.
*/
public boolean getDrawDividers() {
return this.drawDividers;
}
/**
* Returns the stroke used to draw the dividers.
*
* @return The stroke.
*/
public Stroke getDividerStroke() {
return this.dividerStroke;
}
/**
* Returns the paint used to draw the dividers.
*
* @return The paint.
*/
public Paint getDividerPaint() {
return this.dividerPaint;
}
/**
* Creates a time period that includes the specified millisecond, assuming
* the given time zone.
*
* @param millisecond the time.
* @param zone the time zone.
* @param locale the locale.
*
* @return The time period.
*
* @since 1.0.13.
*/
public RegularTimePeriod createInstance(Date millisecond, TimeZone zone,
Locale locale) {
RegularTimePeriod result = null;
try {
Constructor<? extends RegularTimePeriod> c = this.periodClass.getDeclaredConstructor(
new Class[] {Date.class, TimeZone.class, Locale.class});
result = c.newInstance(millisecond, zone, locale);
}
catch (InvocationTargetException e) {
//ignore
}
catch (IllegalAccessException e) {
//ignore
}
catch (NoSuchMethodException e) {
//ignore
}
catch (InstantiationException e) {
//ignore
}
return result;
}
/**
* 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 PeriodAxisLabelInfo) {
PeriodAxisLabelInfo info = (PeriodAxisLabelInfo) obj;
if (!info.periodClass.equals(this.periodClass)) {
return false;
}
if (!info.dateFormat.equals(this.dateFormat)) {
return false;
}
if (!info.padding.equals(this.padding)) {
return false;
}
if (!info.labelFont.equals(this.labelFont)) {
return false;
}
if (!info.labelPaint.equals(this.labelPaint)) {
return false;
}
if (info.drawDividers != this.drawDividers) {
return false;
}
if (!info.dividerStroke.equals(this.dividerStroke)) {
return false;
}
if (!info.dividerPaint.equals(this.dividerPaint)) {
return false;
}
return true;
}
return false;
}
/**
* Returns a hash code for this object.
*
* @return A hash code.
*/
@Override
public int hashCode() {
int result = 41;
result += 37 * this.periodClass.hashCode();
result += 37 * this.dateFormat.hashCode();
return result;
}
/**
* Provides serialization support.
*
* @param stream the output stream.
*
* @throws IOException if there is an I/O error.
*/
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
SerialUtilities.writePaint(this.labelPaint, stream);
SerialUtilities.writeStroke(this.dividerStroke, stream);
SerialUtilities.writePaint(this.dividerPaint, 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.labelPaint = SerialUtilities.readPaint(stream);
this.dividerStroke = SerialUtilities.readStroke(stream);
this.dividerPaint = SerialUtilities.readPaint(stream);
}
}
| 11,840 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
DateAxis.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/axis/DateAxis.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.]
*
* -------------
* DateAxis.java
* -------------
* (C) Copyright 2000-2013, by Object Refinery Limited and Contributors.
*
* Original Author: David Gilbert;
* Contributor(s): Jonathan Nash;
* David Li;
* Michael Rauch;
* Bill Kelemen;
* Pawel Pabis;
* Chris Boek;
* Peter Kolb (patches 1934255 and 2603321);
* Andrew Mickish (patch 1870189);
* Fawad Halim (bug 2201869);
*
* Changes (from 23-Jun-2001)
* --------------------------
* 23-Jun-2001 : Modified to work with null data source (DG);
* 18-Sep-2001 : Updated header (DG);
* 27-Nov-2001 : Changed constructors from public to protected, updated Javadoc
* comments (DG);
* 16-Jan-2002 : Added an optional crosshair, based on the implementation by
* Jonathan Nash (DG);
* 26-Feb-2002 : Updated import statements (DG);
* 22-Apr-2002 : Added a setRange() method (DG);
* 25-Jun-2002 : Removed redundant local variable (DG);
* 25-Jul-2002 : Changed order of parameters in ValueAxis constructor (DG);
* 21-Aug-2002 : The setTickUnit() method now turns off auto-tick unit
* selection (fix for bug id 528885) (DG);
* 05-Sep-2002 : Updated the constructors to reflect changes in the Axis
* class (DG);
* 18-Sep-2002 : Fixed errors reported by Checkstyle (DG);
* 25-Sep-2002 : Added new setRange() methods, and deprecated
* setAxisRange() (DG);
* 04-Oct-2002 : Changed auto tick selection to parallel number axis
* classes (DG);
* 24-Oct-2002 : Added a date format override (DG);
* 08-Nov-2002 : Moved to new package com.jrefinery.chart.axis (DG);
* 14-Jan-2003 : Changed autoRangeMinimumSize from Number --> double, moved
* crosshair settings to the plot (DG);
* 15-Jan-2003 : Removed anchor date (DG);
* 20-Jan-2003 : Removed unnecessary constructors (DG);
* 26-Mar-2003 : Implemented Serializable (DG);
* 02-May-2003 : Added additional units to createStandardDateTickUnits()
* method, as suggested by mhilpert in bug report 723187 (DG);
* 13-May-2003 : Merged HorizontalDateAxis and VerticalDateAxis (DG);
* 24-May-2003 : Added support for underlying timeline for
* SegmentedTimeline (BK);
* 16-Jul-2003 : Applied patch from Pawel Pabis to fix overlapping dates (DG);
* 22-Jul-2003 : Applied patch from Pawel Pabis for monthly ticks (DG);
* 25-Jul-2003 : Fixed bug 777561 and 777586 (DG);
* 13-Aug-2003 : Implemented Cloneable and added equals() method (DG);
* 02-Sep-2003 : Fixes for bug report 790506 (DG);
* 04-Sep-2003 : Fixed tick label alignment when axis appears at the top (DG);
* 10-Sep-2003 : Fixes for segmented timeline (DG);
* 17-Sep-2003 : Fixed a layout bug when multiple domain axes are used (DG);
* 29-Oct-2003 : Added workaround for font alignment in PDF output (DG);
* 07-Nov-2003 : Modified to use new tick classes (DG);
* 12-Nov-2003 : Modified tick labelling to use roll unit from DateTickUnit
* when a calculated tick value is hidden (which can occur in
* segmented date axes) (DG);
* 24-Nov-2003 : Fixed some problems with the auto tick unit selection, and
* fixed bug 846277 (labels missing for inverted axis) (DG);
* 30-Dec-2003 : Fixed bug in refreshTicksHorizontal() when start of time unit
* (ex. 1st of month) was hidden, causing infinite loop (BK);
* 13-Jan-2004 : Fixed bug in previousStandardDate() method (fix by Richard
* Wardle) (DG);
* 21-Jan-2004 : Renamed translateJava2DToValue --> java2DToValue, and
* translateValueToJava2D --> valueToJava2D (DG);
* 12-Mar-2004 : Fixed bug where date format override is ignored for vertical
* axis (DG);
* 16-Mar-2004 : Added plotState to draw() method (DG);
* 07-Apr-2004 : Changed string width calculation (DG);
* 21-Apr-2004 : Fixed bug in estimateMaximumTickLabelWidth() method (bug id
* 939148) (DG);
* 11-Jan-2005 : Removed deprecated methods in preparation for 1.0.0
* release (DG);
* 13-Jan-2005 : Fixed bug (see
* http://www.jfree.org/forum/viewtopic.php?t=11330) (DG);
* 21-Apr-2005 : Replaced Insets with RectangleInsets, removed redundant
* argument from selectAutoTickUnit() (DG);
* ------------- JFREECHART 1.0.x ---------------------------------------------
* 10-Feb-2006 : Added some API doc comments in respect of bug 821046 (DG);
* 19-Apr-2006 : Fixed bug 1472942 in equals() method (DG);
* 25-Sep-2006 : Fixed bug 1564977 missing tick labels (DG);
* 15-Jan-2007 : Added get/setTimeZone() suggested by 'skunk' (DG);
* 18-Jan-2007 : Fixed bug 1638678, time zone for calendar in
* previousStandardDate() (DG);
* 04-Apr-2007 : Use time zone in date calculations (CB);
* 19-Apr-2007 : Fix exceptions in setMinimum/MaximumDate() (DG);
* 03-May-2007 : Fixed minor bugs in previousStandardDate(), with new JUnit
* tests (DG);
* 21-Nov-2007 : Fixed warnings from FindBugs (DG);
* 01-Sep-2008 : Use new methods from DateRange, added fix for bug
* 2078057 (DG);
* 18-Sep-2008 : Added locale to go with timezone (DG);
* 25-Sep-2008 : Added minor tick support, see patch 1934255 by Peter Kolb (DG);
* 25-Nov-2008 : Added bug fix 2201869 by Fawad Halim (DG);
* 21-Jan-2009 : Check tickUnit for minor tick count (DG);
* 19-Mar-2009 : Added entity support - see patch 2603321 by Peter Kolb (DG);
* 08-Feb-2012 : Bugfix for endless-loop, bug 3484403 by rbrabe (MH);
* 16-Jun-2012 : Removed JCommon dependencies (DG);
*
*/
package org.jfree.chart.axis;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.font.FontRenderContext;
import java.awt.font.LineMetrics;
import java.awt.geom.Rectangle2D;
import java.io.Serializable;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
import org.jfree.chart.ui.RectangleEdge;
import org.jfree.chart.ui.RectangleInsets;
import org.jfree.chart.ui.TextAnchor;
import org.jfree.chart.util.ObjectUtilities;
import org.jfree.chart.plot.Plot;
import org.jfree.chart.plot.PlotRenderingInfo;
import org.jfree.chart.plot.ValueAxisPlot;
import org.jfree.chart.util.ParamChecks;
import org.jfree.data.Range;
import org.jfree.data.time.DateRange;
import org.jfree.data.time.Month;
import org.jfree.data.time.RegularTimePeriod;
import org.jfree.data.time.Year;
/**
* The base class for axes that display dates. You will find it easier to
* understand how this axis works if you bear in mind that it really
* displays/measures integer (or long) data, where the integers are
* milliseconds since midnight, 1-Jan-1970. When displaying tick labels, the
* millisecond values are converted back to dates using a
* <code>DateFormat</code> instance.
* <P>
* You can also create a {@link org.jfree.chart.axis.Timeline} and supply in
* the constructor to create an axis that only contains certain domain values.
* For example, this allows you to create a date axis that only contains
* working days.
*/
public class DateAxis extends ValueAxis implements Cloneable, Serializable {
/** For serialization. */
private static final long serialVersionUID = -1013460999649007604L;
/** The default axis range. */
public static final DateRange DEFAULT_DATE_RANGE = new DateRange();
/** The default minimum auto range size. */
public static final double
DEFAULT_AUTO_RANGE_MINIMUM_SIZE_IN_MILLISECONDS = 2.0;
/** The default anchor date. */
public static final Date DEFAULT_ANCHOR_DATE = new Date();
/** The current tick unit. */
private DateTickUnit tickUnit;
/** The override date format. */
private DateFormat dateFormatOverride;
/**
* Tick marks can be displayed at the start or the middle of the time
* period.
*/
private DateTickMarkPosition tickMarkPosition = DateTickMarkPosition.START;
/**
* A timeline that includes all milliseconds (as defined by
* <code>java.util.Date</code>) in the real time line.
*/
private static class DefaultTimeline implements Timeline, Serializable {
/**
* Converts a millisecond into a timeline value.
*
* @param millisecond the millisecond.
*
* @return The timeline value.
*/
@Override
public long toTimelineValue(long millisecond) {
return millisecond;
}
/**
* Converts a date into a timeline value.
*
* @param date the domain value.
*
* @return The timeline value.
*/
@Override
public long toTimelineValue(Date date) {
return date.getTime();
}
/**
* Converts a timeline value into a millisecond (as encoded by
* <code>java.util.Date</code>).
*
* @param value the value.
*
* @return The millisecond.
*/
@Override
public long toMillisecond(long value) {
return value;
}
/**
* Returns <code>true</code> if the timeline includes the specified
* domain value.
*
* @param millisecond the millisecond.
*
* @return <code>true</code>.
*/
@Override
public boolean containsDomainValue(long millisecond) {
return true;
}
/**
* Returns <code>true</code> if the timeline includes the specified
* domain value.
*
* @param date the date.
*
* @return <code>true</code>.
*/
@Override
public boolean containsDomainValue(Date date) {
return true;
}
/**
* Returns <code>true</code> if the timeline includes the specified
* domain value range.
*
* @param from the start value.
* @param to the end value.
*
* @return <code>true</code>.
*/
@Override
public boolean containsDomainRange(long from, long to) {
return true;
}
/**
* Returns <code>true</code> if the timeline includes the specified
* domain value range.
*
* @param from the start date.
* @param to the end date.
*
* @return <code>true</code>.
*/
@Override
public boolean containsDomainRange(Date from, Date to) {
return true;
}
/**
* Tests an object for equality with this instance.
*
* @param object the object.
*
* @return A boolean.
*/
@Override
public boolean equals(Object object) {
if (object == null) {
return false;
}
if (object == this) {
return true;
}
if (object instanceof DefaultTimeline) {
return true;
}
return false;
}
}
/** A static default timeline shared by all standard DateAxis */
private static final Timeline DEFAULT_TIMELINE = new DefaultTimeline();
/** The time zone for the axis. */
private TimeZone timeZone;
/**
* The locale for the axis (<code>null</code> is not permitted).
*
* @since 1.0.11
*/
private Locale locale;
/** Our underlying timeline. */
private Timeline timeline;
/**
* Creates a date axis with no label.
*/
public DateAxis() {
this(null);
}
/**
* Creates a date axis with the specified label.
*
* @param label the axis label (<code>null</code> permitted).
*/
public DateAxis(String label) {
this(label, TimeZone.getDefault(), Locale.getDefault());
}
/**
* Creates a date axis. A timeline is specified for the axis. This allows
* special transformations to occur between a domain of values and the
* values included in the axis.
*
* @see org.jfree.chart.axis.SegmentedTimeline
*
* @param label the axis label (<code>null</code> permitted).
* @param zone the time zone.
* @param locale the locale (<code>null</code> not permitted).
*
* @since 1.0.11
*/
public DateAxis(String label, TimeZone zone, Locale locale) {
super(label, DateAxis.createStandardDateTickUnits(zone, locale));
this.tickUnit = new DateTickUnit(DateTickUnitType.DAY, 1,
new SimpleDateFormat());
setAutoRangeMinimumSize(
DEFAULT_AUTO_RANGE_MINIMUM_SIZE_IN_MILLISECONDS);
setRange(DEFAULT_DATE_RANGE, false, false);
this.dateFormatOverride = null;
this.timeZone = zone;
this.locale = locale;
this.timeline = DEFAULT_TIMELINE;
}
/**
* Returns the time zone for the axis.
*
* @return The time zone (never <code>null</code>).
*
* @since 1.0.4
*
* @see #setTimeZone(TimeZone)
*/
public TimeZone getTimeZone() {
return this.timeZone;
}
/**
* Sets the time zone for the axis and sends an {@link AxisChangeEvent} to
* all registered listeners.
*
* @param zone the time zone (<code>null</code> not permitted).
*
* @since 1.0.4
*
* @see #getTimeZone()
*/
public void setTimeZone(TimeZone zone) {
ParamChecks.nullNotPermitted(zone, "zone");
if (!this.timeZone.equals(zone)) {
this.timeZone = zone;
setStandardTickUnits(createStandardDateTickUnits(zone,
this.locale));
fireChangeEvent();
}
}
/**
* Returns the underlying timeline used by this axis.
*
* @return The timeline.
*/
public Timeline getTimeline() {
return this.timeline;
}
/**
* Sets the underlying timeline to use for this axis. If the timeline is
* changed, an {@link AxisChangeEvent} is sent to all registered listeners.
*
* @param timeline the timeline.
*/
public void setTimeline(Timeline timeline) {
if (this.timeline != timeline) {
this.timeline = timeline;
fireChangeEvent();
}
}
/**
* Returns the tick unit for the axis.
* <p>
* Note: if the <code>autoTickUnitSelection</code> flag is
* <code>true</code> the tick unit may be changed while the axis is being
* drawn, so in that case the return value from this method may be
* irrelevant if the method is called before the axis has been drawn.
*
* @return The tick unit (possibly <code>null</code>).
*
* @see #setTickUnit(DateTickUnit)
* @see ValueAxis#isAutoTickUnitSelection()
*/
public DateTickUnit getTickUnit() {
return this.tickUnit;
}
/**
* Sets the tick unit for the axis. The auto-tick-unit-selection flag is
* set to <code>false</code>, and registered listeners are notified that
* the axis has been changed.
*
* @param unit the tick unit.
*
* @see #getTickUnit()
* @see #setTickUnit(DateTickUnit, boolean, boolean)
*/
public void setTickUnit(DateTickUnit unit) {
setTickUnit(unit, true, true);
}
/**
* Sets the tick unit attribute and, if requested, sends an
* {@link AxisChangeEvent} to all registered listeners.
*
* @param unit the new tick unit.
* @param notify notify registered listeners?
* @param turnOffAutoSelection turn off auto selection?
*
* @see #getTickUnit()
*/
public void setTickUnit(DateTickUnit unit, boolean notify,
boolean turnOffAutoSelection) {
this.tickUnit = unit;
if (turnOffAutoSelection) {
setAutoTickUnitSelection(false, false);
}
if (notify) {
fireChangeEvent();
}
}
/**
* Returns the date format override. If this is non-null, then it will be
* used to format the dates on the axis.
*
* @return The formatter (possibly <code>null</code>).
*/
public DateFormat getDateFormatOverride() {
return this.dateFormatOverride;
}
/**
* Sets the date format override and sends an {@link AxisChangeEvent} to
* all registered listeners. If this is non-null, then it will be
* used to format the dates on the axis.
*
* @param formatter the date formatter (<code>null</code> permitted).
*/
public void setDateFormatOverride(DateFormat formatter) {
this.dateFormatOverride = formatter;
fireChangeEvent();
}
/**
* Sets the upper and lower bounds for the axis and sends an
* {@link AxisChangeEvent} to all registered listeners. As a side-effect,
* the auto-range flag is set to false.
*
* @param range the new range (<code>null</code> not permitted).
*/
@Override
public void setRange(Range range) {
setRange(range, true, true);
}
/**
* Sets the range for the axis, if requested, sends an
* {@link AxisChangeEvent} to all registered listeners. As a side-effect,
* the auto-range flag is set to <code>false</code> (optional).
*
* @param range the range (<code>null</code> not permitted).
* @param turnOffAutoRange a flag that controls whether or not the auto
* range is turned off.
* @param notify a flag that controls whether or not listeners are
* notified.
*/
@Override
public void setRange(Range range, boolean turnOffAutoRange,
boolean notify) {
ParamChecks.nullNotPermitted(range, "range");
// usually the range will be a DateRange, but if it isn't do a
// conversion...
if (!(range instanceof DateRange)) {
range = new DateRange(range);
}
super.setRange(range, turnOffAutoRange, notify);
}
/**
* Sets the axis range and sends an {@link AxisChangeEvent} to all
* registered listeners.
*
* @param lower the lower bound for the axis.
* @param upper the upper bound for the axis.
*/
public void setRange(Date lower, Date upper) {
if (lower.getTime() >= upper.getTime()) {
throw new IllegalArgumentException("Requires 'lower' < 'upper'.");
}
setRange(new DateRange(lower, upper));
}
/**
* Sets the axis range and sends an {@link AxisChangeEvent} to all
* registered listeners.
*
* @param lower the lower bound for the axis.
* @param upper the upper bound for the axis.
*/
@Override
public void setRange(double lower, double upper) {
if (lower >= upper) {
throw new IllegalArgumentException("Requires 'lower' < 'upper'.");
}
setRange(new DateRange(lower, upper));
}
/**
* Returns the earliest date visible on the axis.
*
* @return The date.
*
* @see #setMinimumDate(Date)
* @see #getMaximumDate()
*/
public Date getMinimumDate() {
Date result;
Range range = getRange();
if (range instanceof DateRange) {
DateRange r = (DateRange) range;
result = r.getLowerDate();
}
else {
result = new Date((long) range.getLowerBound());
}
return result;
}
/**
* Sets the minimum date visible on the axis and sends an
* {@link AxisChangeEvent} to all registered listeners. If
* <code>date</code> is on or after the current maximum date for
* the axis, the maximum date will be shifted to preserve the current
* length of the axis.
*
* @param date the date (<code>null</code> not permitted).
*
* @see #getMinimumDate()
* @see #setMaximumDate(Date)
*/
public void setMinimumDate(Date date) {
ParamChecks.nullNotPermitted(date, "date");
// check the new minimum date relative to the current maximum date
Date maxDate = getMaximumDate();
long maxMillis = maxDate.getTime();
long newMinMillis = date.getTime();
if (maxMillis <= newMinMillis) {
Date oldMin = getMinimumDate();
long length = maxMillis - oldMin.getTime();
maxDate = new Date(newMinMillis + length);
}
setRange(new DateRange(date, maxDate), true, false);
fireChangeEvent();
}
/**
* Returns the latest date visible on the axis.
*
* @return The date.
*
* @see #setMaximumDate(Date)
* @see #getMinimumDate()
*/
public Date getMaximumDate() {
Date result;
Range range = getRange();
if (range instanceof DateRange) {
DateRange r = (DateRange) range;
result = r.getUpperDate();
}
else {
result = new Date((long) range.getUpperBound());
}
return result;
}
/**
* Sets the maximum date visible on the axis and sends an
* {@link AxisChangeEvent} to all registered listeners. If
* <code>maximumDate</code> is on or before the current minimum date for
* the axis, the minimum date will be shifted to preserve the current
* length of the axis.
*
* @param maximumDate the date (<code>null</code> not permitted).
*
* @see #getMinimumDate()
* @see #setMinimumDate(Date)
*/
public void setMaximumDate(Date maximumDate) {
ParamChecks.nullNotPermitted(maximumDate, "maximumDate");
// check the new maximum date relative to the current minimum date
Date minDate = getMinimumDate();
long minMillis = minDate.getTime();
long newMaxMillis = maximumDate.getTime();
if (minMillis >= newMaxMillis) {
Date oldMax = getMaximumDate();
long length = oldMax.getTime() - minMillis;
minDate = new Date(newMaxMillis - length);
}
setRange(new DateRange(minDate, maximumDate), true, false);
fireChangeEvent();
}
/**
* Returns the tick mark position (start, middle or end of the time period).
*
* @return The position (never <code>null</code>).
*/
public DateTickMarkPosition getTickMarkPosition() {
return this.tickMarkPosition;
}
/**
* Sets the tick mark position (start, middle or end of the time period)
* and sends an {@link AxisChangeEvent} to all registered listeners.
*
* @param position the position (<code>null</code> not permitted).
*/
public void setTickMarkPosition(DateTickMarkPosition position) {
ParamChecks.nullNotPermitted(position, "position");
this.tickMarkPosition = position;
fireChangeEvent();
}
/**
* Configures the axis to work with the specified plot. If the axis has
* auto-scaling, then sets the maximum and minimum values.
*/
@Override
public void configure() {
if (isAutoRange()) {
autoAdjustRange();
}
}
/**
* Returns <code>true</code> if the axis hides this value, and
* <code>false</code> otherwise.
*
* @param millis the data value.
*
* @return A value.
*/
public boolean isHiddenValue(long millis) {
return (!this.timeline.containsDomainValue(new Date(millis)));
}
/**
* Translates the data value to the display coordinates (Java 2D User Space)
* of the chart.
*
* @param value the date to be plotted.
* @param area the rectangle (in Java2D space) where the data is to be
* plotted.
* @param edge the axis location.
*
* @return The coordinate corresponding to the supplied data value.
*/
@Override
public double valueToJava2D(double value, Rectangle2D area,
RectangleEdge edge) {
value = this.timeline.toTimelineValue((long) value);
DateRange range = (DateRange) getRange();
double axisMin = this.timeline.toTimelineValue(range.getLowerMillis());
double axisMax = this.timeline.toTimelineValue(range.getUpperMillis());
double result = 0.0;
if (RectangleEdge.isTopOrBottom(edge)) {
double minX = area.getX();
double maxX = area.getMaxX();
if (isInverted()) {
result = maxX + ((value - axisMin) / (axisMax - axisMin))
* (minX - maxX);
}
else {
result = minX + ((value - axisMin) / (axisMax - axisMin))
* (maxX - minX);
}
}
else if (RectangleEdge.isLeftOrRight(edge)) {
double minY = area.getMinY();
double maxY = area.getMaxY();
if (isInverted()) {
result = minY + (((value - axisMin) / (axisMax - axisMin))
* (maxY - minY));
}
else {
result = maxY - (((value - axisMin) / (axisMax - axisMin))
* (maxY - minY));
}
}
return result;
}
/**
* Translates a date to Java2D coordinates, based on the range displayed by
* this axis for the specified data area.
*
* @param date the date.
* @param area the rectangle (in Java2D space) where the data is to be
* plotted.
* @param edge the axis location.
*
* @return The coordinate corresponding to the supplied date.
*/
public double dateToJava2D(Date date, Rectangle2D area,
RectangleEdge edge) {
double value = date.getTime();
return valueToJava2D(value, area, edge);
}
/**
* Translates a Java2D coordinate into the corresponding data value. To
* perform this translation, you need to know the area used for plotting
* data, and which edge the axis is located on.
*
* @param java2DValue the coordinate in Java2D space.
* @param area the rectangle (in Java2D space) where the data is to be
* plotted.
* @param edge the axis location.
*
* @return A data value.
*/
@Override
public double java2DToValue(double java2DValue, Rectangle2D area,
RectangleEdge edge) {
DateRange range = (DateRange) getRange();
double axisMin = this.timeline.toTimelineValue(range.getLowerMillis());
double axisMax = this.timeline.toTimelineValue(range.getUpperMillis());
double min = 0.0;
double max = 0.0;
if (RectangleEdge.isTopOrBottom(edge)) {
min = area.getX();
max = area.getMaxX();
}
else if (RectangleEdge.isLeftOrRight(edge)) {
min = area.getMaxY();
max = area.getY();
}
double result;
if (isInverted()) {
result = axisMax - ((java2DValue - min) / (max - min)
* (axisMax - axisMin));
}
else {
result = axisMin + ((java2DValue - min) / (max - min)
* (axisMax - axisMin));
}
return this.timeline.toMillisecond((long) result);
}
/**
* Calculates the value of the lowest visible tick on the axis.
*
* @param unit date unit to use.
*
* @return The value of the lowest visible tick on the axis.
*/
public Date calculateLowestVisibleTickValue(DateTickUnit unit) {
return nextStandardDate(getMinimumDate(), unit);
}
/**
* Calculates the value of the highest visible tick on the axis.
*
* @param unit date unit to use.
*
* @return The value of the highest visible tick on the axis.
*/
public Date calculateHighestVisibleTickValue(DateTickUnit unit) {
return previousStandardDate(getMaximumDate(), unit);
}
/**
* Returns the previous "standard" date, for a given date and tick unit.
*
* @param date the reference date.
* @param unit the tick unit.
*
* @return The previous "standard" date.
*/
protected Date previousStandardDate(Date date, DateTickUnit unit) {
int milliseconds;
int seconds;
int minutes;
int hours;
int days;
int months;
int years;
Calendar calendar = Calendar.getInstance(this.timeZone, this.locale);
calendar.setTime(date);
int count = unit.getMultiple();
int current = calendar.get(unit.getCalendarField());
int value = count * (current / count);
if (DateTickUnitType.MILLISECOND.equals(unit.getUnitType())) {
years = calendar.get(Calendar.YEAR);
months = calendar.get(Calendar.MONTH);
days = calendar.get(Calendar.DATE);
hours = calendar.get(Calendar.HOUR_OF_DAY);
minutes = calendar.get(Calendar.MINUTE);
seconds = calendar.get(Calendar.SECOND);
calendar.set(years, months, days, hours, minutes, seconds);
calendar.set(Calendar.MILLISECOND, value);
Date mm = calendar.getTime();
if (mm.getTime() >= date.getTime()) {
calendar.set(Calendar.MILLISECOND, value - 1);
mm = calendar.getTime();
}
return mm;
}
else if (DateTickUnitType.SECOND.equals(unit.getUnitType())) {
years = calendar.get(Calendar.YEAR);
months = calendar.get(Calendar.MONTH);
days = calendar.get(Calendar.DATE);
hours = calendar.get(Calendar.HOUR_OF_DAY);
minutes = calendar.get(Calendar.MINUTE);
if (this.tickMarkPosition == DateTickMarkPosition.START) {
milliseconds = 0;
}
else if (this.tickMarkPosition == DateTickMarkPosition.MIDDLE) {
milliseconds = 500;
}
else {
milliseconds = 999;
}
calendar.set(Calendar.MILLISECOND, milliseconds);
calendar.set(years, months, days, hours, minutes, value);
Date dd = calendar.getTime();
if (dd.getTime() >= date.getTime()) {
calendar.set(Calendar.SECOND, value - 1);
dd = calendar.getTime();
}
return dd;
}
else if (DateTickUnitType.MINUTE.equals(unit.getUnitType())) {
years = calendar.get(Calendar.YEAR);
months = calendar.get(Calendar.MONTH);
days = calendar.get(Calendar.DATE);
hours = calendar.get(Calendar.HOUR_OF_DAY);
if (this.tickMarkPosition == DateTickMarkPosition.START) {
seconds = 0;
}
else if (this.tickMarkPosition == DateTickMarkPosition.MIDDLE) {
seconds = 30;
}
else {
seconds = 59;
}
calendar.clear(Calendar.MILLISECOND);
calendar.set(years, months, days, hours, value, seconds);
Date d0 = calendar.getTime();
if (d0.getTime() >= date.getTime()) {
calendar.set(Calendar.MINUTE, value - 1);
d0 = calendar.getTime();
}
return d0;
}
else if (DateTickUnitType.HOUR.equals(unit.getUnitType())) {
years = calendar.get(Calendar.YEAR);
months = calendar.get(Calendar.MONTH);
days = calendar.get(Calendar.DATE);
if (this.tickMarkPosition == DateTickMarkPosition.START) {
minutes = 0;
seconds = 0;
}
else if (this.tickMarkPosition == DateTickMarkPosition.MIDDLE) {
minutes = 30;
seconds = 0;
}
else {
minutes = 59;
seconds = 59;
}
calendar.clear(Calendar.MILLISECOND);
calendar.set(years, months, days, value, minutes, seconds);
Date d1 = calendar.getTime();
if (d1.getTime() >= date.getTime()) {
calendar.set(Calendar.HOUR_OF_DAY, value - 1);
d1 = calendar.getTime();
}
return d1;
}
else if (DateTickUnitType.DAY.equals(unit.getUnitType())) {
years = calendar.get(Calendar.YEAR);
months = calendar.get(Calendar.MONTH);
if (this.tickMarkPosition == DateTickMarkPosition.START) {
hours = 0;
}
else if (this.tickMarkPosition == DateTickMarkPosition.MIDDLE) {
hours = 12;
}
else {
hours = 23;
}
calendar.clear(Calendar.MILLISECOND);
calendar.set(years, months, value, hours, 0, 0);
// long result = calendar.getTimeInMillis();
// won't work with JDK 1.3
Date d2 = calendar.getTime();
if (d2.getTime() >= date.getTime()) {
calendar.set(Calendar.DATE, value - 1);
d2 = calendar.getTime();
}
return d2;
}
else if (DateTickUnitType.MONTH.equals(unit.getUnitType())) {
years = calendar.get(Calendar.YEAR);
calendar.clear(Calendar.MILLISECOND);
calendar.set(years, value, 1, 0, 0, 0);
Month month = new Month(calendar.getTime(), this.timeZone,
this.locale);
Date standardDate = calculateDateForPosition(
month, this.tickMarkPosition);
long millis = standardDate.getTime();
if (millis >= date.getTime()) {
month = (Month) month.previous();
// need to peg the month in case the time zone isn't the
// default - see bug 2078057
month.peg(Calendar.getInstance(this.timeZone));
standardDate = calculateDateForPosition(
month, this.tickMarkPosition);
}
return standardDate;
}
else if (DateTickUnitType.YEAR.equals(unit.getUnitType())) {
if (this.tickMarkPosition == DateTickMarkPosition.START) {
months = 0;
days = 1;
}
else if (this.tickMarkPosition == DateTickMarkPosition.MIDDLE) {
months = 6;
days = 1;
}
else {
months = 11;
days = 31;
}
calendar.clear(Calendar.MILLISECOND);
calendar.set(value, months, days, 0, 0, 0);
Date d3 = calendar.getTime();
if (d3.getTime() >= date.getTime()) {
calendar.set(Calendar.YEAR, value - 1);
d3 = calendar.getTime();
}
return d3;
}
else {
return null;
}
}
/**
* Returns a {@link java.util.Date} corresponding to the specified position
* within a {@link RegularTimePeriod}.
*
* @param period the period.
* @param position the position (<code>null</code> not permitted).
*
* @return A date.
*/
private Date calculateDateForPosition(RegularTimePeriod period,
DateTickMarkPosition position) {
ParamChecks.nullNotPermitted(period, "period");
Date result = null;
if (position == DateTickMarkPosition.START) {
result = new Date(period.getFirstMillisecond());
}
else if (position == DateTickMarkPosition.MIDDLE) {
result = new Date(period.getMiddleMillisecond());
}
else if (position == DateTickMarkPosition.END) {
result = new Date(period.getLastMillisecond());
}
return result;
}
/**
* Returns the first "standard" date (based on the specified field and
* units).
*
* @param date the reference date.
* @param unit the date tick unit.
*
* @return The next "standard" date.
*/
protected Date nextStandardDate(Date date, DateTickUnit unit) {
Date previous = previousStandardDate(date, unit);
Calendar calendar = Calendar.getInstance(this.timeZone, this.locale);
calendar.setTime(previous);
calendar.add(unit.getCalendarField(), unit.getMultiple());
return calendar.getTime();
}
/**
* Returns a collection of standard date tick units that uses the default
* time zone. This collection will be used by default, but you are free
* to create your own collection if you want to (see the
* {@link ValueAxis#setStandardTickUnits(TickUnitSource)} method inherited
* from the {@link ValueAxis} class).
*
* @return A collection of standard date tick units.
*/
public static TickUnitSource createStandardDateTickUnits() {
return createStandardDateTickUnits(TimeZone.getDefault(),
Locale.getDefault());
}
/**
* Returns a collection of standard date tick units. This collection will
* be used by default, but you are free to create your own collection if
* you want to (see the
* {@link ValueAxis#setStandardTickUnits(TickUnitSource)} method inherited
* from the {@link ValueAxis} class).
*
* @param zone the time zone (<code>null</code> not permitted).
* @param locale the locale (<code>null</code> not permitted).
*
* @return A collection of standard date tick units.
*
* @since 1.0.11
*/
public static TickUnitSource createStandardDateTickUnits(TimeZone zone,
Locale locale) {
ParamChecks.nullNotPermitted(zone, "zone");
ParamChecks.nullNotPermitted(locale, "locale");
TickUnits units = new TickUnits();
// date formatters
DateFormat f1 = new SimpleDateFormat("HH:mm:ss.SSS", locale);
DateFormat f2 = new SimpleDateFormat("HH:mm:ss", locale);
DateFormat f3 = new SimpleDateFormat("HH:mm", locale);
DateFormat f4 = new SimpleDateFormat("d-MMM, HH:mm", locale);
DateFormat f5 = new SimpleDateFormat("d-MMM", locale);
DateFormat f6 = new SimpleDateFormat("MMM-yyyy", locale);
DateFormat f7 = new SimpleDateFormat("yyyy", locale);
f1.setTimeZone(zone);
f2.setTimeZone(zone);
f3.setTimeZone(zone);
f4.setTimeZone(zone);
f5.setTimeZone(zone);
f6.setTimeZone(zone);
f7.setTimeZone(zone);
// milliseconds
units.add(new DateTickUnit(DateTickUnitType.MILLISECOND, 1, f1));
units.add(new DateTickUnit(DateTickUnitType.MILLISECOND, 5,
DateTickUnitType.MILLISECOND, 1, f1));
units.add(new DateTickUnit(DateTickUnitType.MILLISECOND, 10,
DateTickUnitType.MILLISECOND, 1, f1));
units.add(new DateTickUnit(DateTickUnitType.MILLISECOND, 25,
DateTickUnitType.MILLISECOND, 5, f1));
units.add(new DateTickUnit(DateTickUnitType.MILLISECOND, 50,
DateTickUnitType.MILLISECOND, 10, f1));
units.add(new DateTickUnit(DateTickUnitType.MILLISECOND, 100,
DateTickUnitType.MILLISECOND, 10, f1));
units.add(new DateTickUnit(DateTickUnitType.MILLISECOND, 250,
DateTickUnitType.MILLISECOND, 10, f1));
units.add(new DateTickUnit(DateTickUnitType.MILLISECOND, 500,
DateTickUnitType.MILLISECOND, 50, f1));
// seconds
units.add(new DateTickUnit(DateTickUnitType.SECOND, 1,
DateTickUnitType.MILLISECOND, 50, f2));
units.add(new DateTickUnit(DateTickUnitType.SECOND, 5,
DateTickUnitType.SECOND, 1, f2));
units.add(new DateTickUnit(DateTickUnitType.SECOND, 10,
DateTickUnitType.SECOND, 1, f2));
units.add(new DateTickUnit(DateTickUnitType.SECOND, 30,
DateTickUnitType.SECOND, 5, f2));
// minutes
units.add(new DateTickUnit(DateTickUnitType.MINUTE, 1,
DateTickUnitType.SECOND, 5, f3));
units.add(new DateTickUnit(DateTickUnitType.MINUTE, 2,
DateTickUnitType.SECOND, 10, f3));
units.add(new DateTickUnit(DateTickUnitType.MINUTE, 5,
DateTickUnitType.MINUTE, 1, f3));
units.add(new DateTickUnit(DateTickUnitType.MINUTE, 10,
DateTickUnitType.MINUTE, 1, f3));
units.add(new DateTickUnit(DateTickUnitType.MINUTE, 15,
DateTickUnitType.MINUTE, 5, f3));
units.add(new DateTickUnit(DateTickUnitType.MINUTE, 20,
DateTickUnitType.MINUTE, 5, f3));
units.add(new DateTickUnit(DateTickUnitType.MINUTE, 30,
DateTickUnitType.MINUTE, 5, f3));
// hours
units.add(new DateTickUnit(DateTickUnitType.HOUR, 1,
DateTickUnitType.MINUTE, 5, f3));
units.add(new DateTickUnit(DateTickUnitType.HOUR, 2,
DateTickUnitType.MINUTE, 10, f3));
units.add(new DateTickUnit(DateTickUnitType.HOUR, 4,
DateTickUnitType.MINUTE, 30, f3));
units.add(new DateTickUnit(DateTickUnitType.HOUR, 6,
DateTickUnitType.HOUR, 1, f3));
units.add(new DateTickUnit(DateTickUnitType.HOUR, 12,
DateTickUnitType.HOUR, 1, f4));
// days
units.add(new DateTickUnit(DateTickUnitType.DAY, 1,
DateTickUnitType.HOUR, 1, f5));
units.add(new DateTickUnit(DateTickUnitType.DAY, 2,
DateTickUnitType.HOUR, 1, f5));
units.add(new DateTickUnit(DateTickUnitType.DAY, 7,
DateTickUnitType.DAY, 1, f5));
units.add(new DateTickUnit(DateTickUnitType.DAY, 15,
DateTickUnitType.DAY, 1, f5));
// months
units.add(new DateTickUnit(DateTickUnitType.MONTH, 1,
DateTickUnitType.DAY, 1, f6));
units.add(new DateTickUnit(DateTickUnitType.MONTH, 2,
DateTickUnitType.DAY, 1, f6));
units.add(new DateTickUnit(DateTickUnitType.MONTH, 3,
DateTickUnitType.MONTH, 1, f6));
units.add(new DateTickUnit(DateTickUnitType.MONTH, 4,
DateTickUnitType.MONTH, 1, f6));
units.add(new DateTickUnit(DateTickUnitType.MONTH, 6,
DateTickUnitType.MONTH, 1, f6));
// years
units.add(new DateTickUnit(DateTickUnitType.YEAR, 1,
DateTickUnitType.MONTH, 1, f7));
units.add(new DateTickUnit(DateTickUnitType.YEAR, 2,
DateTickUnitType.MONTH, 3, f7));
units.add(new DateTickUnit(DateTickUnitType.YEAR, 5,
DateTickUnitType.YEAR, 1, f7));
units.add(new DateTickUnit(DateTickUnitType.YEAR, 10,
DateTickUnitType.YEAR, 1, f7));
units.add(new DateTickUnit(DateTickUnitType.YEAR, 25,
DateTickUnitType.YEAR, 5, f7));
units.add(new DateTickUnit(DateTickUnitType.YEAR, 50,
DateTickUnitType.YEAR, 10, f7));
units.add(new DateTickUnit(DateTickUnitType.YEAR, 100,
DateTickUnitType.YEAR, 20, f7));
return units;
}
/**
* Rescales the axis to ensure that all data is visible.
*/
@Override
protected void autoAdjustRange() {
Plot plot = getPlot();
if (plot == null) {
return; // no plot, no data
}
if (plot instanceof ValueAxisPlot) {
ValueAxisPlot vap = (ValueAxisPlot) plot;
Range r = vap.getDataRange(this);
if (r == null) {
r = new DateRange();
}
long upper = this.timeline.toTimelineValue(
(long) r.getUpperBound());
long lower;
long fixedAutoRange = (long) getFixedAutoRange();
if (fixedAutoRange > 0.0) {
lower = upper - fixedAutoRange;
}
else {
lower = this.timeline.toTimelineValue((long) r.getLowerBound());
double range = upper - lower;
long minRange = (long) getAutoRangeMinimumSize();
if (range < minRange) {
long expand = (long) (minRange - range) / 2;
upper = upper + expand;
lower = lower - expand;
}
upper = upper + (long) (range * getUpperMargin());
lower = lower - (long) (range * getLowerMargin());
}
upper = this.timeline.toMillisecond(upper);
lower = this.timeline.toMillisecond(lower);
DateRange dr = new DateRange(new Date(lower), new Date(upper));
setRange(dr, false, false);
}
}
/**
* Selects an appropriate tick value for the axis. The strategy is to
* display as many ticks as possible (selected from an array of 'standard'
* tick units) without the labels overlapping.
*
* @param g2 the graphics device.
* @param dataArea the area defined by the axes.
* @param edge the axis location.
*/
protected void selectAutoTickUnit(Graphics2D g2, Rectangle2D dataArea,
RectangleEdge edge) {
if (RectangleEdge.isTopOrBottom(edge)) {
selectHorizontalAutoTickUnit(g2, dataArea, edge);
}
else if (RectangleEdge.isLeftOrRight(edge)) {
selectVerticalAutoTickUnit(g2, dataArea, edge);
}
}
/**
* Selects an appropriate tick size for the axis. The strategy is to
* display as many ticks as possible (selected from a collection of
* 'standard' tick units) without the labels overlapping.
*
* @param g2 the graphics device.
* @param dataArea the area defined by the axes.
* @param edge the axis location.
*/
protected void selectHorizontalAutoTickUnit(Graphics2D g2,
Rectangle2D dataArea, RectangleEdge edge) {
long shift = 0;
double zero = valueToJava2D(shift + 0.0, dataArea, edge);
double tickLabelWidth = estimateMaximumTickLabelWidth(g2,
getTickUnit());
// start with the current tick unit...
TickUnitSource tickUnits = getStandardTickUnits();
TickUnit unit1 = tickUnits.getCeilingTickUnit(getTickUnit());
double x1 = valueToJava2D(shift + unit1.getSize(), dataArea, edge);
double unit1Width = Math.abs(x1 - zero);
// then extrapolate...
double guess = (tickLabelWidth / unit1Width) * unit1.getSize();
DateTickUnit unit2 = (DateTickUnit) tickUnits.getCeilingTickUnit(guess);
double x2 = valueToJava2D(shift + unit2.getSize(), dataArea, edge);
double unit2Width = Math.abs(x2 - zero);
tickLabelWidth = estimateMaximumTickLabelWidth(g2, unit2);
if (tickLabelWidth > unit2Width) {
unit2 = (DateTickUnit) tickUnits.getLargerTickUnit(unit2);
}
setTickUnit(unit2, false, false);
}
/**
* Selects an appropriate tick size for the axis. The strategy is to
* display as many ticks as possible (selected from a collection of
* 'standard' tick units) without the labels overlapping.
*
* @param g2 the graphics device.
* @param dataArea the area in which the plot should be drawn.
* @param edge the axis location.
*/
protected void selectVerticalAutoTickUnit(Graphics2D g2,
Rectangle2D dataArea, RectangleEdge edge) {
// start with the current tick unit...
TickUnitSource tickUnits = getStandardTickUnits();
double zero = valueToJava2D(0.0, dataArea, edge);
// start with a unit that is at least 1/10th of the axis length
double estimate1 = getRange().getLength() / 10.0;
DateTickUnit candidate1
= (DateTickUnit) tickUnits.getCeilingTickUnit(estimate1);
double labelHeight1 = estimateMaximumTickLabelHeight(g2, candidate1);
double y1 = valueToJava2D(candidate1.getSize(), dataArea, edge);
double candidate1UnitHeight = Math.abs(y1 - zero);
// now extrapolate based on label height and unit height...
double estimate2
= (labelHeight1 / candidate1UnitHeight) * candidate1.getSize();
DateTickUnit candidate2
= (DateTickUnit) tickUnits.getCeilingTickUnit(estimate2);
double labelHeight2 = estimateMaximumTickLabelHeight(g2, candidate2);
double y2 = valueToJava2D(candidate2.getSize(), dataArea, edge);
double unit2Height = Math.abs(y2 - zero);
// make final selection...
DateTickUnit finalUnit;
if (labelHeight2 < unit2Height) {
finalUnit = candidate2;
}
else {
finalUnit = (DateTickUnit) tickUnits.getLargerTickUnit(candidate2);
}
setTickUnit(finalUnit, false, false);
}
/**
* Estimates the maximum width of the tick labels, assuming the specified
* tick unit is used.
* <P>
* Rather than computing the string bounds of every tick on the axis, we
* just look at two values: the lower bound and the upper bound for the
* axis. These two values will usually be representative.
*
* @param g2 the graphics device.
* @param unit the tick unit to use for calculation.
*
* @return The estimated maximum width of the tick labels.
*/
private double estimateMaximumTickLabelWidth(Graphics2D g2,
DateTickUnit unit) {
RectangleInsets tickLabelInsets = getTickLabelInsets();
double result = tickLabelInsets.getLeft() + tickLabelInsets.getRight();
Font tickLabelFont = getTickLabelFont();
FontRenderContext frc = g2.getFontRenderContext();
LineMetrics lm = tickLabelFont.getLineMetrics("ABCxyz", frc);
if (isVerticalTickLabels()) {
// all tick labels have the same width (equal to the height of
// the font)...
result += lm.getHeight();
}
else {
// look at lower and upper bounds...
DateRange range = (DateRange) getRange();
Date lower = range.getLowerDate();
Date upper = range.getUpperDate();
String lowerStr, upperStr;
DateFormat formatter = getDateFormatOverride();
if (formatter != null) {
lowerStr = formatter.format(lower);
upperStr = formatter.format(upper);
}
else {
lowerStr = unit.dateToString(lower);
upperStr = unit.dateToString(upper);
}
FontMetrics fm = g2.getFontMetrics(tickLabelFont);
double w1 = fm.stringWidth(lowerStr);
double w2 = fm.stringWidth(upperStr);
result += Math.max(w1, w2);
}
return result;
}
/**
* Estimates the maximum width of the tick labels, assuming the specified
* tick unit is used.
* <P>
* Rather than computing the string bounds of every tick on the axis, we
* just look at two values: the lower bound and the upper bound for the
* axis. These two values will usually be representative.
*
* @param g2 the graphics device.
* @param unit the tick unit to use for calculation.
*
* @return The estimated maximum width of the tick labels.
*/
private double estimateMaximumTickLabelHeight(Graphics2D g2,
DateTickUnit unit) {
RectangleInsets tickLabelInsets = getTickLabelInsets();
double result = tickLabelInsets.getTop() + tickLabelInsets.getBottom();
Font tickLabelFont = getTickLabelFont();
FontRenderContext frc = g2.getFontRenderContext();
LineMetrics lm = tickLabelFont.getLineMetrics("ABCxyz", frc);
if (!isVerticalTickLabels()) {
// all tick labels have the same width (equal to the height of
// the font)...
result += lm.getHeight();
}
else {
// look at lower and upper bounds...
DateRange range = (DateRange) getRange();
Date lower = range.getLowerDate();
Date upper = range.getUpperDate();
String lowerStr, upperStr;
DateFormat formatter = getDateFormatOverride();
if (formatter != null) {
lowerStr = formatter.format(lower);
upperStr = formatter.format(upper);
}
else {
lowerStr = unit.dateToString(lower);
upperStr = unit.dateToString(upper);
}
FontMetrics fm = g2.getFontMetrics(tickLabelFont);
double w1 = fm.stringWidth(lowerStr);
double w2 = fm.stringWidth(upperStr);
result += Math.max(w1, w2);
}
return result;
}
/**
* Calculates the positions of the tick labels for the axis, storing the
* results in the tick label list (ready for drawing).
*
* @param g2 the graphics device.
* @param state the axis state.
* @param dataArea the area in which the plot should be drawn.
* @param edge the location of the axis.
*
* @return A list of ticks.
*/
@Override
public List<ValueTick> refreshTicks(Graphics2D g2, AxisState state,
Rectangle2D dataArea, RectangleEdge edge) {
List<ValueTick> result = null;
if (RectangleEdge.isTopOrBottom(edge)) {
result = refreshTicksHorizontal(g2, dataArea, edge);
}
else if (RectangleEdge.isLeftOrRight(edge)) {
result = refreshTicksVertical(g2, dataArea, edge);
}
return result;
}
/**
* Corrects the given tick date for the position setting.
*
* @param time the tick date/time.
* @param unit the tick unit.
* @param position the tick position.
*
* @return The adjusted time.
*/
private Date correctTickDateForPosition(Date time, DateTickUnit unit,
DateTickMarkPosition position) {
Date result = time;
if (unit.getUnitType().equals(DateTickUnitType.MONTH)) {
result = calculateDateForPosition(new Month(time, this.timeZone,
this.locale), position);
} else if (unit.getUnitType().equals(DateTickUnitType.YEAR)) {
result = calculateDateForPosition(new Year(time, this.timeZone,
this.locale), position);
}
return result;
}
/**
* Recalculates the ticks for the date axis.
*
* @param g2 the graphics device.
* @param dataArea the area in which the data is to be drawn.
* @param edge the location of the axis.
*
* @return A list of ticks.
*/
protected List<ValueTick> refreshTicksHorizontal(Graphics2D g2,
Rectangle2D dataArea, RectangleEdge edge) {
List<ValueTick> result = new java.util.ArrayList<ValueTick>();
Font tickLabelFont = getTickLabelFont();
g2.setFont(tickLabelFont);
if (isAutoTickUnitSelection()) {
selectAutoTickUnit(g2, dataArea, edge);
}
DateTickUnit unit = getTickUnit();
Date tickDate = calculateLowestVisibleTickValue(unit);
Date upperDate = getMaximumDate();
boolean hasRolled = false;
while (tickDate.before(upperDate)) {
// could add a flag to make the following correction optional...
if (!hasRolled) {
tickDate = correctTickDateForPosition(tickDate, unit,
this.tickMarkPosition);
}
long lowestTickTime = tickDate.getTime();
long distance = unit.addToDate(tickDate, this.timeZone).getTime()
- lowestTickTime;
int minorTickSpaces = getMinorTickCount();
if (minorTickSpaces <= 0) {
minorTickSpaces = unit.getMinorTickCount();
}
for (int minorTick = 1; minorTick < minorTickSpaces; minorTick++) {
long minorTickTime = lowestTickTime - distance
* minorTick / minorTickSpaces;
if (minorTickTime > 0 && getRange().contains(minorTickTime)
&& (!isHiddenValue(minorTickTime))) {
result.add(new DateTick(TickType.MINOR,
new Date(minorTickTime), "", TextAnchor.TOP_CENTER,
TextAnchor.CENTER, 0.0));
}
}
if (!isHiddenValue(tickDate.getTime())) {
// work out the value, label and position
String tickLabel;
DateFormat formatter = getDateFormatOverride();
if (formatter != null) {
tickLabel = formatter.format(tickDate);
}
else {
tickLabel = this.tickUnit.dateToString(tickDate);
}
TextAnchor anchor, rotationAnchor;
double angle = 0.0;
if (isVerticalTickLabels()) {
anchor = TextAnchor.CENTER_RIGHT;
rotationAnchor = TextAnchor.CENTER_RIGHT;
if (edge == RectangleEdge.TOP) {
angle = Math.PI / 2.0;
}
else {
angle = -Math.PI / 2.0;
}
}
else {
if (edge == RectangleEdge.TOP) {
anchor = TextAnchor.BOTTOM_CENTER;
rotationAnchor = TextAnchor.BOTTOM_CENTER;
}
else {
anchor = TextAnchor.TOP_CENTER;
rotationAnchor = TextAnchor.TOP_CENTER;
}
}
result.add(new DateTick(tickDate, tickLabel, anchor,
rotationAnchor, angle));
hasRolled = false;
long currentTickTime = tickDate.getTime();
tickDate = unit.addToDate(tickDate, this.timeZone);
long nextTickTime = tickDate.getTime();
for (int minorTick = 1; minorTick < minorTickSpaces;
minorTick++) {
long minorTickTime = currentTickTime
+ (nextTickTime - currentTickTime)
* minorTick / minorTickSpaces;
if (getRange().contains(minorTickTime)
&& (!isHiddenValue(minorTickTime))) {
result.add(new DateTick(TickType.MINOR,
new Date(minorTickTime), "",
TextAnchor.TOP_CENTER, TextAnchor.CENTER,
0.0));
}
}
}
else {
tickDate = unit.rollDate(tickDate, this.timeZone);
hasRolled = true;
continue;
}
}
return result;
}
/**
* Recalculates the ticks for the date axis.
*
* @param g2 the graphics device.
* @param dataArea the area in which the plot should be drawn.
* @param edge the location of the axis.
*
* @return A list of ticks.
*/
protected List<ValueTick> refreshTicksVertical(Graphics2D g2,
Rectangle2D dataArea, RectangleEdge edge) {
List<ValueTick> result = new java.util.ArrayList<ValueTick>();
Font tickLabelFont = getTickLabelFont();
g2.setFont(tickLabelFont);
if (isAutoTickUnitSelection()) {
selectAutoTickUnit(g2, dataArea, edge);
}
DateTickUnit unit = getTickUnit();
Date tickDate = calculateLowestVisibleTickValue(unit);
Date upperDate = getMaximumDate();
boolean hasRolled = false;
while (tickDate.before(upperDate)) {
// could add a flag to make the following correction optional...
if (!hasRolled) {
tickDate = correctTickDateForPosition(tickDate, unit,
this.tickMarkPosition);
}
long lowestTickTime = tickDate.getTime();
long distance = unit.addToDate(tickDate, this.timeZone).getTime()
- lowestTickTime;
int minorTickSpaces = getMinorTickCount();
if (minorTickSpaces <= 0) {
minorTickSpaces = unit.getMinorTickCount();
}
for (int minorTick = 1; minorTick < minorTickSpaces; minorTick++) {
long minorTickTime = lowestTickTime - distance
* minorTick / minorTickSpaces;
if (minorTickTime > 0 && getRange().contains(minorTickTime)
&& (!isHiddenValue(minorTickTime))) {
result.add(new DateTick(TickType.MINOR,
new Date(minorTickTime), "", TextAnchor.TOP_CENTER,
TextAnchor.CENTER, 0.0));
}
}
if (!isHiddenValue(tickDate.getTime())) {
// work out the value, label and position
String tickLabel;
DateFormat formatter = getDateFormatOverride();
if (formatter != null) {
tickLabel = formatter.format(tickDate);
}
else {
tickLabel = this.tickUnit.dateToString(tickDate);
}
TextAnchor anchor, rotationAnchor;
double angle = 0.0;
if (isVerticalTickLabels()) {
anchor = TextAnchor.BOTTOM_CENTER;
rotationAnchor = TextAnchor.BOTTOM_CENTER;
if (edge == RectangleEdge.LEFT) {
angle = -Math.PI / 2.0;
}
else {
angle = Math.PI / 2.0;
}
}
else {
if (edge == RectangleEdge.LEFT) {
anchor = TextAnchor.CENTER_RIGHT;
rotationAnchor = TextAnchor.CENTER_RIGHT;
}
else {
anchor = TextAnchor.CENTER_LEFT;
rotationAnchor = TextAnchor.CENTER_LEFT;
}
}
result.add(new DateTick(tickDate, tickLabel, anchor,
rotationAnchor, angle));
hasRolled = false;
long currentTickTime = tickDate.getTime();
tickDate = unit.addToDate(tickDate, this.timeZone);
long nextTickTime = tickDate.getTime();
for (int minorTick = 1; minorTick < minorTickSpaces;
minorTick++) {
long minorTickTime = currentTickTime
+ (nextTickTime - currentTickTime)
* minorTick / minorTickSpaces;
if (getRange().contains(minorTickTime)
&& (!isHiddenValue(minorTickTime))) {
result.add(new DateTick(TickType.MINOR,
new Date(minorTickTime), "",
TextAnchor.TOP_CENTER, TextAnchor.CENTER,
0.0));
}
}
}
else {
tickDate = unit.rollDate(tickDate, this.timeZone);
hasRolled = true;
}
}
return result;
}
/**
* Draws the axis on a Java 2D graphics device (such as the screen or a
* printer).
*
* @param g2 the graphics device (<code>null</code> not permitted).
* @param cursor the cursor location.
* @param plotArea the area within which the axes and data should be
* drawn (<code>null</code> not permitted).
* @param dataArea the area within which the data should be drawn
* (<code>null</code> not permitted).
* @param edge the location of the axis (<code>null</code> not permitted).
* @param plotState collects information about the plot
* (<code>null</code> permitted).
*
* @return The axis state (never <code>null</code>).
*/
@Override
public AxisState draw(Graphics2D g2, double cursor, Rectangle2D plotArea,
Rectangle2D dataArea, RectangleEdge edge,
PlotRenderingInfo plotState) {
// if the axis is not visible, don't draw it...
if (!isVisible()) {
AxisState state = new AxisState(cursor);
// even though the axis is not visible, we need to refresh ticks in
// case the grid is being drawn...
List<ValueTick> ticks = refreshTicks(g2, state, dataArea, edge);
state.setTicks(ticks);
return state;
}
// draw the tick marks and labels...
AxisState state = drawTickMarksAndLabels(g2, cursor, plotArea,
dataArea, edge);
// draw the axis label (note that 'state' is passed in *and*
// returned)...
state = drawLabel(getLabel(), g2, plotArea, dataArea, edge, state);
createAndAddEntity(cursor, state, dataArea, edge, plotState);
return state;
}
/**
* Zooms in on the current range (zoom-in stops once the axis length
* reaches the equivalent of one millisecond).
*
* @param lowerPercent the new lower bound.
* @param upperPercent the new upper bound.
*/
@Override
public void zoomRange(double lowerPercent, double upperPercent) {
double start = this.timeline.toTimelineValue(
(long) getRange().getLowerBound());
double end = this.timeline.toTimelineValue(
(long) getRange().getUpperBound());
double length = end - start;
Range adjusted;
long adjStart, adjEnd;
if (isInverted()) {
adjStart = (long) (start + (length * (1 - upperPercent)));
adjEnd = (long) (start + (length * (1 - lowerPercent)));
}
else {
adjStart = (long) (start + length * lowerPercent);
adjEnd = (long) (start + length * upperPercent);
}
// when zooming to sub-millisecond ranges, it can be the case that
// adjEnd == adjStart...and we can't have an axis with zero length
// so we apply this instead:
if (adjEnd <= adjStart) {
adjEnd = adjStart + 1L;
}
adjusted = new DateRange(this.timeline.toMillisecond(adjStart),
this.timeline.toMillisecond(adjEnd));
setRange(adjusted);
}
/**
* Tests this axis 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 DateAxis)) {
return false;
}
DateAxis that = (DateAxis) obj;
if (!ObjectUtilities.equal(this.tickUnit, that.tickUnit)) {
return false;
}
if (!ObjectUtilities.equal(this.dateFormatOverride,
that.dateFormatOverride)) {
return false;
}
if (!ObjectUtilities.equal(this.tickMarkPosition,
that.tickMarkPosition)) {
return false;
}
if (!ObjectUtilities.equal(this.timeline, that.timeline)) {
return false;
}
return super.equals(obj);
}
@Override
public int hashCode() {
return super.hashCode();
}
/**
* Returns a clone of the object.
*
* @return A clone.
*
* @throws CloneNotSupportedException if some component of the axis does
* not support cloning.
*/
@Override
public Object clone() throws CloneNotSupportedException {
DateAxis clone = (DateAxis) super.clone();
// 'dateTickUnit' is immutable : no need to clone
if (this.dateFormatOverride != null) {
clone.dateFormatOverride
= (DateFormat) this.dateFormatOverride.clone();
}
// 'tickMarkPosition' is immutable : no need to clone
return clone;
}
}
| 70,313 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
AxisCollection.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/axis/AxisCollection.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.]
*
* -------------------
* AxisCollection.java
* -------------------
* (C) Copyright 2003-2012, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 03-Nov-2003 : Added standard header (DG);
* 17-Jun-2012 : Removed JCommon dependencies (DG);
*
*/
package org.jfree.chart.axis;
import java.util.List;
import org.jfree.chart.ui.RectangleEdge;
/**
* A collection of axes that have been assigned to the TOP, BOTTOM, LEFT or
* RIGHT of a chart. This class is used internally by JFreeChart, you won't
* normally need to use it yourself.
*/
public class AxisCollection {
/** The axes that need to be drawn at the top of the plot area. */
private List<Axis> axesAtTop;
/** The axes that need to be drawn at the bottom of the plot area. */
private List<Axis> axesAtBottom;
/** The axes that need to be drawn at the left of the plot area. */
private List<Axis> axesAtLeft;
/** The axes that need to be drawn at the right of the plot area. */
private List<Axis> axesAtRight;
/**
* Creates a new empty collection.
*/
public AxisCollection() {
this.axesAtTop = new java.util.ArrayList<Axis>();
this.axesAtBottom = new java.util.ArrayList<Axis>();
this.axesAtLeft = new java.util.ArrayList<Axis>();
this.axesAtRight = new java.util.ArrayList<Axis>();
}
/**
* Returns a list of the axes (if any) that need to be drawn at the top of
* the plot area.
*
* @return A list of axes.
*/
public List<Axis> getAxesAtTop() {
return this.axesAtTop;
}
/**
* Returns a list of the axes (if any) that need to be drawn at the bottom
* of the plot area.
*
* @return A list of axes.
*/
public List<Axis> getAxesAtBottom() {
return this.axesAtBottom;
}
/**
* Returns a list of the axes (if any) that need to be drawn at the left
* of the plot area.
*
* @return A list of axes.
*/
public List<Axis> getAxesAtLeft() {
return this.axesAtLeft;
}
/**
* Returns a list of the axes (if any) that need to be drawn at the right
* of the plot area.
*
* @return A list of axes.
*/
public List<Axis> getAxesAtRight() {
return this.axesAtRight;
}
/**
* Adds an axis to the collection.
*
* @param axis the axis (<code>null</code> not permitted).
* @param edge the edge of the plot that the axis should be drawn on
* (<code>null</code> not permitted).
*/
public void add(Axis axis, RectangleEdge edge) {
if (axis == null) {
throw new IllegalArgumentException("Null 'axis' argument.");
}
if (edge == null) {
throw new IllegalArgumentException("Null 'edge' argument.");
}
if (edge == RectangleEdge.TOP) {
this.axesAtTop.add(axis);
}
else if (edge == RectangleEdge.BOTTOM) {
this.axesAtBottom.add(axis);
}
else if (edge == RectangleEdge.LEFT) {
this.axesAtLeft.add(axis);
}
else if (edge == RectangleEdge.RIGHT) {
this.axesAtRight.add(axis);
}
}
}
| 4,520 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
CategoryAxis.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/axis/CategoryAxis.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.]
*
* -----------------
* CategoryAxis.java
* -----------------
* (C) Copyright 2000-2013, by Object Refinery Limited and Contributors.
*
* Original Author: David Gilbert;
* Contributor(s): Pady Srinivasan (patch 1217634);
* Peter Kolb (patches 2497611 and 2603321);
*
* Changes
* -------
* 21-Aug-2001 : Added standard header. Fixed DOS encoding problem (DG);
* 18-Sep-2001 : Updated header (DG);
* 04-Dec-2001 : Changed constructors to protected, and tidied up default
* values (DG);
* 19-Apr-2002 : Updated import statements (DG);
* 05-Sep-2002 : Updated constructor for changes in Axis class (DG);
* 06-Nov-2002 : Moved margins from the CategoryPlot class (DG);
* 08-Nov-2002 : Moved to new package com.jrefinery.chart.axis (DG);
* 22-Jan-2002 : Removed monolithic constructor (DG);
* 26-Mar-2003 : Implemented Serializable (DG);
* 09-May-2003 : Merged HorizontalCategoryAxis and VerticalCategoryAxis into
* this class (DG);
* 13-Aug-2003 : Implemented Cloneable (DG);
* 29-Oct-2003 : Added workaround for font alignment in PDF output (DG);
* 05-Nov-2003 : Fixed serialization bug (DG);
* 26-Nov-2003 : Added category label offset (DG);
* 06-Jan-2004 : Moved axis line attributes to Axis class, rationalised
* category label position attributes (DG);
* 07-Jan-2004 : Added new implementation for linewrapping of category
* labels (DG);
* 17-Feb-2004 : Moved deprecated code to bottom of source file (DG);
* 10-Mar-2004 : Changed Dimension --> Dimension2D in text classes (DG);
* 16-Mar-2004 : Added support for tooltips on category labels (DG);
* 01-Apr-2004 : Changed java.awt.geom.Dimension2D to org.jfree.ui.Size2D
* because of JDK bug 4976448 which persists on JDK 1.3.1 (DG);
* 03-Sep-2004 : Added 'maxCategoryLabelLines' attribute (DG);
* 04-Oct-2004 : Renamed ShapeUtils --> ShapeUtilities (DG);
* 11-Jan-2005 : Removed deprecated methods in preparation for 1.0.0
* release (DG);
* 21-Jan-2005 : Modified return type for RectangleAnchor.coordinates()
* method (DG);
* 21-Apr-2005 : Replaced Insets with RectangleInsets (DG);
* 26-Apr-2005 : Removed LOGGER (DG);
* 08-Jun-2005 : Fixed bug in axis layout (DG);
* 22-Nov-2005 : Added a method to access the tool tip text for a category
* label (DG);
* 23-Nov-2005 : Added per-category font and paint options - see patch
* 1217634 (DG);
* ------------- JFreeChart 1.0.x ---------------------------------------------
* 11-Jan-2006 : Fixed null pointer exception in drawCategoryLabels - see bug
* 1403043 (DG);
* 18-Aug-2006 : Fix for bug drawing category labels, thanks to Adriaan
* Joubert (1277726) (DG);
* 02-Oct-2006 : Updated category label entity (DG);
* 30-Oct-2006 : Updated refreshTicks() method to account for possibility of
* multiple domain axes (DG);
* 07-Mar-2007 : Fixed bug in axis label positioning (DG);
* 27-Sep-2007 : Added getCategorySeriesMiddle() method (DG);
* 21-Nov-2007 : Fixed performance bug noted by FindBugs in the
* equalPaintMaps() method (DG);
* 23-Apr-2008 : Fixed bug 1942059, bad use of insets in
* calculateTextBlockWidth() (DG);
* 26-Jun-2008 : Added new getCategoryMiddle() method (DG);
* 27-Oct-2008 : Set font on Graphics2D when creating category labels (DG);
* 14-Jan-2009 : Added new variant of getCategorySeriesMiddle() to make it
* simpler for renderers with hidden series (PK);
* 19-Mar-2009 : Added entity support - see patch 2603321 by Peter Kolb (DG);
* 16-Apr-2009 : Added tick mark drawing (DG);
* 29-Jun-2009 : Fixed bug where axis entity is hiding label entities (DG);
* 16-Jun-2012 : Removed JCommon dependencies, deprecated method (DG);
*
*/
package org.jfree.chart.axis;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.Shape;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.text.AttributedString;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.jfree.chart.ui.RectangleAnchor;
import org.jfree.chart.ui.RectangleEdge;
import org.jfree.chart.ui.RectangleInsets;
import org.jfree.chart.ui.Size2D;
import org.jfree.chart.util.ObjectUtilities;
import org.jfree.chart.util.PaintUtilities;
import org.jfree.chart.util.ShapeUtilities;
import org.jfree.chart.entity.CategoryLabelEntity;
import org.jfree.chart.entity.EntityCollection;
import org.jfree.chart.event.AxisChangeEvent;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.Plot;
import org.jfree.chart.plot.PlotRenderingInfo;
import org.jfree.chart.text.G2TextMeasurer;
import org.jfree.chart.text.TextBlock;
import org.jfree.chart.text.TextUtilities;
import org.jfree.chart.util.ParamChecks;
import org.jfree.chart.util.SerialUtilities;
import org.jfree.data.category.CategoryDataset;
/**
* An axis that displays categories. This is used with the {@link CategoryPlot}
* class.
*/
public class CategoryAxis extends Axis implements Cloneable, Serializable {
/** For serialization. */
private static final long serialVersionUID = 5886554608114265863L;
/**
* The default margin for the axis (used for both lower and upper margins).
*/
public static final double DEFAULT_AXIS_MARGIN = 0.05;
/**
* The default margin between categories (a percentage of the overall axis
* length).
*/
public static final double DEFAULT_CATEGORY_MARGIN = 0.20;
/** The amount of space reserved at the start of the axis. */
private double lowerMargin;
/** The amount of space reserved at the end of the axis. */
private double upperMargin;
/** The amount of space reserved between categories. */
private double categoryMargin;
/** The maximum number of lines for category labels. */
private int maximumCategoryLabelLines;
/**
* A ratio that is multiplied by the width of one category to determine the
* maximum label width.
*/
private float maximumCategoryLabelWidthRatio;
/** The category label offset. */
private int categoryLabelPositionOffset;
/**
* A structure defining the category label positions for each axis
* location.
*/
private CategoryLabelPositions categoryLabelPositions;
/** Storage for tick label font overrides (if any). */
private Map<Comparable, Font> tickLabelFontMap;
/** Storage for tick label paint overrides (if any). */
private transient Map<Comparable, Paint> tickLabelPaintMap;
/** Storage for the category label tooltips (if any). */
private Map<Comparable, String> categoryLabelToolTips;
/** Storage for the category label URLs (if any). */
private Map<Comparable, String> categoryLabelURLs;
/**
* Creates a new category axis with no label.
*/
public CategoryAxis() {
this(null);
}
/**
* Constructs a category axis, using default values where necessary.
*
* @param label the axis label (<code>null</code> permitted).
*/
public CategoryAxis(String label) {
super(label);
this.lowerMargin = DEFAULT_AXIS_MARGIN;
this.upperMargin = DEFAULT_AXIS_MARGIN;
this.categoryMargin = DEFAULT_CATEGORY_MARGIN;
this.maximumCategoryLabelLines = 1;
this.maximumCategoryLabelWidthRatio = 0.0f;
this.categoryLabelPositionOffset = 4;
this.categoryLabelPositions = CategoryLabelPositions.STANDARD;
this.tickLabelFontMap = new HashMap<Comparable, Font>();
this.tickLabelPaintMap = new HashMap<Comparable, Paint>();
this.categoryLabelToolTips = new HashMap<Comparable, String>();
this.categoryLabelURLs = new HashMap<Comparable, String>();
}
/**
* Returns the lower margin for the axis.
*
* @return The margin.
*
* @see #getUpperMargin()
* @see #setLowerMargin(double)
*/
public double getLowerMargin() {
return this.lowerMargin;
}
/**
* Sets the lower margin for the axis and sends an {@link AxisChangeEvent}
* to all registered listeners.
*
* @param margin the margin as a percentage of the axis length (for
* example, 0.05 is five percent).
*
* @see #getLowerMargin()
*/
public void setLowerMargin(double margin) {
this.lowerMargin = margin;
fireChangeEvent();
}
/**
* Returns the upper margin for the axis.
*
* @return The margin.
*
* @see #getLowerMargin()
* @see #setUpperMargin(double)
*/
public double getUpperMargin() {
return this.upperMargin;
}
/**
* Sets the upper margin for the axis and sends an {@link AxisChangeEvent}
* to all registered listeners.
*
* @param margin the margin as a percentage of the axis length (for
* example, 0.05 is five percent).
*
* @see #getUpperMargin()
*/
public void setUpperMargin(double margin) {
this.upperMargin = margin;
fireChangeEvent();
}
/**
* Returns the category margin.
*
* @return The margin.
*
* @see #setCategoryMargin(double)
*/
public double getCategoryMargin() {
return this.categoryMargin;
}
/**
* Sets the category margin and sends an {@link AxisChangeEvent} to all
* registered listeners. The overall category margin is distributed over
* N-1 gaps, where N is the number of categories on the axis.
*
* @param margin the margin as a percentage of the axis length (for
* example, 0.05 is five percent).
*
* @see #getCategoryMargin()
*/
public void setCategoryMargin(double margin) {
this.categoryMargin = margin;
fireChangeEvent();
}
/**
* Returns the maximum number of lines to use for each category label.
*
* @return The maximum number of lines.
*
* @see #setMaximumCategoryLabelLines(int)
*/
public int getMaximumCategoryLabelLines() {
return this.maximumCategoryLabelLines;
}
/**
* Sets the maximum number of lines to use for each category label and
* sends an {@link AxisChangeEvent} to all registered listeners.
*
* @param lines the maximum number of lines.
*
* @see #getMaximumCategoryLabelLines()
*/
public void setMaximumCategoryLabelLines(int lines) {
this.maximumCategoryLabelLines = lines;
fireChangeEvent();
}
/**
* Returns the category label width ratio.
*
* @return The ratio.
*
* @see #setMaximumCategoryLabelWidthRatio(float)
*/
public float getMaximumCategoryLabelWidthRatio() {
return this.maximumCategoryLabelWidthRatio;
}
/**
* Sets the maximum category label width ratio and sends an
* {@link AxisChangeEvent} to all registered listeners.
*
* @param ratio the ratio.
*
* @see #getMaximumCategoryLabelWidthRatio()
*/
public void setMaximumCategoryLabelWidthRatio(float ratio) {
this.maximumCategoryLabelWidthRatio = ratio;
fireChangeEvent();
}
/**
* Returns the offset between the axis and the category labels (before
* label positioning is taken into account).
*
* @return The offset (in Java2D units).
*
* @see #setCategoryLabelPositionOffset(int)
*/
public int getCategoryLabelPositionOffset() {
return this.categoryLabelPositionOffset;
}
/**
* Sets the offset between the axis and the category labels (before label
* positioning is taken into account) and sends a change event to all
* registered listeners.
*
* @param offset the offset (in Java2D units).
*
* @see #getCategoryLabelPositionOffset()
*/
public void setCategoryLabelPositionOffset(int offset) {
this.categoryLabelPositionOffset = offset;
fireChangeEvent();
}
/**
* Returns the category label position specification (this contains label
* positioning info for all four possible axis locations).
*
* @return The positions (never <code>null</code>).
*
* @see #setCategoryLabelPositions(CategoryLabelPositions)
*/
public CategoryLabelPositions getCategoryLabelPositions() {
return this.categoryLabelPositions;
}
/**
* Sets the category label position specification for the axis and sends an
* {@link AxisChangeEvent} to all registered listeners.
*
* @param positions the positions (<code>null</code> not permitted).
*
* @see #getCategoryLabelPositions()
*/
public void setCategoryLabelPositions(CategoryLabelPositions positions) {
ParamChecks.nullNotPermitted(positions, "positions");
this.categoryLabelPositions = positions;
fireChangeEvent();
}
/**
* Returns the font for the tick label for the given category.
*
* @param category the category (<code>null</code> not permitted).
*
* @return The font (never <code>null</code>).
*
* @see #setTickLabelFont(Comparable, Font)
*/
public Font getTickLabelFont(Comparable category) {
ParamChecks.nullNotPermitted(category, "category");
Font result = this.tickLabelFontMap.get(category);
// if there is no specific font, use the general one...
if (result == null) {
result = getTickLabelFont();
}
return result;
}
/**
* Sets the font for the tick label for the specified category and sends
* an {@link AxisChangeEvent} to all registered listeners.
*
* @param category the category (<code>null</code> not permitted).
* @param font the font (<code>null</code> permitted).
*
* @see #getTickLabelFont(Comparable)
*/
public void setTickLabelFont(Comparable category, Font font) {
ParamChecks.nullNotPermitted(category, "category");
if (font == null) {
this.tickLabelFontMap.remove(category);
}
else {
this.tickLabelFontMap.put(category, font);
}
fireChangeEvent();
}
/**
* Returns the paint for the tick label for the given category.
*
* @param category the category (<code>null</code> not permitted).
*
* @return The paint (never <code>null</code>).
*
* @see #setTickLabelPaint(Paint)
*/
public Paint getTickLabelPaint(Comparable category) {
ParamChecks.nullNotPermitted(category, "category");
Paint result = this.tickLabelPaintMap.get(category);
// if there is no specific paint, use the general one...
if (result == null) {
result = getTickLabelPaint();
}
return result;
}
/**
* Sets the paint for the tick label for the specified category and sends
* an {@link AxisChangeEvent} to all registered listeners.
*
* @param category the category (<code>null</code> not permitted).
* @param paint the paint (<code>null</code> permitted).
*
* @see #getTickLabelPaint(Comparable)
*/
public void setTickLabelPaint(Comparable category, Paint paint) {
ParamChecks.nullNotPermitted(category, "category");
if (paint == null) {
this.tickLabelPaintMap.remove(category);
}
else {
this.tickLabelPaintMap.put(category, paint);
}
fireChangeEvent();
}
/**
* Adds a tooltip to the specified category and sends an
* {@link AxisChangeEvent} to all registered listeners.
*
* @param category the category (<code>null</code> not permitted).
* @param tooltip the tooltip text (<code>null</code> permitted).
*
* @see #removeCategoryLabelToolTip(Comparable)
*/
public void addCategoryLabelToolTip(Comparable category, String tooltip) {
ParamChecks.nullNotPermitted(category, "category");
this.categoryLabelToolTips.put(category, tooltip);
fireChangeEvent();
}
/**
* Returns the tool tip text for the label belonging to the specified
* category.
*
* @param category the category (<code>null</code> not permitted).
*
* @return The tool tip text (possibly <code>null</code>).
*
* @see #addCategoryLabelToolTip(Comparable, String)
* @see #removeCategoryLabelToolTip(Comparable)
*/
public String getCategoryLabelToolTip(Comparable category) {
ParamChecks.nullNotPermitted(category, "category");
return this.categoryLabelToolTips.get(category);
}
/**
* Removes the tooltip for the specified category and, if there was a value
* associated with that category, sends an {@link AxisChangeEvent} to all
* registered listeners.
*
* @param category the category (<code>null</code> not permitted).
*
* @see #addCategoryLabelToolTip(Comparable, String)
* @see #clearCategoryLabelToolTips()
*/
public void removeCategoryLabelToolTip(Comparable category) {
ParamChecks.nullNotPermitted(category, "category");
if (this.categoryLabelToolTips.remove(category) != null) {
fireChangeEvent();
}
}
/**
* Clears the category label tooltips and sends an {@link AxisChangeEvent}
* to all registered listeners.
*
* @see #addCategoryLabelToolTip(Comparable, String)
* @see #removeCategoryLabelToolTip(Comparable)
*/
public void clearCategoryLabelToolTips() {
this.categoryLabelToolTips.clear();
fireChangeEvent();
}
/**
* Adds a URL (to be used in image maps) to the specified category and
* sends an {@link AxisChangeEvent} to all registered listeners.
*
* @param category the category (<code>null</code> not permitted).
* @param url the URL text (<code>null</code> permitted).
*
* @see #removeCategoryLabelURL(Comparable)
*
* @since 1.0.16
*/
public void addCategoryLabelURL(Comparable category, String url) {
ParamChecks.nullNotPermitted(category, "category");
this.categoryLabelURLs.put(category, url);
fireChangeEvent();
}
/**
* Returns the URL for the label belonging to the specified category.
*
* @param category the category (<code>null</code> not permitted).
*
* @return The URL text (possibly <code>null</code>).
*
* @see #addCategoryLabelURL(Comparable, String)
* @see #removeCategoryLabelURL(Comparable)
*
* @since 1.0.16
*/
public String getCategoryLabelURL(Comparable category) {
ParamChecks.nullNotPermitted(category, "category");
return this.categoryLabelURLs.get(category);
}
/**
* Removes the URL for the specified category and, if there was a URL
* associated with that category, sends an {@link AxisChangeEvent} to all
* registered listeners.
*
* @param category the category (<code>null</code> not permitted).
*
* @see #addCategoryLabelURL(Comparable, String)
* @see #clearCategoryLabelURLs()
*
* @since 1.0.16
*/
public void removeCategoryLabelURL(Comparable category) {
ParamChecks.nullNotPermitted(category, "category");
if (this.categoryLabelURLs.remove(category) != null) {
fireChangeEvent();
}
}
/**
* Clears the category label URLs and sends an {@link AxisChangeEvent}
* to all registered listeners.
*
* @see #addCategoryLabelURL(Comparable, String)
* @see #removeCategoryLabelURL(Comparable)
*
* @since 1.0.16
*/
public void clearCategoryLabelURLs() {
this.categoryLabelURLs.clear();
fireChangeEvent();
}
/**
* Returns the Java 2D coordinate for a category.
*
* @param anchor the anchor point.
* @param category the category index.
* @param categoryCount the category count.
* @param area the data area.
* @param edge the location of the axis.
*
* @return The coordinate.
*/
public double getCategoryJava2DCoordinate(CategoryAnchor anchor,
int category, int categoryCount, Rectangle2D area,
RectangleEdge edge) {
double result = 0.0;
if (anchor == CategoryAnchor.START) {
result = getCategoryStart(category, categoryCount, area, edge);
}
else if (anchor == CategoryAnchor.MIDDLE) {
result = getCategoryMiddle(category, categoryCount, area, edge);
}
else if (anchor == CategoryAnchor.END) {
result = getCategoryEnd(category, categoryCount, area, edge);
}
return result;
}
/**
* Returns the starting coordinate for the specified category.
*
* @param category the category.
* @param categoryCount the number of categories.
* @param area the data area.
* @param edge the axis location.
*
* @return The coordinate.
*
* @see #getCategoryMiddle(int, int, Rectangle2D, RectangleEdge)
* @see #getCategoryEnd(int, int, Rectangle2D, RectangleEdge)
*/
public double getCategoryStart(int category, int categoryCount,
Rectangle2D area, RectangleEdge edge) {
double result = 0.0;
if ((edge == RectangleEdge.TOP) || (edge == RectangleEdge.BOTTOM)) {
result = area.getX() + area.getWidth() * getLowerMargin();
}
else if ((edge == RectangleEdge.LEFT)
|| (edge == RectangleEdge.RIGHT)) {
result = area.getMinY() + area.getHeight() * getLowerMargin();
}
double categorySize = calculateCategorySize(categoryCount, area, edge);
double categoryGapWidth = calculateCategoryGapSize(categoryCount, area,
edge);
result = result + category * (categorySize + categoryGapWidth);
return result;
}
/**
* Returns the middle coordinate for the specified category.
*
* @param category the category.
* @param categoryCount the number of categories.
* @param area the data area.
* @param edge the axis location.
*
* @return The coordinate.
*
* @see #getCategoryStart(int, int, Rectangle2D, RectangleEdge)
* @see #getCategoryEnd(int, int, Rectangle2D, RectangleEdge)
*/
public double getCategoryMiddle(int category, int categoryCount,
Rectangle2D area, RectangleEdge edge) {
if (category < 0 || category >= categoryCount) {
throw new IllegalArgumentException("Invalid category index: "
+ category);
}
return getCategoryStart(category, categoryCount, area, edge)
+ calculateCategorySize(categoryCount, area, edge) / 2;
}
/**
* Returns the end coordinate for the specified category.
*
* @param category the category.
* @param categoryCount the number of categories.
* @param area the data area.
* @param edge the axis location.
*
* @return The coordinate.
*
* @see #getCategoryStart(int, int, Rectangle2D, RectangleEdge)
* @see #getCategoryMiddle(int, int, Rectangle2D, RectangleEdge)
*/
public double getCategoryEnd(int category, int categoryCount,
Rectangle2D area, RectangleEdge edge) {
return getCategoryStart(category, categoryCount, area, edge)
+ calculateCategorySize(categoryCount, area, edge);
}
/**
* A convenience method that returns the axis coordinate for the centre of
* a category.
*
* @param category the category key (<code>null</code> not permitted).
* @param categories the categories (<code>null</code> not permitted).
* @param area the data area (<code>null</code> not permitted).
* @param edge the edge along which the axis lies (<code>null</code> not
* permitted).
*
* @return The centre coordinate.
*
* @since 1.0.11
*
* @see #getCategorySeriesMiddle(Comparable, Comparable, CategoryDataset,
* double, Rectangle2D, RectangleEdge)
*/
public double getCategoryMiddle(Comparable category,
List<Comparable> categories, Rectangle2D area, RectangleEdge edge) {
ParamChecks.nullNotPermitted(categories, "categories");
int categoryIndex = categories.indexOf(category);
int categoryCount = categories.size();
return getCategoryMiddle(categoryIndex, categoryCount, area, edge);
}
/**
* Returns the middle coordinate (in Java2D space) for a series within a
* category.
*
* @param category the category (<code>null</code> not permitted).
* @param seriesKey the series key (<code>null</code> not permitted).
* @param dataset the dataset (<code>null</code> not permitted).
* @param itemMargin the item margin (0.0 <= itemMargin < 1.0);
* @param area the area (<code>null</code> not permitted).
* @param edge the edge (<code>null</code> not permitted).
*
* @return The coordinate in Java2D space.
*
* @since 1.0.7
*/
public double getCategorySeriesMiddle(Comparable category,
Comparable seriesKey, CategoryDataset dataset, double itemMargin,
Rectangle2D area, RectangleEdge edge) {
int categoryIndex = dataset.getColumnIndex(category);
int categoryCount = dataset.getColumnCount();
int seriesIndex = dataset.getRowIndex(seriesKey);
int seriesCount = dataset.getRowCount();
double start = getCategoryStart(categoryIndex, categoryCount, area,
edge);
double end = getCategoryEnd(categoryIndex, categoryCount, area, edge);
double width = end - start;
if (seriesCount == 1) {
return start + width / 2.0;
}
double gap = (width * itemMargin) / (seriesCount - 1);
double ww = (width * (1 - itemMargin)) / seriesCount;
return start + (seriesIndex * (ww + gap)) + ww / 2.0;
}
/**
* Returns the middle coordinate (in Java2D space) for a series within a
* category.
*
* @param categoryIndex the category index.
* @param categoryCount the category count.
* @param seriesIndex the series index.
* @param seriesCount the series count.
* @param itemMargin the item margin (0.0 <= itemMargin < 1.0);
* @param area the area (<code>null</code> not permitted).
* @param edge the edge (<code>null</code> not permitted).
*
* @return The coordinate in Java2D space.
*
* @since 1.0.13
*/
public double getCategorySeriesMiddle(int categoryIndex, int categoryCount,
int seriesIndex, int seriesCount, double itemMargin,
Rectangle2D area, RectangleEdge edge) {
double start = getCategoryStart(categoryIndex, categoryCount, area,
edge);
double end = getCategoryEnd(categoryIndex, categoryCount, area, edge);
double width = end - start;
if (seriesCount == 1) {
return start + width / 2.0;
}
double gap = (width * itemMargin) / (seriesCount - 1);
double ww = (width * (1 - itemMargin)) / seriesCount;
return start + (seriesIndex * (ww + gap)) + ww / 2.0;
}
/**
* Calculates the size (width or height, depending on the location of the
* axis) of a category.
*
* @param categoryCount the number of categories.
* @param area the area within which the categories will be drawn.
* @param edge the axis location.
*
* @return The category size.
*/
protected double calculateCategorySize(int categoryCount, Rectangle2D area,
RectangleEdge edge) {
double result;
double available = 0.0;
if ((edge == RectangleEdge.TOP) || (edge == RectangleEdge.BOTTOM)) {
available = area.getWidth();
}
else if ((edge == RectangleEdge.LEFT)
|| (edge == RectangleEdge.RIGHT)) {
available = area.getHeight();
}
if (categoryCount > 1) {
result = available * (1 - getLowerMargin() - getUpperMargin()
- getCategoryMargin());
result = result / categoryCount;
}
else {
result = available * (1 - getLowerMargin() - getUpperMargin());
}
return result;
}
/**
* Calculates the size (width or height, depending on the location of the
* axis) of a category gap.
*
* @param categoryCount the number of categories.
* @param area the area within which the categories will be drawn.
* @param edge the axis location.
*
* @return The category gap width.
*/
protected double calculateCategoryGapSize(int categoryCount,
Rectangle2D area, RectangleEdge edge) {
double result = 0.0;
double available = 0.0;
if ((edge == RectangleEdge.TOP) || (edge == RectangleEdge.BOTTOM)) {
available = area.getWidth();
}
else if ((edge == RectangleEdge.LEFT)
|| (edge == RectangleEdge.RIGHT)) {
available = area.getHeight();
}
if (categoryCount > 1) {
result = available * getCategoryMargin() / (categoryCount - 1);
}
return result;
}
/**
* Estimates the space required for the axis, given a specific drawing area.
*
* @param g2 the graphics device (used to obtain font information).
* @param plot the plot that the axis belongs to.
* @param plotArea the area within which the axis should be drawn.
* @param edge the axis location (top or bottom).
* @param space the space already reserved.
*
* @return The space required to draw the axis.
*/
@Override
public AxisSpace reserveSpace(Graphics2D g2, Plot plot,
Rectangle2D plotArea, RectangleEdge edge, AxisSpace space) {
// create a new space object if one wasn't supplied...
if (space == null) {
space = new AxisSpace();
}
// if the axis is not visible, no additional space is required...
if (!isVisible()) {
return space;
}
// calculate the max size of the tick labels (if visible)...
double tickLabelHeight = 0.0;
double tickLabelWidth = 0.0;
if (isTickLabelsVisible()) {
g2.setFont(getTickLabelFont());
AxisState state = new AxisState();
// we call refresh ticks just to get the maximum width or height
refreshTicks(g2, state, plotArea, edge);
if (edge == RectangleEdge.TOP) {
tickLabelHeight = state.getMax();
}
else if (edge == RectangleEdge.BOTTOM) {
tickLabelHeight = state.getMax();
}
else if (edge == RectangleEdge.LEFT) {
tickLabelWidth = state.getMax();
}
else if (edge == RectangleEdge.RIGHT) {
tickLabelWidth = state.getMax();
}
}
// get the axis label size and update the space object...
Rectangle2D labelEnclosure = getLabelEnclosure(g2, edge);
double labelHeight, labelWidth;
if (RectangleEdge.isTopOrBottom(edge)) {
labelHeight = labelEnclosure.getHeight();
space.add(labelHeight + tickLabelHeight
+ this.categoryLabelPositionOffset, edge);
}
else if (RectangleEdge.isLeftOrRight(edge)) {
labelWidth = labelEnclosure.getWidth();
space.add(labelWidth + tickLabelWidth
+ this.categoryLabelPositionOffset, edge);
}
return space;
}
/**
* Configures the axis against the current plot.
*/
@Override
public void configure() {
// nothing required
}
/**
* Draws the axis on a Java 2D graphics device (such as the screen or a
* printer).
*
* @param g2 the graphics device (<code>null</code> not permitted).
* @param cursor the cursor location.
* @param plotArea the area within which the axis should be drawn
* (<code>null</code> not permitted).
* @param dataArea the area within which the plot is being drawn
* (<code>null</code> not permitted).
* @param edge the location of the axis (<code>null</code> not permitted).
* @param plotState collects information about the plot
* (<code>null</code> permitted).
*
* @return The axis state (never <code>null</code>).
*/
@Override
public AxisState draw(Graphics2D g2, double cursor, Rectangle2D plotArea,
Rectangle2D dataArea, RectangleEdge edge,
PlotRenderingInfo plotState) {
// if the axis is not visible, don't draw it...
if (!isVisible()) {
return new AxisState(cursor);
}
if (isAxisLineVisible()) {
drawAxisLine(g2, cursor, dataArea, edge);
}
AxisState state = new AxisState(cursor);
if (isTickMarksVisible()) {
drawTickMarks(g2, cursor, dataArea, edge, state);
}
createAndAddEntity(cursor, state, dataArea, edge, plotState);
// draw the category labels and axis label
state = drawCategoryLabels(g2, plotArea, dataArea, edge, state,
plotState);
state = drawLabel(getLabel(), g2, plotArea, dataArea, edge, state);
return state;
}
/**
* Draws the category labels and returns the updated axis state.
*
* @param g2 the graphics device (<code>null</code> not permitted).
* @param plotArea the plot area (<code>null</code> not permitted).
* @param dataArea the area inside the axes (<code>null</code> not
* permitted).
* @param edge the axis location (<code>null</code> not permitted).
* @param state the axis state (<code>null</code> not permitted).
* @param plotState collects information about the plot (<code>null</code>
* permitted).
*
* @return The updated axis state (never <code>null</code>).
*/
protected AxisState drawCategoryLabels(Graphics2D g2, Rectangle2D plotArea,
Rectangle2D dataArea, RectangleEdge edge, AxisState state,
PlotRenderingInfo plotState) {
ParamChecks.nullNotPermitted(state, "state");
if (!isTickLabelsVisible()) {
return state;
}
List<CategoryTick> ticks = refreshTicks(g2, state, plotArea, edge);
//state.setTicks(ticks); //FIXME MMC had to remove this as the types don't match
int categoryIndex = 0;
for (CategoryTick tick : ticks) {
g2.setFont(getTickLabelFont(tick.getCategory()));
g2.setPaint(getTickLabelPaint(tick.getCategory()));
CategoryLabelPosition position
= this.categoryLabelPositions.getLabelPosition(edge);
double x0 = 0.0;
double x1 = 0.0;
double y0 = 0.0;
double y1 = 0.0;
if (edge == RectangleEdge.TOP) {
x0 = getCategoryStart(categoryIndex, ticks.size(), dataArea,
edge);
x1 = getCategoryEnd(categoryIndex, ticks.size(), dataArea,
edge);
y1 = state.getCursor() - this.categoryLabelPositionOffset;
y0 = y1 - state.getMax();
} else if (edge == RectangleEdge.BOTTOM) {
x0 = getCategoryStart(categoryIndex, ticks.size(), dataArea,
edge);
x1 = getCategoryEnd(categoryIndex, ticks.size(), dataArea,
edge);
y0 = state.getCursor() + this.categoryLabelPositionOffset;
y1 = y0 + state.getMax();
} else if (edge == RectangleEdge.LEFT) {
y0 = getCategoryStart(categoryIndex, ticks.size(), dataArea,
edge);
y1 = getCategoryEnd(categoryIndex, ticks.size(), dataArea,
edge);
x1 = state.getCursor() - this.categoryLabelPositionOffset;
x0 = x1 - state.getMax();
} else if (edge == RectangleEdge.RIGHT) {
y0 = getCategoryStart(categoryIndex, ticks.size(), dataArea,
edge);
y1 = getCategoryEnd(categoryIndex, ticks.size(), dataArea,
edge);
x0 = state.getCursor() + this.categoryLabelPositionOffset;
x1 = x0 - state.getMax();
}
Rectangle2D area = new Rectangle2D.Double(x0, y0, (x1 - x0),
(y1 - y0));
Point2D anchorPoint = RectangleAnchor.coordinates(area,
position.getCategoryAnchor());
TextBlock block = tick.getLabel();
block.draw(g2, (float) anchorPoint.getX(),
(float) anchorPoint.getY(), position.getLabelAnchor(),
(float) anchorPoint.getX(), (float) anchorPoint.getY(),
position.getAngle());
Shape bounds = block.calculateBounds(g2,
(float) anchorPoint.getX(), (float) anchorPoint.getY(),
position.getLabelAnchor(), (float) anchorPoint.getX(),
(float) anchorPoint.getY(), position.getAngle());
if (plotState != null && plotState.getOwner() != null) {
EntityCollection entities
= plotState.getOwner().getEntityCollection();
if (entities != null) {
String tooltip = getCategoryLabelToolTip(
tick.getCategory());
String url = getCategoryLabelURL(tick.getCategory());
entities.add(new CategoryLabelEntity(tick.getCategory(),
bounds, tooltip, url));
}
}
categoryIndex++;
}
if (edge.equals(RectangleEdge.TOP)) {
double h = state.getMax() + this.categoryLabelPositionOffset;
state.cursorUp(h);
}
else if (edge.equals(RectangleEdge.BOTTOM)) {
double h = state.getMax() + this.categoryLabelPositionOffset;
state.cursorDown(h);
}
else if (edge == RectangleEdge.LEFT) {
double w = state.getMax() + this.categoryLabelPositionOffset;
state.cursorLeft(w);
}
else if (edge == RectangleEdge.RIGHT) {
double w = state.getMax() + this.categoryLabelPositionOffset;
state.cursorRight(w);
}
return state;
}
/**
* Creates a temporary list of ticks that can be used when drawing the axis.
*
* @param g2 the graphics device (used to get font measurements).
* @param state the axis state.
* @param dataArea the area inside the axes.
* @param edge the location of the axis.
*
* @return A list of ticks.
*/
@Override
public List<CategoryTick> refreshTicks(Graphics2D g2, AxisState state,
Rectangle2D dataArea, RectangleEdge edge) {
List<CategoryTick> ticks = new java.util.ArrayList<CategoryTick>();
// sanity check for data area...
if (dataArea.getHeight() <= 0.0 || dataArea.getWidth() < 0.0) {
return ticks;
}
CategoryPlot plot = (CategoryPlot) getPlot();
List<Comparable> categories = plot.getCategoriesForAxis(this);
double max = 0.0;
if (categories != null) {
CategoryLabelPosition position
= this.categoryLabelPositions.getLabelPosition(edge);
float r = this.maximumCategoryLabelWidthRatio;
if (r <= 0.0) {
r = position.getWidthRatio();
}
float l;
if (position.getWidthType() == CategoryLabelWidthType.CATEGORY) {
l = (float) calculateCategorySize(categories.size(), dataArea,
edge);
}
else {
if (RectangleEdge.isLeftOrRight(edge)) {
l = (float) dataArea.getWidth();
}
else {
l = (float) dataArea.getHeight();
}
}
int categoryIndex = 0;
for (Comparable category : categories) {
g2.setFont(getTickLabelFont(category));
TextBlock label = createLabel(category, l * r, edge, g2);
if (edge == RectangleEdge.TOP || edge == RectangleEdge.BOTTOM) {
max = Math.max(max, calculateTextBlockHeight(label,
position, g2));
} else if (edge == RectangleEdge.LEFT
|| edge == RectangleEdge.RIGHT) {
max = Math.max(max, calculateTextBlockWidth(label,
position, g2));
}
ticks.add(new CategoryTick(category, label,
position.getLabelAnchor(),
position.getRotationAnchor(), position.getAngle()));
categoryIndex = categoryIndex + 1;
}
}
state.setMax(max);
return ticks;
}
/**
* Draws the tick marks. This method is called during chart rendering,
* you normally would not call this method yourself.
*
* @param g2 the graphics target ({@code null} not permitted)
* @param cursor the current offset from the edge of the dataArea
* @param dataArea the area used for plotting data ({@code null} not
* permitted)
* @param edge the location of the axis ({@code null} not permitted)
* @param state axis state information ({@code null} not permitted)
*
* @since 1.0.13
*/
public void drawTickMarks(Graphics2D g2, double cursor,
Rectangle2D dataArea, RectangleEdge edge, AxisState state) {
Plot p = getPlot();
if (p == null) {
return;
}
CategoryPlot plot = (CategoryPlot) p;
double il = getTickMarkInsideLength();
double ol = getTickMarkOutsideLength();
Line2D line = new Line2D.Double();
List<Comparable> categories = plot.getCategoriesForAxis(this);
g2.setPaint(getTickMarkPaint());
g2.setStroke(getTickMarkStroke());
if (edge.equals(RectangleEdge.TOP)) {
for (Comparable key : categories) {
double x = getCategoryMiddle(key, categories, dataArea, edge);
line.setLine(x, cursor, x, cursor + il);
g2.draw(line);
line.setLine(x, cursor, x, cursor - ol);
g2.draw(line);
}
state.cursorUp(ol);
}
else if (edge.equals(RectangleEdge.BOTTOM)) {
for (Comparable key : categories) {
double x = getCategoryMiddle(key, categories, dataArea, edge);
line.setLine(x, cursor, x, cursor - il);
g2.draw(line);
line.setLine(x, cursor, x, cursor + ol);
g2.draw(line);
}
state.cursorDown(ol);
}
else if (edge.equals(RectangleEdge.LEFT)) {
for (Comparable key : categories) {
double y = getCategoryMiddle(key, categories, dataArea, edge);
line.setLine(cursor, y, cursor + il, y);
g2.draw(line);
line.setLine(cursor, y, cursor - ol, y);
g2.draw(line);
}
state.cursorLeft(ol);
}
else if (edge.equals(RectangleEdge.RIGHT)) {
for (Comparable key : categories) {
double y = getCategoryMiddle(key, categories, dataArea, edge);
line.setLine(cursor, y, cursor - il, y);
g2.draw(line);
line.setLine(cursor, y, cursor + ol, y);
g2.draw(line);
}
state.cursorRight(ol);
}
}
/**
* Creates a label.
*
* @param category the category.
* @param width the available width.
* @param edge the edge on which the axis appears.
* @param g2 the graphics device.
*
* @return A label.
*/
protected TextBlock createLabel(Comparable category, float width,
RectangleEdge edge, Graphics2D g2) {
TextBlock label = TextUtilities.createTextBlock(category.toString(),
getTickLabelFont(category), getTickLabelPaint(category), width,
this.maximumCategoryLabelLines, new G2TextMeasurer(g2));
return label;
}
/**
* A utility method for determining the width of a text block.
*
* @param block the text block.
* @param position the position.
* @param g2 the graphics device.
*
* @return The width.
*/
protected double calculateTextBlockWidth(TextBlock block,
CategoryLabelPosition position, Graphics2D g2) {
RectangleInsets insets = getTickLabelInsets();
Size2D size = block.calculateDimensions(g2);
Rectangle2D box = new Rectangle2D.Double(0.0, 0.0, size.getWidth(),
size.getHeight());
Shape rotatedBox = ShapeUtilities.rotateShape(box, position.getAngle(),
0.0f, 0.0f);
double w = rotatedBox.getBounds2D().getWidth() + insets.getLeft()
+ insets.getRight();
return w;
}
/**
* A utility method for determining the height of a text block.
*
* @param block the text block.
* @param position the label position.
* @param g2 the graphics device.
*
* @return The height.
*/
protected double calculateTextBlockHeight(TextBlock block,
CategoryLabelPosition position, Graphics2D g2) {
RectangleInsets insets = getTickLabelInsets();
Size2D size = block.calculateDimensions(g2);
Rectangle2D box = new Rectangle2D.Double(0.0, 0.0, size.getWidth(),
size.getHeight());
Shape rotatedBox = ShapeUtilities.rotateShape(box, position.getAngle(),
0.0f, 0.0f);
double h = rotatedBox.getBounds2D().getHeight()
+ insets.getTop() + insets.getBottom();
return h;
}
/**
* Creates a clone of the axis.
*
* @return A clone.
*
* @throws CloneNotSupportedException if some component of the axis does
* not support cloning.
*/
@Override
public Object clone() throws CloneNotSupportedException {
CategoryAxis clone = (CategoryAxis) super.clone();
clone.tickLabelFontMap = new HashMap<Comparable, Font>(this.tickLabelFontMap);
clone.tickLabelPaintMap = new HashMap<Comparable, Paint>(this.tickLabelPaintMap);
clone.categoryLabelToolTips = new HashMap<Comparable, String>(this.categoryLabelToolTips);
clone.categoryLabelURLs = new HashMap<Comparable, String>(this.categoryLabelToolTips);
return clone;
}
/**
* Tests this axis 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 CategoryAxis)) {
return false;
}
if (!super.equals(obj)) {
return false;
}
CategoryAxis that = (CategoryAxis) obj;
if (that.lowerMargin != this.lowerMargin) {
return false;
}
if (that.upperMargin != this.upperMargin) {
return false;
}
if (that.categoryMargin != this.categoryMargin) {
return false;
}
if (that.maximumCategoryLabelWidthRatio
!= this.maximumCategoryLabelWidthRatio) {
return false;
}
if (that.categoryLabelPositionOffset
!= this.categoryLabelPositionOffset) {
return false;
}
if (!ObjectUtilities.equal(that.categoryLabelPositions,
this.categoryLabelPositions)) {
return false;
}
if (!ObjectUtilities.equal(that.categoryLabelToolTips,
this.categoryLabelToolTips)) {
return false;
}
if (!ObjectUtilities.equal(this.categoryLabelURLs,
that.categoryLabelURLs)) {
return false;
}
if (!ObjectUtilities.equal(this.tickLabelFontMap,
that.tickLabelFontMap)) {
return false;
}
if (!equalPaintMaps(this.tickLabelPaintMap, that.tickLabelPaintMap)) {
return false;
}
return true;
}
@Override
public int hashCode() {
return super.hashCode();
}
/**
* 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();
writePaintMap(this.tickLabelPaintMap, 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.tickLabelPaintMap = readPaintMap(stream);
}
/**
* Reads a <code>Map</code> of (<code>Comparable</code>, <code>Paint</code>)
* elements from a stream.
*
* @param in the input stream.
*
* @return The map.
*
* @throws IOException
* @throws ClassNotFoundException
*
* @see #writePaintMap(Map, ObjectOutputStream)
*/
private Map<Comparable, Paint> readPaintMap(ObjectInputStream in)
throws IOException, ClassNotFoundException {
boolean isNull = in.readBoolean();
if (isNull) {
return null;
}
Map<Comparable, Paint> result = new HashMap<Comparable, Paint>();
int count = in.readInt();
for (int i = 0; i < count; i++) {
Comparable category = (Comparable) in.readObject();
Paint paint = SerialUtilities.readPaint(in);
result.put(category, paint);
}
return result;
}
/**
* Writes a map of (<code>Comparable</code>, <code>Paint</code>)
* elements to a stream.
*
* @param map the map (<code>null</code> permitted).
*
* @param out
* @throws IOException
*
* @see #readPaintMap(ObjectInputStream)
*/
private void writePaintMap(Map<Comparable, Paint> map, ObjectOutputStream out)
throws IOException {
if (map == null) {
out.writeBoolean(true);
}
else {
out.writeBoolean(false);
Set<Comparable> keys = map.keySet();
int count = keys.size();
out.writeInt(count);
for (Comparable key : keys) {
out.writeObject(key);
SerialUtilities.writePaint(map.get(key), out);
}
}
}
/**
* Tests two maps containing (<code>Comparable</code>, <code>Paint</code>)
* elements for equality.
*
* @param map1 the first map (<code>null</code> not permitted).
* @param map2 the second map (<code>null</code> not permitted).
*
* @return A boolean.
*/
private boolean equalPaintMaps(Map<Comparable, Paint> map1, Map<Comparable, Paint> map2) {
if (map1.size() != map2.size()) {
return false;
}
for (Map.Entry<Comparable, Paint> entry : map1.entrySet()) {
Paint p1 = entry.getValue();
Paint p2 = map2.get(entry.getKey());
if (!PaintUtilities.equal(p1, p2)) {
return false;
}
}
return true;
}
}
| 54,058 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
QuarterDateFormat.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/axis/QuarterDateFormat.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.]
*
* ----------------------
* QuarterDateFormat.java
* ----------------------
* (C) Copyright 2005-2008, by Object Refinery Limited and Contributors.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes:
* --------
* 01-Mar-2005 : Version 1 (DG);
* 10-May-2005 : Added equals() method, and implemented Cloneable and
* Serializable (DG);
* ------------- JFREECHART 1.0.x ---------------------------------------------
* 08-Jun-2007 : Added Greek symbols, and support for reversing the date - see
* patch 1577221 (DG);
*
*/
package org.jfree.chart.axis;
import java.io.Serializable;
import java.text.DateFormat;
import java.text.FieldPosition;
import java.text.NumberFormat;
import java.text.ParsePosition;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;
/**
* A formatter that formats dates to show the year and quarter (for example,
* '2004 IV' for the last quarter of 2004.
*/
public class QuarterDateFormat extends DateFormat
implements Cloneable, Serializable {
/** For serialization. */
private static final long serialVersionUID = -6738465248529797176L;
/** Symbols for regular quarters. */
public static final String[] REGULAR_QUARTERS = new String[] {"1", "2",
"3", "4"};
/** Symbols for roman numbered quarters. */
public static final String[] ROMAN_QUARTERS = new String[] {"I", "II",
"III", "IV"};
/**
* Symbols for greek numbered quarters.
*
* @since 1.0.6
*/
public static final String[] GREEK_QUARTERS = new String[] {"\u0391",
"\u0392", "\u0393", "\u0394"};
/** The strings. */
private String[] quarters = REGULAR_QUARTERS;
/** A flag that controls whether the quarter or the year goes first. */
private boolean quarterFirst;
/**
* Creates a new instance for the default time zone.
*/
public QuarterDateFormat() {
this(TimeZone.getDefault());
}
/**
* Creates a new instance for the specified time zone.
*
* @param zone the time zone (<code>null</code> not permitted).
*/
public QuarterDateFormat(TimeZone zone) {
this(zone, REGULAR_QUARTERS);
}
/**
* Creates a new instance for the specified time zone.
*
* @param zone the time zone (<code>null</code> not permitted).
* @param quarterSymbols the quarter symbols.
*/
public QuarterDateFormat(TimeZone zone, String[] quarterSymbols) {
this(zone, quarterSymbols, false);
}
/**
* Creates a new instance for the specified time zone.
*
* @param zone the time zone (<code>null</code> not permitted).
* @param quarterSymbols the quarter symbols.
* @param quarterFirst a flag that controls whether the quarter or the
* year is displayed first.
*
* @since 1.0.6
*/
public QuarterDateFormat(TimeZone zone, String[] quarterSymbols,
boolean quarterFirst) {
if (zone == null) {
throw new IllegalArgumentException("Null 'zone' argument.");
}
this.calendar = new GregorianCalendar(zone);
this.quarters = quarterSymbols;
this.quarterFirst = quarterFirst;
// the following is never used, but it seems that DateFormat requires
// it to be non-null. It isn't well covered in the spec, refer to
// bug parade 5061189 for more info.
this.numberFormat = NumberFormat.getNumberInstance();
}
/**
* Formats the given date.
*
* @param date the date.
* @param toAppendTo the string buffer.
* @param fieldPosition the field position.
*
* @return The formatted date.
*/
@Override
public StringBuffer format(Date date, StringBuffer toAppendTo,
FieldPosition fieldPosition) {
this.calendar.setTime(date);
int year = this.calendar.get(Calendar.YEAR);
int month = this.calendar.get(Calendar.MONTH);
int quarter = month / 3;
if (this.quarterFirst) {
toAppendTo.append(this.quarters[quarter]);
toAppendTo.append(" ");
toAppendTo.append(year);
}
else {
toAppendTo.append(year);
toAppendTo.append(" ");
toAppendTo.append(this.quarters[quarter]);
}
return toAppendTo;
}
/**
* Parses the given string (not implemented).
*
* @param source the date string.
* @param pos the parse position.
*
* @return <code>null</code>, as this method has not been implemented.
*/
@Override
public Date parse(String source, ParsePosition pos) {
return null;
}
/**
* Tests this formatter 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 QuarterDateFormat)) {
return false;
}
QuarterDateFormat that = (QuarterDateFormat) obj;
if (!Arrays.equals(this.quarters, that.quarters)) {
return false;
}
if (this.quarterFirst != that.quarterFirst) {
return false;
}
return super.equals(obj);
}
}
| 6,756 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
NumberTickUnit.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/axis/NumberTickUnit.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.]
*
* -------------------
* NumberTickUnit.java
* -------------------
* (C) Copyright 2001-2008, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 19-Dec-2001 : Added standard header (DG);
* 01-May-2002 : Updated for changed to TickUnit class (DG);
* 01-Oct-2002 : Fixed errors reported by Checkstyle (DG);
* 08-Nov-2002 : Moved to new package com.jrefinery.chart.axis (DG);
* 09-Jan-2002 : Added a new constructor (DG);
* 26-Mar-2003 : Implemented Serializable (DG);
* 05-Jul-2005 : Added equals() implementation (DG);
* 05-Sep-2005 : Implemented hashCode(), thanks to Thomas Morgner (DG);
* 02-Aug-2007 : Added new constructor with minorTickCount (DG);
*
*/
package org.jfree.chart.axis;
import java.io.Serializable;
import java.text.NumberFormat;
/**
* A numerical tick unit.
*/
public class NumberTickUnit extends TickUnit implements Serializable {
/** For serialization. */
private static final long serialVersionUID = 3849459506627654442L;
/** A formatter for the tick unit. */
private NumberFormat formatter;
/**
* Creates a new number tick unit.
*
* @param size the size of the tick unit.
*/
public NumberTickUnit(double size) {
this(size, NumberFormat.getNumberInstance());
}
/**
* Creates a new number tick unit.
*
* @param size the size of the tick unit.
* @param formatter a number formatter for the tick unit (<code>null</code>
* not permitted).
*/
public NumberTickUnit(double size, NumberFormat formatter) {
super(size);
if (formatter == null) {
throw new IllegalArgumentException("Null 'formatter' argument.");
}
this.formatter = formatter;
}
/**
* Creates a new number tick unit.
*
* @param size the size of the tick unit.
* @param formatter a number formatter for the tick unit (<code>null</code>
* not permitted).
* @param minorTickCount the number of minor ticks.
*
* @since 1.0.7
*/
public NumberTickUnit(double size, NumberFormat formatter,
int minorTickCount) {
super(size, minorTickCount);
if (formatter == null) {
throw new IllegalArgumentException("Null 'formatter' argument.");
}
this.formatter = formatter;
}
/**
* Converts a value to a string.
*
* @param value the value.
*
* @return The formatted string.
*/
@Override
public String valueToString(double value) {
return this.formatter.format(value);
}
/**
* Tests this formatter 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 NumberTickUnit)) {
return false;
}
if (!super.equals(obj)) {
return false;
}
NumberTickUnit that = (NumberTickUnit) obj;
if (!this.formatter.equals(that.formatter)) {
return false;
}
return true;
}
/**
* Returns a string representing this unit.
*
* @return A string.
*/
@Override
public String toString() {
return "[size=" + this.valueToString(this.getSize()) + "]";
}
/**
* Returns a hash code for this instance.
*
* @return A hash code.
*/
@Override
public int hashCode() {
int result = super.hashCode();
result = 29 * result + (this.formatter != null
? this.formatter.hashCode() : 0);
return result;
}
}
| 5,082 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
AxisState.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/axis/AxisState.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.]
*
* --------------
* AxisState.java
* --------------
* (C) Copyright 2003-2012, by Object Refinery Limited and Contributors.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 03-Nov-2003 : Added standard header (DG);
* 07-Nov-2003 : Added 'max' attribute (DG);
* 17-Jun-2012 : Removed JCommon dependencies (DG);
*
*/
package org.jfree.chart.axis;
import java.util.List;
import org.jfree.chart.ui.RectangleEdge;
/**
* Instances of this class are used to carry state information for an axis
* during the drawing process. By retaining this information in a separate
* object, it is possible for multiple threads to draw the same axis to
* different output targets (each drawing will maintain separate state
* information).
*/
public class AxisState {
/** The cursor position. */
private double cursor;
/** The axis ticks. */
private List<ValueTick> ticks;
/** The maximum width/height. */
private double max;
/**
* Creates a new axis state.
*/
public AxisState() {
this(0.0);
}
/**
* Creates a new axis state.
*
* @param cursor the cursor.
*/
public AxisState(double cursor) {
this.cursor = cursor;
this.ticks = new java.util.ArrayList<ValueTick>();
}
/**
* Returns the cursor position.
*
* @return The cursor position.
*/
public double getCursor() {
return this.cursor;
}
/**
* Sets the cursor position.
*
* @param cursor the cursor position.
*/
public void setCursor(double cursor) {
this.cursor = cursor;
}
/**
* Moves the cursor outwards by the specified number of units.
*
* @param units the units.
* @param edge the edge.
*/
public void moveCursor(double units, RectangleEdge edge) {
if (edge == RectangleEdge.TOP) {
cursorUp(units);
}
else if (edge == RectangleEdge.BOTTOM) {
cursorDown(units);
}
else if (edge == RectangleEdge.LEFT) {
cursorLeft(units);
}
else if (edge == RectangleEdge.RIGHT) {
cursorRight(units);
}
}
/**
* Moves the cursor up by the specified number of Java 2D units.
*
* @param units the units.
*/
public void cursorUp(double units) {
this.cursor = this.cursor - units;
}
/**
* Moves the cursor down by the specified number of Java 2D units.
*
* @param units the units.
*/
public void cursorDown(double units) {
this.cursor = this.cursor + units;
}
/**
* Moves the cursor left by the specified number of Java 2D units.
*
* @param units the units.
*/
public void cursorLeft(double units) {
this.cursor = this.cursor - units;
}
/**
* Moves the cursor right by the specified number of Java 2D units.
*
* @param units the units.
*/
public void cursorRight(double units) {
this.cursor = this.cursor + units;
}
/**
* Returns the list of ticks.
*
* @return The list of ticks.
*/
public List<ValueTick> getTicks() {
return this.ticks;
}
/**
* Sets the list of ticks.
*
* @param ticks the ticks.
*/
public void setTicks(List<ValueTick> ticks) {
this.ticks = ticks;
}
/**
* Returns the maximum width/height.
*
* @return The maximum width/height.
*/
public double getMax() {
return this.max;
}
/**
* Sets the maximum width/height.
*
* @param max the maximum width/height.
*/
public void setMax(double max) {
this.max = max;
}
}
| 5,031 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
Timeline.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/axis/Timeline.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.]
*
* -------------
* Timeline.java
* -------------
* (C) Copyright 2000-2008, by Object Refinery Limited and Contributors.
*
* Original Author: Bill Kelemen;
* Contributor(s): David Gilbert (for Object Refinery Limited);
*
* Changes
* -------
* 23-May-2003 : Version 1 (BK);
* 09-Sep-2003 : Changed some method and parameter names (DG);
* 02-Feb-2007 : Removed author tags all over JFreeChart sources (DG);
*
*/
package org.jfree.chart.axis;
import java.util.Date;
/**
* An interface that defines the contract for a Timeline.
* <P>
* A Timeline will present a series of values to be used for an axis. Each
* Timeline must provide transformation methods between domain values and
* timeline values. In theory many transformations are possible. This interface
* has been implemented completely in
* {@link org.jfree.chart.axis.SegmentedTimeline}.
* <P>
* A timeline can be used as parameter to a
* {@link org.jfree.chart.axis.DateAxis} to define the values that this axis
* supports. As an example, the {@link org.jfree.chart.axis.SegmentedTimeline}
* implements a timeline formed by segments of equal length (ex. days, hours,
* minutes) where some segments can be included in the timeline and others
* excluded. Therefore timelines like "working days" or "working hours" can be
* created where non-working days or non-working hours respectively can be
* removed from the timeline, and therefore from the axis. This creates a smooth
* plot with equal separation between all included segments.
* <P>
* Because Timelines were created mainly for Date related axis, values are
* represented as longs instead of doubles. In this case, the domain value is
* just the number of milliseconds since January 1, 1970, 00:00:00 GMT as
* defined by the getTime() method of {@link java.util.Date}.
*
* @see org.jfree.chart.axis.SegmentedTimeline
* @see org.jfree.chart.axis.DateAxis
*/
public interface Timeline {
/**
* Translates a millisecond (as defined by java.util.Date) into an index
* along this timeline.
*
* @param millisecond the millisecond.
*
* @return A timeline value.
*/
long toTimelineValue(long millisecond);
/**
* Translates a date into a value on this timeline.
*
* @param date the date.
*
* @return A timeline value
*/
long toTimelineValue(Date date);
/**
* Translates a value relative to this timeline into a domain value. The
* domain value obtained by this method is not always the same domain value
* that could have been supplied to
* translateDomainValueToTimelineValue(domainValue).
* This is because the original tranformation may not be complete
* reversable.
*
* @see org.jfree.chart.axis.SegmentedTimeline
*
* @param timelineValue a timeline value.
*
* @return A domain value.
*/
long toMillisecond(long timelineValue);
/**
* Returns <code>true</code> if a value is contained in the timeline values.
*
* @param millisecond the millisecond.
*
* @return <code>true</code> if value is contained in the timeline and
* <code>false</code> otherwise.
*/
boolean containsDomainValue(long millisecond);
/**
* Returns <code>true</code> if a date is contained in the timeline values.
*
* @param date the date to verify.
*
* @return <code>true</code> if value is contained in the timeline and
* <code>false</code> otherwise.
*/
boolean containsDomainValue(Date date);
/**
* Returns <code>true</code> if a range of values are contained in the
* timeline.
*
* @param fromMillisecond the start of the range to verify.
* @param toMillisecond the end of the range to verify.
*
* @return <code>true</code> if the range is contained in the timeline or
* <code>false</code> otherwise
*/
boolean containsDomainRange(long fromMillisecond, long toMillisecond);
/**
* Returns <code>true</code> if a range of dates are contained in the
* timeline.
*
* @param fromDate the start of the range to verify.
* @param toDate the end of the range to verify.
*
* @return <code>true</code> if the range is contained in the timeline or
* <code>false</code> otherwise
*/
boolean containsDomainRange(Date fromDate, Date toDate);
}
| 5,672 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
DateTickUnit.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/axis/DateTickUnit.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.]
*
* -----------------
* DateTickUnit.java
* -----------------
* (C) Copyright 2000-2012, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): Chris Boek;
*
* Changes
* -------
* 08-Nov-2002 : Moved to new package com.jrefinery.chart.axis (DG);
* 27-Nov-2002 : Added IllegalArgumentException to getMillisecondCount()
* method (DG);
* 26-Mar-2003 : Implemented Serializable (DG);
* 12-Nov-2003 : Added roll fields that can improve the labelling on segmented
* date axes (DG);
* 03-Dec-2003 : DateFormat constructor argument is now filled with an default
* if null (TM);
* 07-Dec-2003 : Fixed bug (null pointer exception) in constructor (DG);
* ------------- JFREECHART 1.0.x ---------------------------------------------
* 21-Mar-2007 : Added toString() for debugging (DG);
* 04-Apr-2007 : Added new methods addToDate(Date, TimeZone) and rollDate(Date,
* TimeZone) (CB);
* 09-Jun-2008 : Deprecated addToDate(Date) (DG);
* 09-Jan-2009 : Replaced the unit and rollUnit fields with an enumerated
* type (DG);
* 17-Jun-2012 : Removed JCommon dependencies (DG);
*
*/
package org.jfree.chart.axis;
import java.io.Serializable;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import org.jfree.chart.util.ObjectUtilities;
/**
* A tick unit for use by subclasses of {@link DateAxis}. Instances of this
* class are immutable.
*/
public class DateTickUnit extends TickUnit implements Serializable {
/** For serialization. */
private static final long serialVersionUID = -7289292157229621901L;
/**
* The units.
*
* @since 1.0.13
*/
private DateTickUnitType unitType;
/** The unit count. */
private int count;
/**
* The roll unit type.
*
* @since 1.0.13
*/
private DateTickUnitType rollUnitType;
/** The roll count. */
private int rollCount;
/** The date formatter. */
private DateFormat formatter;
/**
* Creates a new date tick unit.
*
* @param unitType the unit type (<code>null</code> not permitted).
* @param multiple the multiple (of the unit type, must be > 0).
*
* @since 1.0.13
*/
public DateTickUnit(DateTickUnitType unitType, int multiple) {
this(unitType, multiple, DateFormat.getDateInstance(DateFormat.SHORT));
}
/**
* Creates a new date tick unit.
*
* @param unitType the unit type (<code>null</code> not permitted).
* @param multiple the multiple (of the unit type, must be > 0).
* @param formatter the date formatter (<code>null</code> not permitted).
*
* @since 1.0.13
*/
public DateTickUnit(DateTickUnitType unitType, int multiple,
DateFormat formatter) {
this(unitType, multiple, unitType, multiple, formatter);
}
/**
* Creates a new unit.
*
* @param unitType the unit.
* @param multiple the multiple.
* @param rollUnitType the roll unit.
* @param rollMultiple the roll multiple.
* @param formatter the date formatter (<code>null</code> not permitted).
*
* @since 1.0.13
*/
public DateTickUnit(DateTickUnitType unitType, int multiple,
DateTickUnitType rollUnitType, int rollMultiple,
DateFormat formatter) {
super(DateTickUnit.getMillisecondCount(unitType, multiple));
if (formatter == null) {
throw new IllegalArgumentException("Null 'formatter' argument.");
}
if (multiple <= 0) {
throw new IllegalArgumentException("Requires 'multiple' > 0.");
}
if (rollMultiple <= 0) {
throw new IllegalArgumentException("Requires 'rollMultiple' > 0.");
}
this.unitType = unitType;
this.count = multiple;
this.rollUnitType = rollUnitType;
this.rollCount = rollMultiple;
this.formatter = formatter;
}
/**
* Returns the unit type.
*
* @return The unit type (never <code>null</code>).
*
* @since 1.0.13
*/
public DateTickUnitType getUnitType() {
return this.unitType;
}
/**
* Returns the unit multiple.
*
* @return The unit multiple (always > 0).
*/
public int getMultiple() {
return this.count;
}
/**
* Returns the roll unit type.
*
* @return The roll unit type (never <code>null</code>).
*
* @since 1.0.13
*/
public DateTickUnitType getRollUnitType() {
return this.rollUnitType;
}
/**
* Returns the roll unit multiple.
*
* @return The roll unit multiple.
*
* @since 1.0.13
*/
public int getRollMultiple() {
return this.rollCount;
}
/**
* Formats a value.
*
* @param milliseconds date in milliseconds since 01-01-1970.
*
* @return The formatted date.
*/
@Override
public String valueToString(double milliseconds) {
return this.formatter.format(new Date((long) milliseconds));
}
/**
* Formats a date using the tick unit's formatter.
*
* @param date the date.
*
* @return The formatted date.
*/
public String dateToString(Date date) {
return this.formatter.format(date);
}
/**
* Calculates a new date by adding this unit to the base date.
*
* @param base the base date.
* @param zone the time zone for the date calculation.
*
* @return A new date one unit after the base date.
*
* @since 1.0.6
*/
public Date addToDate(Date base, TimeZone zone) {
// as far as I know, the Locale for the calendar only affects week
// number calculations, and since DateTickUnit doesn't do week
// arithmetic, the default locale (whatever it is) should be fine
// here...
Calendar calendar = Calendar.getInstance(zone);
calendar.setTime(base);
calendar.add(this.unitType.getCalendarField(), this.count);
return calendar.getTime();
}
/**
* Rolls the date forward by the amount specified by the roll unit and
* count.
*
* @param base the base date.
* @return The rolled date.
*
* @see #rollDate(Date, TimeZone)
*/
public Date rollDate(Date base) {
return rollDate(base, TimeZone.getDefault());
}
/**
* Rolls the date forward by the amount specified by the roll unit and
* count.
*
* @param base the base date.
* @param zone the time zone.
*
* @return The rolled date.
*
* @since 1.0.6
*/
public Date rollDate(Date base, TimeZone zone) {
// as far as I know, the Locale for the calendar only affects week
// number calculations, and since DateTickUnit doesn't do week
// arithmetic, the default locale (whatever it is) should be fine
// here...
Calendar calendar = Calendar.getInstance(zone);
calendar.setTime(base);
calendar.add(this.rollUnitType.getCalendarField(), this.rollCount);
return calendar.getTime();
}
/**
* Returns a field code that can be used with the <code>Calendar</code>
* class.
*
* @return The field code.
*/
public int getCalendarField() {
return this.unitType.getCalendarField();
}
/**
* Returns the (approximate) number of milliseconds for the given unit and
* unit count.
* <P>
* This value is an approximation some of the time (e.g. months are
* assumed to have 31 days) but this shouldn't matter.
*
* @param unit the unit.
* @param count the unit count.
*
* @return The number of milliseconds.
*
* @since 1.0.13
*/
private static long getMillisecondCount(DateTickUnitType unit, int count) {
if (unit.equals(DateTickUnitType.YEAR)) {
return (365L * 24L * 60L * 60L * 1000L) * count;
}
else if (unit.equals(DateTickUnitType.MONTH)) {
return (31L * 24L * 60L * 60L * 1000L) * count;
}
else if (unit.equals(DateTickUnitType.DAY)) {
return (24L * 60L * 60L * 1000L) * count;
}
else if (unit.equals(DateTickUnitType.HOUR)) {
return (60L * 60L * 1000L) * count;
}
else if (unit.equals(DateTickUnitType.MINUTE)) {
return (60L * 1000L) * count;
}
else if (unit.equals(DateTickUnitType.SECOND)) {
return 1000L * count;
}
else if (unit.equals(DateTickUnitType.MILLISECOND)) {
return count;
}
else {
throw new IllegalArgumentException("The 'unit' argument has a "
+ "value that is not recognised.");
}
}
/**
* A utility method to put a default in place if a null formatter is
* supplied.
*
* @param formatter the formatter (<code>null</code> permitted).
*
* @return The formatter if it is not null, otherwise a default.
*/
private static DateFormat notNull(DateFormat formatter) {
if (formatter == null) {
return DateFormat.getDateInstance(DateFormat.SHORT);
}
else {
return formatter;
}
}
/**
* Tests this unit 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 DateTickUnit)) {
return false;
}
if (!super.equals(obj)) {
return false;
}
DateTickUnit that = (DateTickUnit) obj;
if (!(this.unitType.equals(that.unitType))) {
return false;
}
if (this.count != that.count) {
return false;
}
if (!ObjectUtilities.equal(this.formatter, that.formatter)) {
return false;
}
return true;
}
/**
* Returns a hash code for this object.
*
* @return A hash code.
*/
@Override
public int hashCode() {
int result = 19;
result = 37 * result + this.unitType.hashCode();
result = 37 * result + this.count;
result = 37 * result + this.formatter.hashCode();
return result;
}
/**
* Returns a string representation of this instance, primarily used for
* debugging purposes.
*
* @return A string representation of this instance.
*/
@Override
public String toString() {
return "DateTickUnit[" + this.unitType.toString() + ", "
+ this.count + "]";
}
}
| 12,175 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
StandardTickUnitSource.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/axis/StandardTickUnitSource.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.]
*
* ---------------------------
* StandardTickUnitSource.java
* ---------------------------
* (C) Copyright 2003-2008, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 23-Sep-2003 : Version 1 (DG);
* 25-Oct-2007 : Implemented Serializable and equals() method (DG);
*
*/
package org.jfree.chart.axis;
import java.io.Serializable;
import java.text.DecimalFormat;
/**
* A source that can used by the {@link NumberAxis} class to obtain a
* suitable {@link TickUnit}. Instances of this class are {@link Serializable}
* from version 1.0.7 onwards. Cloning is not supported, because instances
* are immutable.
*/
public class StandardTickUnitSource implements TickUnitSource, Serializable {
/** Constant for log(10.0). */
private static final double LOG_10_VALUE = Math.log(10.0);
/**
* Default constructor.
*/
public StandardTickUnitSource() {
super();
}
/**
* Returns a tick unit that is larger than the supplied unit.
*
* @param unit the unit (<code>null</code> not permitted).
*
* @return A tick unit that is larger than the supplied unit.
*/
@Override
public TickUnit getLargerTickUnit(TickUnit unit) {
double x = unit.getSize();
double log = Math.log(x) / LOG_10_VALUE;
double higher = Math.ceil(log);
return new NumberTickUnit(Math.pow(10, higher),
new DecimalFormat("0.0E0"));
}
/**
* Returns the tick unit in the collection that is greater than or equal
* to (in size) the specified unit.
*
* @param unit the unit (<code>null</code> not permitted).
*
* @return A unit from the collection.
*/
@Override
public TickUnit getCeilingTickUnit(TickUnit unit) {
return getLargerTickUnit(unit);
}
/**
* Returns the tick unit in the collection that is greater than or equal
* to the specified size.
*
* @param size the size.
*
* @return A unit from the collection.
*/
@Override
public TickUnit getCeilingTickUnit(double size) {
double log = Math.log(size) / LOG_10_VALUE;
double higher = Math.ceil(log);
return new NumberTickUnit(Math.pow(10, higher),
new DecimalFormat("0.0E0"));
}
/**
* 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;
}
return (obj instanceof StandardTickUnitSource);
}
/**
* Returns a hash code for this instance.
*
* @return A hash code.
*/
@Override
public int hashCode() {
return 0;
}
}
| 4,132 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
DateTickUnitType.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/axis/DateTickUnitType.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.]
*
* ---------------------
* DateTickUnitType.java
* ---------------------
* (C) Copyright 2009, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 09-Jan-2009 : Version 1 (DG);
*
*/
package org.jfree.chart.axis;
import java.util.Calendar;
/**
* An enumeration of the unit types for a {@link DateTickUnit} instance.
*
* @since 1.0.13
*/
public enum DateTickUnitType {
/** Year. */
YEAR("DateTickUnitType.YEAR", Calendar.YEAR),
/** Month. */
MONTH("DateTickUnitType.MONTH", Calendar.MONTH),
/** Day. */
DAY("DateTickUnitType.DAY", Calendar.DATE),
/** Hour. */
HOUR("DateTickUnitType.HOUR", Calendar.HOUR_OF_DAY),
/** Minute. */
MINUTE("DateTickUnitType.MINUTE", Calendar.MINUTE),
/** Second. */
SECOND("DateTickUnitType.SECOND", Calendar.SECOND),
/** Millisecond. */
MILLISECOND("DateTickUnitType.MILLISECOND", Calendar.MILLISECOND);
/** The name. */
private String name;
/** The corresponding field value in Java's Calendar class. */
private int calendarField;
/**
* Private constructor.
*
* @param name the name.
* @param calendarField the calendar field.
*/
private DateTickUnitType(String name, int calendarField) {
this.name = name;
this.calendarField = calendarField;
}
/**
* Returns the calendar field.
*
* @return The calendar field.
*/
public int getCalendarField() {
return this.calendarField;
}
/**
* Returns a string representing the object.
*
* @return The string.
*/
@Override
public String toString() {
return this.name;
}
}
| 2,995 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
DateTick.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/axis/DateTick.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.]
*
* -------------
* DateTick.java
* -------------
* (C) Copyright 2003-2012, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): Peter Kolb (patch 1934255);
* Andrew Mickish (patch 1870189);
*
* Changes
* -------
* 07-Nov-2003 : Version 1 (DG);
* 13-May-2004 : Added equals() method (DG);
* 25-Sep-2008 : Added minor tick support, see patch 1934255 by Peter Kolb (DG);
* 17-Jun-2012 : Removed JCommon dependencies (DG);
*
*/
package org.jfree.chart.axis;
import java.util.Date;
import org.jfree.chart.ui.TextAnchor;
import org.jfree.chart.util.ObjectUtilities;
/**
* A tick used by the {@link DateAxis} class.
*/
public class DateTick extends ValueTick {
/** The date. */
private Date date;
/**
* Creates a new date tick.
*
* @param date the date.
* @param label the label.
* @param textAnchor the part of the label that is aligned to the anchor
* point.
* @param rotationAnchor defines the rotation point relative to the text.
* @param angle the rotation angle (in radians).
*/
public DateTick(Date date, String label,
TextAnchor textAnchor, TextAnchor rotationAnchor,
double angle) {
this(TickType.MAJOR, date, label, textAnchor, rotationAnchor, angle);
}
/**
* Creates a new date tick.
*
* @param tickType the tick type.
* @param date the date.
* @param label the label.
* @param textAnchor the part of the label that is aligned to the anchor
* point.
* @param rotationAnchor defines the rotation point relative to the text.
* @param angle the rotation angle (in radians).
*
* @since 1.0.12
*/
public DateTick(TickType tickType, Date date, String label,
TextAnchor textAnchor, TextAnchor rotationAnchor,
double angle) {
super(tickType, date.getTime(), label, textAnchor, rotationAnchor,
angle);
this.date = date;
}
/**
* Returns the date.
*
* @return The date.
*/
public Date getDate() {
return this.date;
}
/**
* Tests this tick for equality with an arbitrary object.
*
* @param obj the object to test (<code>null</code> permitted).
*
* @return A boolean.
*/
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof DateTick)) {
return false;
}
DateTick that = (DateTick) obj;
if (!ObjectUtilities.equal(this.date, that.date)) {
return false;
}
return super.equals(obj);
}
/**
* Returns a hash code for this object.
*
* @return A hash code.
*/
@Override
public int hashCode() {
return this.date.hashCode();
}
}
| 4,231 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
TickType.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/axis/TickType.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.]
*
* -------------
* TickType.java
* -------------
* (C) Copyright 2007, 2008, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes:
* --------
* 02-Aug-2007 : Version 1 (DG);
*
*/
package org.jfree.chart.axis;
/**
* Used to indicate the tick type (MAJOR or MINOR).
*
* @since 1.0.7
*/
public enum TickType {
/** Major tick. */
MAJOR("MAJOR"),
/** Minor tick. */
MINOR("MINOR");
/** The name. */
private String name;
/**
* Private constructor.
*
* @param name the name.
*/
private TickType(String name) {
this.name = name;
}
/**
* Returns a string representing the object.
*
* @return The string.
*/
@Override
public String toString() {
return this.name;
}
}
| 2,090 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
ValueTick.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/axis/ValueTick.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.]
*
* --------------
* ValueTick.java
* --------------
* (C) Copyright 2003-2012, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 07-Nov-2003 : Version 1 (DG);
* 02-Aug-2007 : Added tick type attribute (DG);
* 17-Jun-2012 : Removed JCommon dependencies (DG);
*
*/
package org.jfree.chart.axis;
import org.jfree.chart.ui.TextAnchor;
/**
* A value tick.
*/
public abstract class ValueTick extends Tick {
/** The value. */
private double value;
/**
* The tick type (major or minor).
*
* @since 1.0.7
*/
private TickType tickType;
/**
* Creates a new value tick.
*
* @param value the value.
* @param label the label.
* @param textAnchor the part of the label that is aligned to the anchor
* point.
* @param rotationAnchor defines the rotation point relative to the label.
* @param angle the rotation angle (in radians).
*/
public ValueTick(double value, String label,
TextAnchor textAnchor, TextAnchor rotationAnchor,
double angle) {
this(TickType.MAJOR, value, label, textAnchor, rotationAnchor, angle);
this.value = value;
}
/**
* Creates a new value tick.
*
* @param tickType the tick type (major or minor).
* @param value the value.
* @param label the label.
* @param textAnchor the part of the label that is aligned to the anchor
* point.
* @param rotationAnchor defines the rotation point relative to the label.
* @param angle the rotation angle (in radians).
*
* @since 1.0.7
*/
public ValueTick(TickType tickType, double value, String label,
TextAnchor textAnchor, TextAnchor rotationAnchor,
double angle) {
super(label, textAnchor, rotationAnchor, angle);
this.value = value;
this.tickType = tickType;
}
/**
* Returns the value.
*
* @return The value.
*/
public double getValue() {
return this.value;
}
/**
* Returns the tick type (major or minor).
*
* @return The tick type.
*
* @since 1.0.7
*/
public TickType getTickType() {
return this.tickType;
}
/**
* Tests this tick for equality with an arbitrary object.
*
* @param obj the object to test (<code>null</code> permitted).
*
* @return A boolean.
*/
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof ValueTick)) {
return false;
}
ValueTick that = (ValueTick) obj;
if (this.value != that.value) {
return false;
}
if (!this.tickType.equals(that.tickType)) {
return false;
}
return super.equals(obj);
}
}
| 4,259 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
SymbolAxis.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/axis/SymbolAxis.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.]
*
* ---------------
* SymbolAxis.java
* ---------------
* (C) Copyright 2002-2013, by Anthony Boulestreau and Contributors.
*
* Original Author: Anthony Boulestreau;
* Contributor(s): David Gilbert (for Object Refinery Limited);
*
*
* Changes
* -------
* 29-Mar-2002 : First version (AB);
* 19-Apr-2002 : Updated formatting and import statements (DG);
* 21-Jun-2002 : Make change to use the class TickUnit - remove valueToString()
* method and add SymbolicTickUnit (AB);
* 25-Jun-2002 : Removed redundant code (DG);
* 25-Jul-2002 : Changed order of parameters in ValueAxis constructor (DG);
* 05-Sep-2002 : Updated constructor to reflect changes in the Axis class (DG);
* 08-Nov-2002 : Moved to new package com.jrefinery.chart.axis (DG);
* 14-Feb-2003 : Added back missing constructor code (DG);
* 26-Mar-2003 : Implemented Serializable (DG);
* 14-May-2003 : Renamed HorizontalSymbolicAxis --> SymbolicAxis and merged in
* VerticalSymbolicAxis (DG);
* 12-Aug-2003 : Fixed bug where refreshTicks() method has different signature
* to super class (DG);
* 29-Oct-2003 : Added workaround for font alignment in PDF output (DG);
* 02-Nov-2003 : Added code to avoid overlapping labels (MR);
* 07-Nov-2003 : Modified to use new tick classes (DG);
* 18-Nov-2003 : Fixed bug where symbols are not being displayed on the
* axis (DG);
* 24-Nov-2003 : Added fix for gridlines on zooming (bug id 834643) (DG);
* 21-Jan-2004 : Update for renamed method in ValueAxis (DG);
* 11-Mar-2004 : Modified the way the background grid color is being drawn, see
* this thread:
* http://www.jfree.org/phpBB2/viewtopic.php?p=22973 (DG);
* 16-Mar-2004 : Added plotState to draw() method (DG);
* 07-Apr-2004 : Modified string bounds calculation (DG);
* 28-Mar-2005 : Renamed autoRangeIncludesZero() --> getAutoRangeIncludesZero()
* and autoRangeStickyZero() --> getAutoRangeStickyZero() (DG);
* 05-Jul-2005 : Fixed signature on refreshTicks() method - see bug report
* 1232264 (DG);
* 06-Jul-2005 : Renamed SymbolicAxis --> SymbolAxis, added equals() method,
* renamed getSymbolicValue() --> getSymbols(), renamed
* symbolicGridPaint --> gridBandPaint, fixed serialization of
* gridBandPaint, renamed symbolicGridLinesVisible -->
* gridBandsVisible, eliminated symbolicGridLineList (DG);
* ------------- JFREECHART 1.0.x ---------------------------------------------
* 02-Feb-2007 : Removed author tags all over JFreeChart sources (DG);
* 28-Feb-2007 : Fixed bug 1669302 (tick label overlap) (DG);
* 25-Jul-2007 : Added new field for alternate grid band paint (DG);
* 15-Aug-2008 : Use alternate grid band paint when drawing (DG);
* 17-Jun-2012 : Removed JCommon dependencies (DG);
*
*/
package org.jfree.chart.axis;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.Shape;
import java.awt.Stroke;
import java.awt.geom.Rectangle2D;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.text.NumberFormat;
import java.util.Arrays;
import java.util.List;
import org.jfree.chart.ui.RectangleEdge;
import org.jfree.chart.ui.TextAnchor;
import org.jfree.chart.util.PaintUtilities;
import org.jfree.chart.event.AxisChangeEvent;
import org.jfree.chart.plot.Plot;
import org.jfree.chart.plot.PlotRenderingInfo;
import org.jfree.chart.plot.ValueAxisPlot;
import org.jfree.chart.text.TextUtilities;
import org.jfree.chart.util.ParamChecks;
import org.jfree.chart.util.SerialUtilities;
import org.jfree.data.Range;
/**
* A standard linear value axis that replaces integer values with symbols.
*/
public class SymbolAxis extends NumberAxis implements Serializable {
/** For serialization. */
private static final long serialVersionUID = 7216330468770619716L;
/** The default grid band paint. */
public static final Paint DEFAULT_GRID_BAND_PAINT
= new Color(232, 234, 232, 128);
/**
* The default paint for alternate grid bands.
*
* @since 1.0.7
*/
public static final Paint DEFAULT_GRID_BAND_ALTERNATE_PAINT
= new Color(0, 0, 0, 0); // transparent
/** The list of symbols to display instead of the numeric values. */
private List<String> symbols;
/** Flag that indicates whether or not grid bands are visible. */
private boolean gridBandsVisible;
/** The paint used to color the grid bands (if the bands are visible). */
private transient Paint gridBandPaint;
/**
* The paint used to fill the alternate grid bands.
*
* @since 1.0.7
*/
private transient Paint gridBandAlternatePaint;
/**
* Constructs a symbol axis, using default attribute values where
* necessary.
*
* @param label the axis label (<code>null</code> permitted).
* @param sv the list of symbols to display instead of the numeric
* values.
*/
public SymbolAxis(String label, String[] sv) {
super(label);
this.symbols = Arrays.asList(sv);
this.gridBandsVisible = true;
this.gridBandPaint = DEFAULT_GRID_BAND_PAINT;
this.gridBandAlternatePaint = DEFAULT_GRID_BAND_ALTERNATE_PAINT;
setAutoTickUnitSelection(false, false);
setAutoRangeStickyZero(false);
}
/**
* Returns an array of the symbols for the axis.
*
* @return The symbols.
*/
public String[] getSymbols() {
String[] result = new String[this.symbols.size()];
result = this.symbols.toArray(result);
return result;
}
/**
* Returns <code>true</code> if the grid bands are showing, and
* <code>false</code> otherwise.
*
* @return <code>true</code> if the grid bands are showing, and
* <code>false</code> otherwise.
*
* @see #setGridBandsVisible(boolean)
*/
public boolean isGridBandsVisible() {
return this.gridBandsVisible;
}
/**
* Sets the visibility of the grid bands and notifies registered
* listeners that the axis has been modified.
*
* @param flag the new setting.
*
* @see #isGridBandsVisible()
*/
public void setGridBandsVisible(boolean flag) {
if (this.gridBandsVisible != flag) {
this.gridBandsVisible = flag;
fireChangeEvent();
}
}
/**
* Returns the paint used to color the grid bands.
*
* @return The grid band paint (never <code>null</code>).
*
* @see #setGridBandPaint(Paint)
* @see #isGridBandsVisible()
*/
public Paint getGridBandPaint() {
return this.gridBandPaint;
}
/**
* Sets the grid band paint and sends an {@link AxisChangeEvent} to
* all registered listeners.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getGridBandPaint()
*/
public void setGridBandPaint(Paint paint) {
ParamChecks.nullNotPermitted(paint, "paint");
this.gridBandPaint = paint;
fireChangeEvent();
}
/**
* Returns the paint used for alternate grid bands.
*
* @return The paint (never <code>null</code>).
*
* @see #setGridBandAlternatePaint(Paint)
* @see #getGridBandPaint()
*
* @since 1.0.7
*/
public Paint getGridBandAlternatePaint() {
return this.gridBandAlternatePaint;
}
/**
* Sets the paint used for alternate grid bands and sends a
* {@link AxisChangeEvent} to all registered listeners.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getGridBandAlternatePaint()
* @see #setGridBandPaint(Paint)
*
* @since 1.0.7
*/
public void setGridBandAlternatePaint(Paint paint) {
ParamChecks.nullNotPermitted(paint, "paint");
this.gridBandAlternatePaint = paint;
fireChangeEvent();
}
/**
* This operation is not supported by this axis.
*
* @param g2 the graphics device.
* @param dataArea the area in which the plot and axes should be drawn.
* @param edge the edge along which the axis is drawn.
*/
@Override
protected void selectAutoTickUnit(Graphics2D g2, Rectangle2D dataArea,
RectangleEdge edge) {
throw new UnsupportedOperationException();
}
/**
* Draws the axis on a Java 2D graphics device (such as the screen or a
* printer).
*
* @param g2 the graphics device (<code>null</code> not permitted).
* @param cursor the cursor location.
* @param plotArea the area within which the plot and axes should be drawn
* (<code>null</code> not permitted).
* @param dataArea the area within which the data should be drawn
* (<code>null</code> not permitted).
* @param edge the axis location (<code>null</code> not permitted).
* @param plotState collects information about the plot
* (<code>null</code> permitted).
*
* @return The axis state (never <code>null</code>).
*/
@Override
public AxisState draw(Graphics2D g2,
double cursor,
Rectangle2D plotArea,
Rectangle2D dataArea,
RectangleEdge edge,
PlotRenderingInfo plotState) {
AxisState info = new AxisState(cursor);
if (isVisible()) {
info = super.draw(g2, cursor, plotArea, dataArea, edge, plotState);
}
if (this.gridBandsVisible) {
drawGridBands(g2, plotArea, dataArea, edge, info.getTicks());
}
return info;
}
/**
* Draws the grid bands. Alternate bands are colored using
* <CODE>gridBandPaint</CODE> (<CODE>DEFAULT_GRID_BAND_PAINT</CODE> by
* default).
*
* @param g2 the graphics device.
* @param plotArea the area within which the chart should be drawn.
* @param dataArea the area within which the plot should be drawn (a
* subset of the drawArea).
* @param edge the axis location.
* @param ticks the ticks.
*/
protected void drawGridBands(Graphics2D g2, Rectangle2D plotArea,
Rectangle2D dataArea, RectangleEdge edge, List<ValueTick> ticks) {
Shape savedClip = g2.getClip();
g2.clip(dataArea);
if (RectangleEdge.isTopOrBottom(edge)) {
drawGridBandsHorizontal(g2, plotArea, dataArea, true, ticks);
}
else if (RectangleEdge.isLeftOrRight(edge)) {
drawGridBandsVertical(g2, plotArea, dataArea, true, ticks);
}
g2.setClip(savedClip);
}
/**
* Draws the grid bands for the axis when it is at the top or bottom of
* the plot.
*
* @param g2 the graphics device.
* @param plotArea the area within which the chart should be drawn.
* @param dataArea the area within which the plot should be drawn
* (a subset of the drawArea).
* @param firstGridBandIsDark True: the first grid band takes the
* color of <CODE>gridBandPaint</CODE>.
* False: the second grid band takes the
* color of <CODE>gridBandPaint</CODE>.
* @param ticks the ticks.
*/
protected void drawGridBandsHorizontal(Graphics2D g2, Rectangle2D plotArea,
Rectangle2D dataArea, boolean firstGridBandIsDark,
List<ValueTick> ticks) {
boolean currentGridBandIsDark = firstGridBandIsDark;
double yy = dataArea.getY();
double xx1, xx2;
//gets the outline stroke width of the plot
double outlineStrokeWidth;
if (getPlot().getOutlineStroke() != null) {
outlineStrokeWidth
= ((BasicStroke) getPlot().getOutlineStroke()).getLineWidth();
}
else {
outlineStrokeWidth = 1d;
}
for (ValueTick tick : ticks) {
xx1 = valueToJava2D(tick.getValue() - 0.5d, dataArea,
RectangleEdge.BOTTOM);
xx2 = valueToJava2D(tick.getValue() + 0.5d, dataArea,
RectangleEdge.BOTTOM);
if (currentGridBandIsDark) {
g2.setPaint(this.gridBandPaint);
} else {
g2.setPaint(this.gridBandAlternatePaint);
}
Rectangle2D band = new Rectangle2D.Double(xx1, yy + outlineStrokeWidth,
xx2 - xx1, dataArea.getMaxY() - yy - outlineStrokeWidth);
g2.fill(band);
currentGridBandIsDark = !currentGridBandIsDark;
}
g2.setPaintMode();
}
/**
* Draws the grid bands for the axis when it is at the top or bottom of
* the plot.
*
* @param g2 the graphics device.
* @param drawArea the area within which the chart should be drawn.
* @param plotArea the area within which the plot should be drawn (a
* subset of the drawArea).
* @param firstGridBandIsDark True: the first grid band takes the
* color of <CODE>gridBandPaint</CODE>.
* False: the second grid band takes the
* color of <CODE>gridBandPaint</CODE>.
* @param ticks a list of ticks.
*/
protected void drawGridBandsVertical(Graphics2D g2, Rectangle2D drawArea,
Rectangle2D plotArea, boolean firstGridBandIsDark,
List<ValueTick> ticks) {
boolean currentGridBandIsDark = firstGridBandIsDark;
double xx = plotArea.getX();
double yy1, yy2;
//gets the outline stroke width of the plot
double outlineStrokeWidth;
Stroke outlineStroke = getPlot().getOutlineStroke();
if (outlineStroke != null && outlineStroke instanceof BasicStroke) {
outlineStrokeWidth = ((BasicStroke) outlineStroke).getLineWidth();
}
else {
outlineStrokeWidth = 1d;
}
for (ValueTick tick : ticks) {
yy1 = valueToJava2D(tick.getValue() + 0.5d, plotArea,
RectangleEdge.LEFT);
yy2 = valueToJava2D(tick.getValue() - 0.5d, plotArea,
RectangleEdge.LEFT);
if (currentGridBandIsDark) {
g2.setPaint(this.gridBandPaint);
} else {
g2.setPaint(this.gridBandAlternatePaint);
}
Rectangle2D band = new Rectangle2D.Double(xx + outlineStrokeWidth, yy1,
plotArea.getMaxX() - xx - outlineStrokeWidth, yy2 - yy1);
g2.fill(band);
currentGridBandIsDark = !currentGridBandIsDark;
}
g2.setPaintMode();
}
/**
* Rescales the axis to ensure that all data is visible.
*/
@Override
protected void autoAdjustRange() {
Plot plot = getPlot();
if (plot == null) {
return; // no plot, no data
}
if (plot instanceof ValueAxisPlot) {
// ensure that all the symbols are displayed
double upper = this.symbols.size() - 1;
double lower = 0;
double range = upper - lower;
// ensure the autorange is at least <minRange> in size...
double minRange = getAutoRangeMinimumSize();
if (range < minRange) {
upper = (upper + lower + minRange) / 2;
lower = (upper + lower - minRange) / 2;
}
// this ensure that the grid bands will be displayed correctly.
double upperMargin = 0.5;
double lowerMargin = 0.5;
if (getAutoRangeIncludesZero()) {
if (getAutoRangeStickyZero()) {
if (upper <= 0.0) {
upper = 0.0;
}
else {
upper = upper + upperMargin;
}
if (lower >= 0.0) {
lower = 0.0;
}
else {
lower = lower - lowerMargin;
}
}
else {
upper = Math.max(0.0, upper + upperMargin);
lower = Math.min(0.0, lower - lowerMargin);
}
}
else {
if (getAutoRangeStickyZero()) {
if (upper <= 0.0) {
upper = Math.min(0.0, upper + upperMargin);
}
else {
upper = upper + upperMargin * range;
}
if (lower >= 0.0) {
lower = Math.max(0.0, lower - lowerMargin);
}
else {
lower = lower - lowerMargin;
}
}
else {
upper = upper + upperMargin;
lower = lower - lowerMargin;
}
}
setRange(new Range(lower, upper), false, false);
}
}
/**
* Calculates the positions of the tick labels for the axis, storing the
* results in the tick label list (ready for drawing).
*
* @param g2 the graphics device.
* @param state the axis state.
* @param dataArea the area in which the data should be drawn.
* @param edge the location of the axis.
*
* @return A list of ticks.
*/
@Override
public List<ValueTick> refreshTicks(Graphics2D g2, AxisState state,
Rectangle2D dataArea, RectangleEdge edge) {
List<ValueTick> ticks = null;
if (RectangleEdge.isTopOrBottom(edge)) {
ticks = refreshTicksHorizontal(g2, dataArea, edge);
}
else if (RectangleEdge.isLeftOrRight(edge)) {
ticks = refreshTicksVertical(g2, dataArea, edge);
}
return ticks;
}
/**
* Calculates the positions of the tick labels for the axis, storing the
* results in the tick label list (ready for drawing).
*
* @param g2 the graphics device.
* @param dataArea the area in which the data should be drawn.
* @param edge the location of the axis.
*
* @return The ticks.
*/
@Override
protected List<ValueTick> refreshTicksHorizontal(Graphics2D g2,
Rectangle2D dataArea, RectangleEdge edge) {
List<ValueTick> ticks = new java.util.ArrayList<ValueTick>();
Font tickLabelFont = getTickLabelFont();
g2.setFont(tickLabelFont);
double size = getTickUnit().getSize();
int count = calculateVisibleTickCount();
double lowestTickValue = calculateLowestVisibleTickValue();
double previousDrawnTickLabelPos = 0.0;
double previousDrawnTickLabelLength = 0.0;
if (count <= ValueAxis.MAXIMUM_TICK_COUNT) {
for (int i = 0; i < count; i++) {
double currentTickValue = lowestTickValue + (i * size);
double xx = valueToJava2D(currentTickValue, dataArea, edge);
String tickLabel;
NumberFormat formatter = getNumberFormatOverride();
if (formatter != null) {
tickLabel = formatter.format(currentTickValue);
}
else {
tickLabel = valueToString(currentTickValue);
}
// avoid to draw overlapping tick labels
Rectangle2D bounds = TextUtilities.getTextBounds(tickLabel, g2,
g2.getFontMetrics());
double tickLabelLength = isVerticalTickLabels()
? bounds.getHeight() : bounds.getWidth();
boolean tickLabelsOverlapping = false;
if (i > 0) {
double avgTickLabelLength = (previousDrawnTickLabelLength
+ tickLabelLength) / 2.0;
if (Math.abs(xx - previousDrawnTickLabelPos)
< avgTickLabelLength) {
tickLabelsOverlapping = true;
}
}
if (tickLabelsOverlapping) {
tickLabel = ""; // don't draw this tick label
}
else {
// remember these values for next comparison
previousDrawnTickLabelPos = xx;
previousDrawnTickLabelLength = tickLabelLength;
}
TextAnchor anchor;
TextAnchor rotationAnchor;
double angle = 0.0;
if (isVerticalTickLabels()) {
anchor = TextAnchor.CENTER_RIGHT;
rotationAnchor = TextAnchor.CENTER_RIGHT;
if (edge == RectangleEdge.TOP) {
angle = Math.PI / 2.0;
}
else {
angle = -Math.PI / 2.0;
}
}
else {
if (edge == RectangleEdge.TOP) {
anchor = TextAnchor.BOTTOM_CENTER;
rotationAnchor = TextAnchor.BOTTOM_CENTER;
}
else {
anchor = TextAnchor.TOP_CENTER;
rotationAnchor = TextAnchor.TOP_CENTER;
}
}
ticks.add(new NumberTick(currentTickValue,
tickLabel, anchor, rotationAnchor, angle));
}
}
return ticks;
}
/**
* Calculates the positions of the tick labels for the axis, storing the
* results in the tick label list (ready for drawing).
*
* @param g2 the graphics device.
* @param dataArea the area in which the plot should be drawn.
* @param edge the location of the axis.
*
* @return The ticks.
*/
@Override
protected List<ValueTick> refreshTicksVertical(Graphics2D g2,
Rectangle2D dataArea, RectangleEdge edge) {
List<ValueTick> ticks = new java.util.ArrayList<ValueTick>();
Font tickLabelFont = getTickLabelFont();
g2.setFont(tickLabelFont);
double size = getTickUnit().getSize();
int count = calculateVisibleTickCount();
double lowestTickValue = calculateLowestVisibleTickValue();
double previousDrawnTickLabelPos = 0.0;
double previousDrawnTickLabelLength = 0.0;
if (count <= ValueAxis.MAXIMUM_TICK_COUNT) {
for (int i = 0; i < count; i++) {
double currentTickValue = lowestTickValue + (i * size);
double yy = valueToJava2D(currentTickValue, dataArea, edge);
String tickLabel;
NumberFormat formatter = getNumberFormatOverride();
if (formatter != null) {
tickLabel = formatter.format(currentTickValue);
}
else {
tickLabel = valueToString(currentTickValue);
}
// avoid to draw overlapping tick labels
Rectangle2D bounds = TextUtilities.getTextBounds(tickLabel, g2,
g2.getFontMetrics());
double tickLabelLength = isVerticalTickLabels()
? bounds.getWidth() : bounds.getHeight();
boolean tickLabelsOverlapping = false;
if (i > 0) {
double avgTickLabelLength = (previousDrawnTickLabelLength
+ tickLabelLength) / 2.0;
if (Math.abs(yy - previousDrawnTickLabelPos)
< avgTickLabelLength) {
tickLabelsOverlapping = true;
}
}
if (tickLabelsOverlapping) {
tickLabel = ""; // don't draw this tick label
}
else {
// remember these values for next comparison
previousDrawnTickLabelPos = yy;
previousDrawnTickLabelLength = tickLabelLength;
}
TextAnchor anchor = null;
TextAnchor rotationAnchor = null;
double angle = 0.0;
if (isVerticalTickLabels()) {
anchor = TextAnchor.BOTTOM_CENTER;
rotationAnchor = TextAnchor.BOTTOM_CENTER;
if (edge == RectangleEdge.LEFT) {
angle = -Math.PI / 2.0;
}
else {
angle = Math.PI / 2.0;
}
}
else {
if (edge == RectangleEdge.LEFT) {
anchor = TextAnchor.CENTER_RIGHT;
rotationAnchor = TextAnchor.CENTER_RIGHT;
}
else {
anchor = TextAnchor.CENTER_LEFT;
rotationAnchor = TextAnchor.CENTER_LEFT;
}
}
ticks.add(new NumberTick(currentTickValue,
tickLabel, anchor, rotationAnchor, angle));
}
}
return ticks;
}
/**
* Converts a value to a string, using the list of symbols.
*
* @param value value to convert.
*
* @return The symbol.
*/
public String valueToString(double value) {
String strToReturn;
try {
strToReturn = this.symbols.get((int) value);
}
catch (IndexOutOfBoundsException ex) {
strToReturn = "";
}
return strToReturn;
}
/**
* Tests this axis 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 SymbolAxis)) {
return false;
}
SymbolAxis that = (SymbolAxis) obj;
if (!this.symbols.equals(that.symbols)) {
return false;
}
if (this.gridBandsVisible != that.gridBandsVisible) {
return false;
}
if (!PaintUtilities.equal(this.gridBandPaint, that.gridBandPaint)) {
return false;
}
if (!PaintUtilities.equal(this.gridBandAlternatePaint,
that.gridBandAlternatePaint)) {
return false;
}
return super.equals(obj);
}
/**
* Provides serialization support.
*
* @param stream the output stream.
*
* @throws IOException if there is an I/O error.
*/
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
SerialUtilities.writePaint(this.gridBandPaint, stream);
SerialUtilities.writePaint(this.gridBandAlternatePaint, 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.gridBandPaint = SerialUtilities.readPaint(stream);
this.gridBandAlternatePaint = SerialUtilities.readPaint(stream);
}
}
| 29,252 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
CompassFormat.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/axis/CompassFormat.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.]
*
* ------------------
* CompassFormat.java
* ------------------
* (C) Copyright 2003-2008, by Sylvain Vieujot and Contributors.
*
* Original Author: Sylvain Vieujot;
* Contributor(s): David Gilbert (for Object Refinery Limited);
*
* Changes
* -------
* 18-Feb-2004 : Version 1 contributed by Sylvain Vieujot (DG);
*
*/
package org.jfree.chart.axis;
import java.text.FieldPosition;
import java.text.NumberFormat;
import java.text.ParsePosition;
/**
* A formatter that displays numbers as directions.
*/
public class CompassFormat extends NumberFormat {
/** The directions. */
public final String[] directions;
/**
* Creates a new formatter using english identifiers.
*/
public CompassFormat() {
this("N", "E", "S", "W");
}
/**
* Creates a new formatter using the specified identifiers for
* the base wind directions.
*/
public CompassFormat(String n, String e, String s, String w) {
this(new String[] {
n, n + n + e, n + e, e + n + e, e, e + s + e, s + e, s + s + e, s,
s + s + w, s + w, w + s + w, w, w + n + w, n + w, n + n + w
});
}
/**
* Creates a new formatter using the specified identifiers.
*/
public CompassFormat(String[] directions) {
super();
if (directions == null) {
throw new IllegalArgumentException("directions must not be null");
} else if (directions.length != 16) {
throw new IllegalArgumentException("directions must contain exactly 16 elements");
}
this.directions = directions;
}
/**
* Returns a string representing the direction.
*
* @param direction the direction.
*
* @return A string.
*/
public String getDirectionCode(double direction) {
direction = direction % 360;
if (direction < 0.0) {
direction = direction + 360.0;
}
int index = ((int) Math.floor(direction / 11.25) + 1) / 2;
return directions[index];
}
/**
* Formats a number into the specified string buffer.
*
* @param number the number to format.
* @param toAppendTo the string buffer.
* @param pos the field position (ignored here).
*
* @return The string buffer.
*/
@Override
public StringBuffer format(double number, StringBuffer toAppendTo,
FieldPosition pos) {
return toAppendTo.append(getDirectionCode(number));
}
/**
* Formats a number into the specified string buffer.
*
* @param number the number to format.
* @param toAppendTo the string buffer.
* @param pos the field position (ignored here).
*
* @return The string buffer.
*/
@Override
public StringBuffer format(long number, StringBuffer toAppendTo,
FieldPosition pos) {
return toAppendTo.append(getDirectionCode(number));
}
/**
* This method returns <code>null</code> for all inputs. This class cannot
* be used for parsing.
*
* @param source the source string.
* @param parsePosition the parse position.
*
* @return <code>null</code>.
*/
@Override
public Number parse(String source, ParsePosition parsePosition) {
return null;
}
}
| 4,586 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
NumberAxis3D.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/axis/NumberAxis3D.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.]
*
* -----------------
* NumberAxis3D.java
* -----------------
* (C) Copyright 2001-2012, by Serge V. Grachov and Contributors.
*
* Original Author: Serge V. Grachov;
* Contributor(s): David Gilbert (for Object Refinery Limited);
* Jonathan Nash;
* Richard Atkinson;
* Tin Luu;
*
* Changes
* -------
* 31-Oct-2001 : Version 1 contributed by Serge V. Grachov (DG);
* 23-Nov-2001 : Overhauled auto tick unit code for all axes (DG);
* 12-Dec-2001 : Minor change due to grid lines bug fix (DG);
* 08-Jan-2002 : Added flag allowing the axis to be 'inverted'. That is, run
* from positive to negative. Added default values to
* constructors (DG);
* 16-Jan-2002 : Added an optional crosshair, based on the implementation by
* Jonathan Nash (DG);
* 25-Feb-2002 : Updated constructors for new autoRangeStickyZero flag (DG);
* 19-Apr-2002 : drawVerticalString() is now drawRotatedString() in
* RefineryUtilities (DG);
* 25-Jun-2002 : Removed redundant import (DG);
* 25-Jul-2002 : Changed order of parameters in ValueAxis constructor (DG);
* 06-Aug-2002 : Modified draw method to not draw axis label if label is empty
* String (RA);
* 05-Sep-2002 : Updated constructor for changes in the Axis class, and changed
* draw method to observe tickMarkPaint (DG);
* 22-Sep-2002 : Fixed errors reported by Checkstyle (DG);
* 08-Nov-2002 : Moved to new package com.jrefinery.chart.axis (DG);
* 20-Jan-2003 : Removed unnecessary constructors (DG);
* 26-Mar-2003 : Implemented Serializable (DG);
* 13-May-2003 : Merged HorizontalNumberAxis3D and VerticalNumberAxis3D (DG);
* 21-Aug-2003 : Updated draw() method signature (DG);
* 07-Nov-2003 : Modified refreshTicks method signature (DG);
* ------------- JFREECHART 1.0.x ---------------------------------------------
* 18-Jan-2006 : Fixed bug 1408904 (axis assumes CategoryPlot) (DG):
* 16-Apr-2009 : Changed axis line visibility default (DG);
* 17-Jun-2012 : Removed JCommon dependencies (DG);
*
*/
package org.jfree.chart.axis;
import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;
import java.io.Serializable;
import java.util.List;
import org.jfree.chart.Effect3D;
import org.jfree.chart.ui.RectangleEdge;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.Plot;
import org.jfree.chart.plot.PlotRenderingInfo;
import org.jfree.chart.renderer.category.CategoryItemRenderer;
/**
* A standard linear value axis with a 3D effect corresponding to the
* offset specified by some renderers.
*/
public class NumberAxis3D extends NumberAxis implements Serializable {
/** For serialization. */
private static final long serialVersionUID = -1790205852569123512L;
/**
* Default constructor.
*/
public NumberAxis3D() {
this(null);
}
/**
* Constructs a new axis.
*
* @param label the axis label (<code>null</code> permitted).
*/
public NumberAxis3D(String label) {
super(label);
}
/**
* Draws the axis on a Java 2D graphics device (such as the screen or a
* printer).
*
* @param g2 the graphics device.
* @param cursor the cursor.
* @param plotArea the area for drawing the axes and data.
* @param dataArea the area for drawing the data (a subset of the
* plotArea).
* @param edge the axis location.
* @param plotState collects information about the plot (<code>null</code>
* permitted).
*
* @return The updated cursor value.
*/
@Override
public AxisState draw(Graphics2D g2, double cursor, Rectangle2D plotArea,
Rectangle2D dataArea, RectangleEdge edge,
PlotRenderingInfo plotState) {
// if the axis is not visible, don't draw it...
if (!isVisible()) {
AxisState state = new AxisState(cursor);
// even though the axis is not visible, we need ticks for the
// gridlines...
List<ValueTick> ticks = refreshTicks(g2, state, dataArea, edge);
state.setTicks(ticks);
return state;
}
// calculate the adjusted data area taking into account the 3D effect...
double xOffset = 0.0;
double yOffset = 0.0;
Plot plot = getPlot();
if (plot instanceof CategoryPlot) {
CategoryPlot cp = (CategoryPlot) plot;
CategoryItemRenderer r = cp.getRenderer();
if (r instanceof Effect3D) {
Effect3D e3D = (Effect3D) r;
xOffset = e3D.getXOffset();
yOffset = e3D.getYOffset();
}
}
double adjustedX = dataArea.getMinX();
double adjustedY = dataArea.getMinY();
double adjustedW = dataArea.getWidth() - xOffset;
double adjustedH = dataArea.getHeight() - yOffset;
if (edge == RectangleEdge.LEFT || edge == RectangleEdge.BOTTOM) {
adjustedY += yOffset;
}
else if (edge == RectangleEdge.RIGHT || edge == RectangleEdge.TOP) {
adjustedX += xOffset;
}
Rectangle2D adjustedDataArea = new Rectangle2D.Double(adjustedX,
adjustedY, adjustedW, adjustedH);
// draw the tick marks and labels...
AxisState info = drawTickMarksAndLabels(g2, cursor, plotArea,
adjustedDataArea, edge);
// draw the axis label...
info = drawLabel(getLabel(), g2, plotArea, dataArea, edge, info);
return info;
}
}
| 6,857 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
Axis.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/axis/Axis.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.]
*
* ---------
* Axis.java
* ---------
* (C) Copyright 2000-2013, by Object Refinery Limited and Contributors.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): Bill Kelemen;
* Nicolas Brodu;
* Peter Kolb (patches 1934255 and 2603321);
* Andrew Mickish (patch 1870189);
*
* Changes
* -------
* 21-Aug-2001 : Added standard header, fixed DOS encoding problem (DG);
* 18-Sep-2001 : Updated header (DG);
* 07-Nov-2001 : Allow null axis labels (DG);
* : Added default font values (DG);
* 13-Nov-2001 : Modified the setPlot() method to check compatibility between
* the axis and the plot (DG);
* 30-Nov-2001 : Changed default font from "Arial" --> "SansSerif" (DG);
* 06-Dec-2001 : Allow null in setPlot() method (BK);
* 06-Mar-2002 : Added AxisConstants interface (DG);
* 23-Apr-2002 : Added a visible property. Moved drawVerticalString to
* RefineryUtilities. Added fixedDimension property for use in
* combined plots (DG);
* 25-Jun-2002 : Removed unnecessary imports (DG);
* 05-Sep-2002 : Added attribute for tick mark paint (DG);
* 18-Sep-2002 : Fixed errors reported by Checkstyle (DG);
* 07-Nov-2002 : Added attributes to control the inside and outside length of
* the tick marks (DG);
* 08-Nov-2002 : Moved to new package com.jrefinery.chart.axis (DG);
* 18-Nov-2002 : Added axis location to refreshTicks() parameters (DG);
* 15-Jan-2003 : Removed monolithic constructor (DG);
* 17-Jan-2003 : Moved plot classes to separate package (DG);
* 26-Mar-2003 : Implemented Serializable (DG);
* 03-Jul-2003 : Modified reserveSpace method (DG);
* 13-Aug-2003 : Implemented Cloneable (DG);
* 11-Sep-2003 : Took care of listeners while cloning (NB);
* 29-Oct-2003 : Added workaround for font alignment in PDF output (DG);
* 06-Nov-2003 : Modified refreshTicks() signature (DG);
* 06-Jan-2004 : Added axis line attributes (DG);
* 16-Mar-2004 : Added plot state to draw() method (DG);
* 07-Apr-2004 : Modified text bounds calculation (DG);
* 18-May-2004 : Eliminated AxisConstants.java (DG);
* 30-Sep-2004 : Moved drawRotatedString() from RefineryUtilities -->
* TextUtilities (DG);
* 04-Oct-2004 : Modified getLabelEnclosure() method to treat an empty String
* the same way as a null string - see bug 1026521 (DG);
* 21-Apr-2005 : Replaced Insets with RectangleInsets (DG);
* 26-Apr-2005 : Removed LOGGER (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 ---------------------------------------------
* 22-Aug-2006 : API doc updates (DG);
* 06-Jun-2008 : Added setTickLabelInsets(RectangleInsets, boolean) (DG);
* 25-Sep-2008 : Added minor tick support, see patch 1934255 by Peter Kolb (DG);
* 26-Sep-2008 : Added fireChangeEvent() method (DG);
* 19-Mar-2009 : Added entity support - see patch 2603321 by Peter Kolb (DG);
* 16-Jun-2012 : Removed JCommon dependencies (DG);
*
*/
package org.jfree.chart.axis;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.Shape;
import java.awt.Stroke;
import java.awt.font.TextAttribute;
import java.awt.font.TextLayout;
import java.awt.geom.AffineTransform;
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.util.Arrays;
import java.util.EventListener;
import java.util.List;
import javax.swing.event.EventListenerList;
import org.jfree.chart.ui.RectangleEdge;
import org.jfree.chart.ui.RectangleInsets;
import org.jfree.chart.ui.TextAnchor;
import org.jfree.chart.util.ObjectUtilities;
import org.jfree.chart.util.PaintUtilities;
import org.jfree.chart.entity.AxisEntity;
import org.jfree.chart.entity.EntityCollection;
import org.jfree.chart.event.AxisChangeEvent;
import org.jfree.chart.event.AxisChangeListener;
import org.jfree.chart.plot.Plot;
import org.jfree.chart.plot.PlotRenderingInfo;
import org.jfree.chart.text.TextUtilities;
import org.jfree.chart.util.AttributedStringUtilities;
import org.jfree.chart.util.ParamChecks;
import org.jfree.chart.util.SerialUtilities;
/**
* The base class for all axes in JFreeChart. Subclasses are divided into
* those that display values ({@link ValueAxis}) and those that display
* categories ({@link CategoryAxis}).
*/
public abstract class Axis implements Cloneable, Serializable {
/** For serialization. */
private static final long serialVersionUID = 7719289504573298271L;
/** The default axis visibility. */
public static final boolean DEFAULT_AXIS_VISIBLE = true;
/** The default axis label font. */
public static final Font DEFAULT_AXIS_LABEL_FONT = new Font(
"SansSerif", Font.PLAIN, 12);
/** The default axis label paint. */
public static final Paint DEFAULT_AXIS_LABEL_PAINT = Color.BLACK;
/** The default axis label insets. */
public static final RectangleInsets DEFAULT_AXIS_LABEL_INSETS
= new RectangleInsets(3.0, 3.0, 3.0, 3.0);
/** The default axis line paint. */
public static final Paint DEFAULT_AXIS_LINE_PAINT = Color.GRAY;
/** The default axis line stroke. */
public static final Stroke DEFAULT_AXIS_LINE_STROKE = new BasicStroke(1.0f);
/** The default tick labels visibility. */
public static final boolean DEFAULT_TICK_LABELS_VISIBLE = true;
/** The default tick label font. */
public static final Font DEFAULT_TICK_LABEL_FONT = new Font("SansSerif",
Font.PLAIN, 10);
/** The default tick label paint. */
public static final Paint DEFAULT_TICK_LABEL_PAINT = Color.BLACK;
/** The default tick label insets. */
public static final RectangleInsets DEFAULT_TICK_LABEL_INSETS
= new RectangleInsets(2.0, 4.0, 2.0, 4.0);
/** The default tick marks visible. */
public static final boolean DEFAULT_TICK_MARKS_VISIBLE = true;
/** The default tick stroke. */
public static final Stroke DEFAULT_TICK_MARK_STROKE = new BasicStroke(1);
/** The default tick paint. */
public static final Paint DEFAULT_TICK_MARK_PAINT = Color.GRAY;
/** The default tick mark inside length. */
public static final float DEFAULT_TICK_MARK_INSIDE_LENGTH = 0.0f;
/** The default tick mark outside length. */
public static final float DEFAULT_TICK_MARK_OUTSIDE_LENGTH = 2.0f;
/** A flag indicating whether or not the axis is visible. */
private boolean visible;
/** The label for the axis. */
private transient AttributedString label;
/** The font for displaying the axis label. */
private Font labelFont;
/** The paint for drawing the axis label. */
private transient Paint labelPaint;
/** The insets for the axis label. */
private RectangleInsets labelInsets;
/** The label angle. */
private double labelAngle;
/** The axis label location. */
private AxisLabelLocation labelLocation;
/** A flag that controls whether or not the axis line is visible. */
private boolean axisLineVisible;
/** The stroke used for the axis line. */
private transient Stroke axisLineStroke;
/** The paint used for the axis line. */
private transient Paint axisLinePaint;
/**
* A flag that indicates whether or not tick labels are visible for the
* axis.
*/
private boolean tickLabelsVisible;
/** The font used to display the tick labels. */
private Font tickLabelFont;
/** The color used to display the tick labels. */
private transient Paint tickLabelPaint;
/** The blank space around each tick label. */
private RectangleInsets tickLabelInsets;
/**
* A flag that indicates whether or not major tick marks are visible for
* the axis.
*/
private boolean tickMarksVisible;
/**
* The length of the major tick mark inside the data area (zero
* permitted).
*/
private float tickMarkInsideLength;
/**
* The length of the major tick mark outside the data area (zero
* permitted).
*/
private float tickMarkOutsideLength;
/**
* A flag that indicates whether or not minor tick marks are visible for the
* axis.
*
* @since 1.0.12
*/
private boolean minorTickMarksVisible;
/**
* The length of the minor tick mark inside the data area (zero permitted).
*
* @since 1.0.12
*/
private float minorTickMarkInsideLength;
/**
* The length of the minor tick mark outside the data area (zero permitted).
*
* @since 1.0.12
*/
private float minorTickMarkOutsideLength;
/** The stroke used to draw tick marks. */
private transient Stroke tickMarkStroke;
/** The paint used to draw tick marks. */
private transient Paint tickMarkPaint;
/** The fixed (horizontal or vertical) dimension for the axis. */
private double fixedDimension;
/**
* A reference back to the plot that the axis is assigned to (can be
* <code>null</code>).
*/
private transient Plot plot;
/** Storage for registered listeners. */
private transient EventListenerList listenerList;
/**
* Constructs an axis, using default values where necessary.
*
* @param label the axis label (<code>null</code> permitted).
*/
protected Axis(String label) {
this.visible = DEFAULT_AXIS_VISIBLE;
this.labelFont = DEFAULT_AXIS_LABEL_FONT;
this.labelPaint = DEFAULT_AXIS_LABEL_PAINT;
if (label != null) {
AttributedString s = new AttributedString(label);
s.addAttributes(this.labelFont.getAttributes(), 0, label.length());
this.label = s;
}
this.labelInsets = DEFAULT_AXIS_LABEL_INSETS;
this.labelAngle = 0.0;
this.labelLocation = AxisLabelLocation.MIDDLE;
this.axisLineVisible = true;
this.axisLinePaint = DEFAULT_AXIS_LINE_PAINT;
this.axisLineStroke = DEFAULT_AXIS_LINE_STROKE;
this.tickLabelsVisible = DEFAULT_TICK_LABELS_VISIBLE;
this.tickLabelFont = DEFAULT_TICK_LABEL_FONT;
this.tickLabelPaint = DEFAULT_TICK_LABEL_PAINT;
this.tickLabelInsets = DEFAULT_TICK_LABEL_INSETS;
this.tickMarksVisible = DEFAULT_TICK_MARKS_VISIBLE;
this.tickMarkStroke = DEFAULT_TICK_MARK_STROKE;
this.tickMarkPaint = DEFAULT_TICK_MARK_PAINT;
this.tickMarkInsideLength = DEFAULT_TICK_MARK_INSIDE_LENGTH;
this.tickMarkOutsideLength = DEFAULT_TICK_MARK_OUTSIDE_LENGTH;
this.minorTickMarksVisible = false;
this.minorTickMarkInsideLength = 0.0f;
this.minorTickMarkOutsideLength = 2.0f;
this.plot = null;
this.listenerList = new EventListenerList();
}
/**
* Returns <code>true</code> if the axis is visible, and
* <code>false</code> otherwise.
*
* @return A boolean.
*
* @see #setVisible(boolean)
*/
public boolean isVisible() {
return this.visible;
}
/**
* Sets a flag that controls whether or not the axis is visible and sends
* an {@link AxisChangeEvent} to all registered listeners.
*
* @param flag the flag.
*
* @see #isVisible()
*/
public void setVisible(boolean flag) {
if (flag != this.visible) {
this.visible = flag;
fireChangeEvent();
}
}
/**
* Returns the label for the axis (the returned value is a copy, so
* modifying it will not impact the state of the axis).
*
* @return The label for the axis (<code>null</code> possible).
*
* @see #getLabelFont()
* @see #getLabelPaint()
* @see #setLabel(String)
*/
public AttributedString getLabel() {
if (this.label != null) {
return new AttributedString(this.label.getIterator());
} else {
return null;
}
}
/**
* Sets the label for the axis and sends an {@link AxisChangeEvent} to all
* registered listeners.
*
* @param label the new label (<code>null</code> permitted).
*
* @see #getLabel()
* @see #setLabelFont(Font)
* @see #setLabelPaint(Paint)
*/
public void setLabel(AttributedString label) {
if (label != null) {
this.label = new AttributedString(label.getIterator());
} else {
this.label = null;
}
fireChangeEvent();
}
/**
* Sets the label for the axis and sends an {@link AxisChangeEvent} to
* all registered listeners. Note that this is a convenience method that
* converts the <code>String</code> argument to an
* <code>AttributedString</code> (which is the actual type for the label).
*
* @param label the label (<code>null</code> permitted).
*
* @see #setLabel(java.text.AttributedString)
*/
public void setLabel(String label) {
this.label = createLabel(label);
fireChangeEvent();
}
/**
* Creates and returns an <code>AttributedString</code> with the specified
* text and the labelFont attributes applied.
*
* @param label the label (<code>null</code> permitted).
*
* @return An attributed string or <code>null</code>.
*/
public AttributedString createLabel(String label) {
if (label == null) {
return null;
}
AttributedString s = new AttributedString(label);
s.addAttributes(this.labelFont.getAttributes(), 0, label.length());
return s;
}
/**
* Returns the font for the axis label.
*
* @return The font (never <code>null</code>).
*
* @see #setLabelFont(Font)
*/
public Font getLabelFont() {
return this.labelFont;
}
/**
* Sets the font for the axis label and sends an {@link AxisChangeEvent}
* to all registered listeners.
*
* @param font the font (<code>null</code> not permitted).
*
* @see #getLabelFont()
*/
public void setLabelFont(Font font) {
ParamChecks.nullNotPermitted(font, "font");
this.labelFont = font;
if (this.label != null) {
this.label.addAttributes(font.getAttributes(), 0,
this.label.getIterator().getEndIndex());
}
fireChangeEvent();
}
/**
* Returns the color/shade used to draw the axis label.
*
* @return The paint (never <code>null</code>).
*
* @see #setLabelPaint(Paint)
*/
public Paint getLabelPaint() {
return this.labelPaint;
}
/**
* Sets the paint used to draw the axis label and sends an
* {@link AxisChangeEvent} to all registered listeners.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getLabelPaint()
*/
public void setLabelPaint(Paint paint) {
ParamChecks.nullNotPermitted(paint, "paint");
this.labelPaint = paint;
fireChangeEvent();
}
/**
* Returns the insets for the label (that is, the amount of blank space
* that should be left around the label).
*
* @return The label insets (never <code>null</code>).
*
* @see #setLabelInsets(RectangleInsets)
*/
public RectangleInsets getLabelInsets() {
return this.labelInsets;
}
/**
* Sets the insets for the axis label, and sends an {@link AxisChangeEvent}
* to all registered listeners.
*
* @param insets the insets (<code>null</code> not permitted).
*
* @see #getLabelInsets()
*/
public void setLabelInsets(RectangleInsets insets) {
setLabelInsets(insets, true);
}
/**
* Sets the insets for the axis label, and sends an {@link AxisChangeEvent}
* to all registered listeners.
*
* @param insets the insets (<code>null</code> not permitted).
* @param notify notify listeners?
*
* @since 1.0.10
*/
public void setLabelInsets(RectangleInsets insets, boolean notify) {
ParamChecks.nullNotPermitted(insets, "insets");
if (!insets.equals(this.labelInsets)) {
this.labelInsets = insets;
if (notify) {
fireChangeEvent();
}
}
}
/**
* Returns the angle of the axis label.
*
* @return The angle (in radians).
*
* @see #setLabelAngle(double)
*/
public double getLabelAngle() {
return this.labelAngle;
}
/**
* Sets the angle for the label and sends an {@link AxisChangeEvent} to all
* registered listeners.
*
* @param angle the angle (in radians).
*
* @see #getLabelAngle()
*/
public void setLabelAngle(double angle) {
this.labelAngle = angle;
fireChangeEvent();
}
/**
* Returns the location of the axis label. The default is
* {@link AxisLabelLocation#MIDDLE}.
*
* @return The location of the axis label (never <code>null</code>).
*
* @since 1.0.16
*/
public AxisLabelLocation getLabelLocation() {
return this.labelLocation;
}
/**
* Sets the axis label location and sends an {@link AxisChangeEvent} to
* all registered listeners.
*
* @param location the new location (<code>null</code> not permitted).
*
* @since 1.0.16
*/
public void setLabelLocation(AxisLabelLocation location) {
ParamChecks.nullNotPermitted(location, "location");
this.labelLocation = location;
fireChangeEvent();
}
/**
* A flag that controls whether or not the axis line is drawn.
*
* @return A boolean.
*
* @see #getAxisLinePaint()
* @see #getAxisLineStroke()
* @see #setAxisLineVisible(boolean)
*/
public boolean isAxisLineVisible() {
return this.axisLineVisible;
}
/**
* Sets a flag that controls whether or not the axis line is visible and
* sends an {@link AxisChangeEvent} to all registered listeners.
*
* @param visible the flag.
*
* @see #isAxisLineVisible()
* @see #setAxisLinePaint(Paint)
* @see #setAxisLineStroke(Stroke)
*/
public void setAxisLineVisible(boolean visible) {
this.axisLineVisible = visible;
fireChangeEvent();
}
/**
* Returns the paint used to draw the axis line.
*
* @return The paint (never <code>null</code>).
*
* @see #setAxisLinePaint(Paint)
*/
public Paint getAxisLinePaint() {
return this.axisLinePaint;
}
/**
* Sets the paint used to draw the axis line and sends an
* {@link AxisChangeEvent} to all registered listeners.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getAxisLinePaint()
*/
public void setAxisLinePaint(Paint paint) {
ParamChecks.nullNotPermitted(paint, "paint");
this.axisLinePaint = paint;
fireChangeEvent();
}
/**
* Returns the stroke used to draw the axis line.
*
* @return The stroke (never <code>null</code>).
*
* @see #setAxisLineStroke(Stroke)
*/
public Stroke getAxisLineStroke() {
return this.axisLineStroke;
}
/**
* Sets the stroke used to draw the axis line and sends an
* {@link AxisChangeEvent} to all registered listeners.
*
* @param stroke the stroke (<code>null</code> not permitted).
*
* @see #getAxisLineStroke()
*/
public void setAxisLineStroke(Stroke stroke) {
ParamChecks.nullNotPermitted(stroke, "stroke");
this.axisLineStroke = stroke;
fireChangeEvent();
}
/**
* Returns a flag indicating whether or not the tick labels are visible.
*
* @return The flag.
*
* @see #getTickLabelFont()
* @see #getTickLabelPaint()
* @see #setTickLabelsVisible(boolean)
*/
public boolean isTickLabelsVisible() {
return this.tickLabelsVisible;
}
/**
* Sets the flag that determines whether or not the tick labels are
* visible and sends an {@link AxisChangeEvent} to all registered
* listeners.
*
* @param flag the flag.
*
* @see #isTickLabelsVisible()
* @see #setTickLabelFont(Font)
* @see #setTickLabelPaint(Paint)
*/
public void setTickLabelsVisible(boolean flag) {
if (flag != this.tickLabelsVisible) {
this.tickLabelsVisible = flag;
fireChangeEvent();
}
}
/**
* Returns the flag that indicates whether or not the minor tick marks are
* showing.
*
* @return The flag that indicates whether or not the minor tick marks are
* showing.
*
* @see #setMinorTickMarksVisible(boolean)
*
* @since 1.0.12
*/
public boolean isMinorTickMarksVisible() {
return this.minorTickMarksVisible;
}
/**
* Sets the flag that indicates whether or not the minor tick marks are
* showing and sends an {@link AxisChangeEvent} to all registered
* listeners.
*
* @param flag the flag.
*
* @see #isMinorTickMarksVisible()
*
* @since 1.0.12
*/
public void setMinorTickMarksVisible(boolean flag) {
if (flag != this.minorTickMarksVisible) {
this.minorTickMarksVisible = flag;
fireChangeEvent();
}
}
/**
* Returns the font used for the tick labels (if showing).
*
* @return The font (never <code>null</code>).
*
* @see #setTickLabelFont(Font)
*/
public Font getTickLabelFont() {
return this.tickLabelFont;
}
/**
* Sets the font for the tick labels and sends an {@link AxisChangeEvent}
* to all registered listeners.
*
* @param font the font (<code>null</code> not allowed).
*
* @see #getTickLabelFont()
*/
public void setTickLabelFont(Font font) {
ParamChecks.nullNotPermitted(font, "font");
if (!this.tickLabelFont.equals(font)) {
this.tickLabelFont = font;
fireChangeEvent();
}
}
/**
* Returns the color/shade used for the tick labels.
*
* @return The paint used for the tick labels.
*
* @see #setTickLabelPaint(Paint)
*/
public Paint getTickLabelPaint() {
return this.tickLabelPaint;
}
/**
* Sets the paint used to draw tick labels (if they are showing) and
* sends an {@link AxisChangeEvent} to all registered listeners.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getTickLabelPaint()
*/
public void setTickLabelPaint(Paint paint) {
ParamChecks.nullNotPermitted(paint, "paint");
this.tickLabelPaint = paint;
fireChangeEvent();
}
/**
* Returns the insets for the tick labels.
*
* @return The insets (never <code>null</code>).
*
* @see #setTickLabelInsets(RectangleInsets)
*/
public RectangleInsets getTickLabelInsets() {
return this.tickLabelInsets;
}
/**
* Sets the insets for the tick labels and sends an {@link AxisChangeEvent}
* to all registered listeners.
*
* @param insets the insets (<code>null</code> not permitted).
*
* @see #getTickLabelInsets()
*/
public void setTickLabelInsets(RectangleInsets insets) {
ParamChecks.nullNotPermitted(insets, "insets");
if (!this.tickLabelInsets.equals(insets)) {
this.tickLabelInsets = insets;
fireChangeEvent();
}
}
/**
* Returns the flag that indicates whether or not the tick marks are
* showing.
*
* @return The flag that indicates whether or not the tick marks are
* showing.
*
* @see #setTickMarksVisible(boolean)
*/
public boolean isTickMarksVisible() {
return this.tickMarksVisible;
}
/**
* Sets the flag that indicates whether or not the tick marks are showing
* and sends an {@link AxisChangeEvent} to all registered listeners.
*
* @param flag the flag.
*
* @see #isTickMarksVisible()
*/
public void setTickMarksVisible(boolean flag) {
if (flag != this.tickMarksVisible) {
this.tickMarksVisible = flag;
fireChangeEvent();
}
}
/**
* Returns the inside length of the tick marks.
*
* @return The length.
*
* @see #getTickMarkOutsideLength()
* @see #setTickMarkInsideLength(float)
*/
public float getTickMarkInsideLength() {
return this.tickMarkInsideLength;
}
/**
* Sets the inside length of the tick marks and sends
* an {@link AxisChangeEvent} to all registered listeners.
*
* @param length the new length.
*
* @see #getTickMarkInsideLength()
*/
public void setTickMarkInsideLength(float length) {
this.tickMarkInsideLength = length;
fireChangeEvent();
}
/**
* Returns the outside length of the tick marks.
*
* @return The length.
*
* @see #getTickMarkInsideLength()
* @see #setTickMarkOutsideLength(float)
*/
public float getTickMarkOutsideLength() {
return this.tickMarkOutsideLength;
}
/**
* Sets the outside length of the tick marks and sends
* an {@link AxisChangeEvent} to all registered listeners.
*
* @param length the new length.
*
* @see #getTickMarkInsideLength()
*/
public void setTickMarkOutsideLength(float length) {
this.tickMarkOutsideLength = length;
fireChangeEvent();
}
/**
* Returns the stroke used to draw tick marks.
*
* @return The stroke (never <code>null</code>).
*
* @see #setTickMarkStroke(Stroke)
*/
public Stroke getTickMarkStroke() {
return this.tickMarkStroke;
}
/**
* Sets the stroke used to draw tick marks and sends
* an {@link AxisChangeEvent} to all registered listeners.
*
* @param stroke the stroke (<code>null</code> not permitted).
*
* @see #getTickMarkStroke()
*/
public void setTickMarkStroke(Stroke stroke) {
ParamChecks.nullNotPermitted(stroke, "stroke");
if (!this.tickMarkStroke.equals(stroke)) {
this.tickMarkStroke = stroke;
fireChangeEvent();
}
}
/**
* Returns the paint used to draw tick marks (if they are showing).
*
* @return The paint (never <code>null</code>).
*
* @see #setTickMarkPaint(Paint)
*/
public Paint getTickMarkPaint() {
return this.tickMarkPaint;
}
/**
* Sets the paint used to draw tick marks and sends an
* {@link AxisChangeEvent} to all registered listeners.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getTickMarkPaint()
*/
public void setTickMarkPaint(Paint paint) {
ParamChecks.nullNotPermitted(paint, "paint");
this.tickMarkPaint = paint;
fireChangeEvent();
}
/**
* Returns the inside length of the minor tick marks.
*
* @return The length.
*
* @see #getMinorTickMarkOutsideLength()
* @see #setMinorTickMarkInsideLength(float)
*
* @since 1.0.12
*/
public float getMinorTickMarkInsideLength() {
return this.minorTickMarkInsideLength;
}
/**
* Sets the inside length of the minor tick marks and sends
* an {@link AxisChangeEvent} to all registered listeners.
*
* @param length the new length.
*
* @see #getMinorTickMarkInsideLength()
*
* @since 1.0.12
*/
public void setMinorTickMarkInsideLength(float length) {
this.minorTickMarkInsideLength = length;
fireChangeEvent();
}
/**
* Returns the outside length of the minor tick marks.
*
* @return The length.
*
* @see #getMinorTickMarkInsideLength()
* @see #setMinorTickMarkOutsideLength(float)
*
* @since 1.0.12
*/
public float getMinorTickMarkOutsideLength() {
return this.minorTickMarkOutsideLength;
}
/**
* Sets the outside length of the minor tick marks and sends
* an {@link AxisChangeEvent} to all registered listeners.
*
* @param length the new length.
*
* @see #getMinorTickMarkInsideLength()
*
* @since 1.0.12
*/
public void setMinorTickMarkOutsideLength(float length) {
this.minorTickMarkOutsideLength = length;
fireChangeEvent();
}
/**
* Returns the plot that the axis is assigned to. This method will return
* <code>null</code> if the axis is not currently assigned to a plot.
*
* @return The plot that the axis is assigned to (possibly
* <code>null</code>).
*
* @see #setPlot(Plot)
*/
public Plot getPlot() {
return this.plot;
}
/**
* Sets a reference to the plot that the axis is assigned to.
* <P>
* This method is used internally, you shouldn't need to call it yourself.
*
* @param plot the plot.
*
* @see #getPlot()
*/
public void setPlot(Plot plot) {
this.plot = plot;
configure();
}
/**
* Returns the fixed dimension for the axis.
*
* @return The fixed dimension.
*
* @see #setFixedDimension(double)
*/
public double getFixedDimension() {
return this.fixedDimension;
}
/**
* Sets the fixed dimension for the axis.
* <P>
* This is used when combining more than one plot on a chart. In this case,
* there may be several axes that need to have the same height or width so
* that they are aligned. This method is used to fix a dimension for the
* axis (the context determines whether the dimension is horizontal or
* vertical).
*
* @param dimension the fixed dimension.
*
* @see #getFixedDimension()
*/
public void setFixedDimension(double dimension) {
this.fixedDimension = dimension;
}
/**
* Configures the axis to work with the current plot. Override this method
* to perform any special processing (such as auto-rescaling).
*/
public abstract void configure();
/**
* Estimates the space (height or width) required to draw the axis.
*
* @param g2 the graphics device.
* @param plot the plot that the axis belongs to.
* @param plotArea the area within which the plot (including axes) should
* be drawn.
* @param edge the axis location.
* @param space space already reserved.
*
* @return The space required to draw the axis (including pre-reserved
* space).
*/
public abstract AxisSpace reserveSpace(Graphics2D g2, Plot plot,
Rectangle2D plotArea, RectangleEdge edge, AxisSpace space);
/**
* Draws the axis on a Java 2D graphics device (such as the screen or a
* printer).
*
* @param g2 the graphics device (<code>null</code> not permitted).
* @param cursor the cursor location (determines where to draw the axis).
* @param plotArea the area within which the axes and plot should be drawn.
* @param dataArea the area within which the data should be drawn.
* @param edge the axis location (<code>null</code> not permitted).
* @param plotState collects information about the plot
* (<code>null</code> permitted).
*
* @return The axis state (never <code>null</code>).
*/
public abstract AxisState draw(Graphics2D g2, double cursor,
Rectangle2D plotArea, Rectangle2D dataArea, RectangleEdge edge,
PlotRenderingInfo plotState);
/**
* Calculates the positions of the ticks for the axis, storing the results
* in the tick list (ready for drawing).
*
* @param g2 the graphics device.
* @param state the axis state.
* @param dataArea the area inside the axes.
* @param edge the edge on which the axis is located.
*
* @return The list of ticks.
*/
public abstract List<? extends Tick> refreshTicks(Graphics2D g2,
AxisState state, Rectangle2D dataArea, RectangleEdge edge);
/**
* Created an entity for the axis.
*
* @param cursor the initial cursor value.
* @param state the axis state after completion of the drawing with a
* possibly updated cursor position.
* @param dataArea the data area.
* @param edge the edge.
* @param plotState the PlotRenderingInfo from which a reference to the
* entity collection can be obtained.
*
* @since 1.0.13
*/
protected void createAndAddEntity(double cursor, AxisState state,
Rectangle2D dataArea, RectangleEdge edge,
PlotRenderingInfo plotState) {
if (plotState == null || plotState.getOwner() == null) {
return; // no need to create entity if we can´t save it anyways...
}
Rectangle2D hotspot = null;
if (edge.equals(RectangleEdge.TOP)) {
hotspot = new Rectangle2D.Double(dataArea.getX(),
state.getCursor(), dataArea.getWidth(),
cursor - state.getCursor());
}
else if (edge.equals(RectangleEdge.BOTTOM)) {
hotspot = new Rectangle2D.Double(dataArea.getX(), cursor,
dataArea.getWidth(), state.getCursor() - cursor);
}
else if (edge.equals(RectangleEdge.LEFT)) {
hotspot = new Rectangle2D.Double(state.getCursor(),
dataArea.getY(), cursor - state.getCursor(),
dataArea.getHeight());
}
else if (edge.equals(RectangleEdge.RIGHT)) {
hotspot = new Rectangle2D.Double(cursor, dataArea.getY(),
state.getCursor() - cursor, dataArea.getHeight());
}
EntityCollection e = plotState.getOwner().getEntityCollection();
if (e != null) {
e.add(new AxisEntity(hotspot, this));
}
}
/**
* Registers an object for notification of changes to the axis.
*
* @param listener the object that is being registered.
*
* @see #removeChangeListener(AxisChangeListener)
*/
public void addChangeListener(AxisChangeListener listener) {
this.listenerList.add(AxisChangeListener.class, listener);
}
/**
* Deregisters an object for notification of changes to the axis.
*
* @param listener the object to deregister.
*
* @see #addChangeListener(AxisChangeListener)
*/
public void removeChangeListener(AxisChangeListener listener) {
this.listenerList.remove(AxisChangeListener.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);
}
/**
* Notifies all registered listeners that the axis has changed.
* The AxisChangeEvent provides information about the change.
*
* @param event information about the change to the axis.
*/
protected void notifyListeners(AxisChangeEvent event) {
Object[] listeners = this.listenerList.getListenerList();
for (int i = listeners.length - 2; i >= 0; i -= 2) {
if (listeners[i] == AxisChangeListener.class) {
((AxisChangeListener) listeners[i + 1]).axisChanged(event);
}
}
}
/**
* Sends an {@link AxisChangeEvent} to all registered listeners.
*
* @since 1.0.12
*/
protected void fireChangeEvent() {
notifyListeners(new AxisChangeEvent(this));
}
/**
* Returns a rectangle that encloses the axis label. This is typically
* used for layout purposes (it gives the maximum dimensions of the label).
*
* @param g2 the graphics device.
* @param edge the edge of the plot area along which the axis is measuring.
*
* @return The enclosing rectangle.
*/
protected Rectangle2D getLabelEnclosure(Graphics2D g2, RectangleEdge edge) {
Rectangle2D result = new Rectangle2D.Double();
AttributedString axisLabel = getLabel();
if (axisLabel != null) {
TextLayout layout = new TextLayout(axisLabel.getIterator(),
g2.getFontRenderContext());
Rectangle2D bounds = layout.getBounds();
RectangleInsets insets = getLabelInsets();
bounds = insets.createOutsetRectangle(bounds);
double angle = getLabelAngle();
if (edge == RectangleEdge.LEFT || edge == RectangleEdge.RIGHT) {
angle = angle - Math.PI / 2.0;
}
double x = bounds.getCenterX();
double y = bounds.getCenterY();
AffineTransform transformer
= AffineTransform.getRotateInstance(angle, x, y);
Shape labelBounds = transformer.createTransformedShape(bounds);
result = labelBounds.getBounds2D();
}
return result;
}
/**
* Draws the axis label.
*
* @param label the label text.
* @param g2 the graphics device.
* @param plotArea the plot area.
* @param dataArea the area inside the axes.
* @param edge the location of the axis.
* @param state the axis state (<code>null</code> not permitted).
*
* @return Information about the axis.
*/
protected AxisState drawLabel(AttributedString label, Graphics2D g2,
Rectangle2D plotArea, Rectangle2D dataArea, RectangleEdge edge,
AxisState state) {
// it is unlikely that 'state' will be null, but check anyway...
ParamChecks.nullNotPermitted(state, "state");
if (label == null) {
return state;
}
RectangleInsets insets = getLabelInsets();
g2.setFont(getLabelFont());
g2.setPaint(getLabelPaint());
TextLayout layout = new TextLayout(label.getIterator(),
g2.getFontRenderContext());
Rectangle2D labelBounds = layout.getBounds();
if (edge == RectangleEdge.TOP) {
AffineTransform t = AffineTransform.getRotateInstance(
getLabelAngle(), labelBounds.getCenterX(),
labelBounds.getCenterY());
Shape rotatedLabelBounds = t.createTransformedShape(labelBounds);
labelBounds = rotatedLabelBounds.getBounds2D();
double labelx = this.labelLocation.labelLocationX(dataArea);
double labely = state.getCursor() - insets.getBottom()
- labelBounds.getHeight() / 2.0;
TextAnchor anchor = this.labelLocation.labelAnchorH();
TextUtilities.drawRotatedString(label, g2, (float) labelx,
(float) labely, anchor, getLabelAngle(), TextAnchor.CENTER);
state.cursorUp(insets.getTop() + labelBounds.getHeight()
+ insets.getBottom());
}
else if (edge == RectangleEdge.BOTTOM) {
AffineTransform t = AffineTransform.getRotateInstance(
getLabelAngle(), labelBounds.getCenterX(),
labelBounds.getCenterY());
Shape rotatedLabelBounds = t.createTransformedShape(labelBounds);
labelBounds = rotatedLabelBounds.getBounds2D();
double labelx = this.labelLocation.labelLocationX(dataArea);
double labely = state.getCursor()
+ insets.getTop() + labelBounds.getHeight() / 2.0;
TextAnchor anchor = this.labelLocation.labelAnchorH();
TextUtilities.drawRotatedString(label, g2, (float) labelx,
(float) labely, anchor, getLabelAngle(), TextAnchor.CENTER);
state.cursorDown(insets.getTop() + labelBounds.getHeight()
+ insets.getBottom());
}
else if (edge == RectangleEdge.LEFT) {
AffineTransform t = AffineTransform.getRotateInstance(
getLabelAngle() - Math.PI / 2.0, labelBounds.getCenterX(),
labelBounds.getCenterY());
Shape rotatedLabelBounds = t.createTransformedShape(labelBounds);
labelBounds = rotatedLabelBounds.getBounds2D();
double labelx = state.getCursor()
- insets.getRight() - labelBounds.getWidth() / 2.0;
double labely = this.labelLocation.labelLocationY(dataArea);
TextAnchor anchor = this.labelLocation.labelAnchorV();
TextUtilities.drawRotatedString(label, g2, (float) labelx,
(float) labely, anchor, getLabelAngle() - Math.PI / 2.0,
anchor);
state.cursorLeft(insets.getLeft() + labelBounds.getWidth()
+ insets.getRight());
}
else if (edge == RectangleEdge.RIGHT) {
AffineTransform t = AffineTransform.getRotateInstance(
getLabelAngle() + Math.PI / 2.0,
labelBounds.getCenterX(), labelBounds.getCenterY());
Shape rotatedLabelBounds = t.createTransformedShape(labelBounds);
labelBounds = rotatedLabelBounds.getBounds2D();
double labelx = state.getCursor()
+ insets.getLeft() + labelBounds.getWidth() / 2.0;
double labely = this.labelLocation.labelLocationY(dataArea);
TextAnchor anchor = this.labelLocation.labelAnchorV();
TextUtilities.drawRotatedString(label, g2, (float) labelx,
(float) labely, anchor, getLabelAngle() + Math.PI / 2.0,
anchor);
state.cursorRight(insets.getLeft() + labelBounds.getWidth()
+ insets.getRight());
}
return state;
}
/**
* Draws an axis line at the current cursor position and edge.
*
* @param g2 the graphics device.
* @param cursor the cursor position.
* @param dataArea the data area.
* @param edge the edge.
*/
protected void drawAxisLine(Graphics2D g2, double cursor,
Rectangle2D dataArea, RectangleEdge edge) {
Line2D axisLine = null;
if (edge == RectangleEdge.TOP) {
axisLine = new Line2D.Double(dataArea.getX(), cursor,
dataArea.getMaxX(), cursor);
}
else if (edge == RectangleEdge.BOTTOM) {
axisLine = new Line2D.Double(dataArea.getX(), cursor,
dataArea.getMaxX(), cursor);
}
else if (edge == RectangleEdge.LEFT) {
axisLine = new Line2D.Double(cursor, dataArea.getY(), cursor,
dataArea.getMaxY());
}
else if (edge == RectangleEdge.RIGHT) {
axisLine = new Line2D.Double(cursor, dataArea.getY(), cursor,
dataArea.getMaxY());
}
g2.setPaint(this.axisLinePaint);
g2.setStroke(this.axisLineStroke);
g2.draw(axisLine);
}
/**
* Returns a clone of the axis.
*
* @return A clone.
*
* @throws CloneNotSupportedException if some component of the axis does
* not support cloning.
*/
@Override
public Object clone() throws CloneNotSupportedException {
Axis clone = (Axis) super.clone();
// It's up to the plot which clones up to restore the correct references
clone.plot = null;
clone.listenerList = new EventListenerList();
return clone;
}
/**
* Tests this axis 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 Axis)) {
return false;
}
Axis that = (Axis) obj;
if (this.visible != that.visible) {
return false;
}
if (!AttributedStringUtilities.equal(this.label, that.label)) {
return false;
}
if (!ObjectUtilities.equal(this.labelFont, that.labelFont)) {
return false;
}
if (!PaintUtilities.equal(this.labelPaint, that.labelPaint)) {
return false;
}
if (!ObjectUtilities.equal(this.labelInsets, that.labelInsets)) {
return false;
}
if (this.labelAngle != that.labelAngle) {
return false;
}
if (!this.labelLocation.equals(that.labelLocation)) {
return false;
}
if (this.axisLineVisible != that.axisLineVisible) {
return false;
}
if (!ObjectUtilities.equal(this.axisLineStroke, that.axisLineStroke)) {
return false;
}
if (!PaintUtilities.equal(this.axisLinePaint, that.axisLinePaint)) {
return false;
}
if (this.tickLabelsVisible != that.tickLabelsVisible) {
return false;
}
if (!ObjectUtilities.equal(this.tickLabelFont, that.tickLabelFont)) {
return false;
}
if (!PaintUtilities.equal(this.tickLabelPaint, that.tickLabelPaint)) {
return false;
}
if (!ObjectUtilities.equal(
this.tickLabelInsets, that.tickLabelInsets
)) {
return false;
}
if (this.tickMarksVisible != that.tickMarksVisible) {
return false;
}
if (this.tickMarkInsideLength != that.tickMarkInsideLength) {
return false;
}
if (this.tickMarkOutsideLength != that.tickMarkOutsideLength) {
return false;
}
if (!PaintUtilities.equal(this.tickMarkPaint, that.tickMarkPaint)) {
return false;
}
if (!ObjectUtilities.equal(this.tickMarkStroke, that.tickMarkStroke)) {
return false;
}
if (this.minorTickMarksVisible != that.minorTickMarksVisible) {
return false;
}
if (this.minorTickMarkInsideLength != that.minorTickMarkInsideLength) {
return false;
}
if (this.minorTickMarkOutsideLength
!= that.minorTickMarkOutsideLength) {
return false;
}
if (this.fixedDimension != that.fixedDimension) {
return false;
}
return true;
}
/**
* Returns a hash code for this object.
*
* @return A hash code.
*/
@Override
public int hashCode() {
if (getLabel() != null) {
String s = AttributedStringUtilities.toString(
getLabel().getIterator());
return s.hashCode();
}
return 0;
}
/**
* 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.writeAttributedString(this.label, stream);
SerialUtilities.writePaint(this.labelPaint, stream);
SerialUtilities.writePaint(this.tickLabelPaint, stream);
SerialUtilities.writeStroke(this.axisLineStroke, stream);
SerialUtilities.writePaint(this.axisLinePaint, stream);
SerialUtilities.writeStroke(this.tickMarkStroke, stream);
SerialUtilities.writePaint(this.tickMarkPaint, 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.label = SerialUtilities.readAttributedString(stream);
this.labelPaint = SerialUtilities.readPaint(stream);
this.tickLabelPaint = SerialUtilities.readPaint(stream);
this.axisLineStroke = SerialUtilities.readStroke(stream);
this.axisLinePaint = SerialUtilities.readPaint(stream);
this.tickMarkStroke = SerialUtilities.readStroke(stream);
this.tickMarkPaint = SerialUtilities.readPaint(stream);
this.listenerList = new EventListenerList();
}
}
| 50,631 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
TickUnits.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/axis/TickUnits.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.]
*
* --------------
* TickUnits.java
* --------------
* (C) Copyright 2001-2008, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 23-Nov-2001 : Version 1 (DG);
* 18-Feb-2002 : Fixed bug in getNearestTickUnit (thanks to Mario Inchiosa for
* reporting this, SourceForge bug id 518073) (DG);
* 25-Feb-2002 : Moved createStandardTickUnits() method from NumberAxis, and
* added createIntegerTickUnits() method (DG);
* 01-May-2002 : Updated for changes to the TickUnit class (DG);
* 18-Sep-2002 : Added standardTickUnit methods which take a Locale
* instance (AS);
* 26-Sep-2002 : Fixed errors reported by Checkstyle (DG);
* 08-Nov-2002 : Moved to new package com.jrefinery.chart.axis (DG);
* 26-Mar-2003 : Implemented Serializable (DG);
* 13-Aug-2003 : Implemented Cloneable (DG);
* 23-Sep-2003 : Implemented TickUnitSource interface (DG);
* 03-Dec-2003 : Adding null values now throws exceptions (TM);
* 11-Jan-2005 : Removed deprecated methods in preparation for 1.0.0
* release (DG);
*
*/
package org.jfree.chart.axis;
import java.io.Serializable;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* A collection of tick units, used by the {@link DateAxis} and
* {@link NumberAxis} classes.
*/
public class TickUnits implements TickUnitSource, Cloneable, Serializable {
/** For serialization. */
private static final long serialVersionUID = 1134174035901467545L;
/** Storage for the tick units. */
private List<TickUnit> tickUnits;
/**
* Constructs a new collection of tick units.
*/
public TickUnits() {
this.tickUnits = new ArrayList<TickUnit>();
}
/**
* Adds a tick unit to the collection. The tick units are maintained in
* ascending order.
*
* @param unit the tick unit to add (<code>null</code> not permitted).
*/
public void add(TickUnit unit) {
if (unit == null) {
throw new NullPointerException("Null 'unit' argument.");
}
this.tickUnits.add(unit);
Collections.sort(this.tickUnits);
}
/**
* Returns the number of tick units in this collection.
* <P>
* This method is required for the XML writer.
*
* @return The number of units in this collection.
*/
public int size() {
return this.tickUnits.size();
}
/**
* Returns the tickunit on the given position.
* <P>
* This method is required for the XML writer.
*
* @param pos the position in the list.
*
* @return The tickunit.
*/
public TickUnit get(int pos) {
return this.tickUnits.get(pos);
}
/**
* Returns a tick unit that is larger than the supplied unit.
*
* @param unit the unit.
*
* @return A tick unit that is larger than the supplied unit.
*/
@Override
public TickUnit getLargerTickUnit(TickUnit unit) {
int index = Collections.binarySearch(this.tickUnits, unit);
if (index >= 0) {
index = index + 1;
}
else {
index = -index;
}
return this.tickUnits.get(Math.min(index,
this.tickUnits.size() - 1));
}
/**
* Returns the tick unit in the collection that is greater than or equal
* to (in size) the specified unit.
*
* @param unit the unit.
*
* @return A unit from the collection.
*/
@Override
public TickUnit getCeilingTickUnit(TickUnit unit) {
int index = Collections.binarySearch(this.tickUnits, unit);
if (index >= 0) {
return this.tickUnits.get(index);
}
else {
index = -(index + 1);
return this.tickUnits.get(Math.min(index,
this.tickUnits.size() - 1));
}
}
/**
* Returns the tick unit in the collection that is greater than or equal
* to the specified size.
*
* @param size the size.
*
* @return A unit from the collection.
*/
@Override
public TickUnit getCeilingTickUnit(double size) {
return getCeilingTickUnit(new NumberTickUnit(size,
NumberFormat.getInstance()));
}
/**
* Returns a clone of the collection.
*
* @return A clone.
*
* @throws CloneNotSupportedException if an item in the collection does not
* support cloning.
*/
@Override
public Object clone() throws CloneNotSupportedException {
TickUnits clone = (TickUnits) super.clone();
clone.tickUnits = new java.util.ArrayList<TickUnit>(this.tickUnits);
return clone;
}
/**
* Tests an object for equality with this instance.
*
* @param obj the object to test (<code>null</code> permitted).
*
* @return A boolean.
*/
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof TickUnits)) {
return false;
}
TickUnits that = (TickUnits) obj;
return that.tickUnits.equals(this.tickUnits);
}
}
| 6,542 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
DateTickMarkPosition.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/axis/DateTickMarkPosition.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.]
*
* -------------------------
* DateTickMarkPosition.java
* -------------------------
* (C) Copyright 2003-2008, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes:
* --------
* 30-Apr-2003 : Version 1 (DG);
*
*/
package org.jfree.chart.axis;
/**
* Used to indicate the required position of tick marks on a date axis relative
* to the underlying time period.
*/
public enum DateTickMarkPosition {
/** Start of period. */
START("DateTickMarkPosition.START"),
/** Middle of period. */
MIDDLE("DateTickMarkPosition.MIDDLE"),
/** End of period. */
END("DateTickMarkPosition.END");
/** The name. */
private String name;
/**
* Private constructor.
*
* @param name the name.
*/
private DateTickMarkPosition(String name) {
this.name = name;
}
/**
* Returns a string representing the object.
*
* @return The string.
*/
@Override
public String toString() {
return this.name;
}
}
| 2,311 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
ValueAxis.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/axis/ValueAxis.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.]
*
* --------------
* ValueAxis.java
* --------------
* (C) Copyright 2000-2013, by Object Refinery Limited and Contributors.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): Jonathan Nash;
* Nicolas Brodu (for Astrium and EADS Corporate Research
* Center);
* Peter Kolb (patch 1934255);
* Andrew Mickish (patch 1870189);
*
* Changes
* -------
* 18-Sep-2001 : Added standard header and fixed DOS encoding problem (DG);
* 23-Nov-2001 : Overhauled standard tick unit code (DG);
* 04-Dec-2001 : Changed constructors to protected, and tidied up default
* values (DG);
* 12-Dec-2001 : Fixed vertical gridlines bug (DG);
* 16-Jan-2002 : Added an optional crosshair, based on the implementation by
* Jonathan Nash (DG);
* 23-Jan-2002 : Moved the minimum and maximum values to here from NumberAxis,
* and changed the type from Number to double (DG);
* 25-Feb-2002 : Added default value for autoRange. Changed autoAdjustRange
* from public to protected. Updated import statements (DG);
* 23-Apr-2002 : Added setRange() method (DG);
* 29-Apr-2002 : Added range adjustment methods (DG);
* 13-Jun-2002 : Modified setCrosshairValue() to notify listeners only when the
* crosshairs are visible, to avoid unnecessary repaints, as
* suggested by Kees Kuip (DG);
* 25-Jul-2002 : Moved lower and upper margin attributes from the NumberAxis
* class (DG);
* 05-Sep-2002 : Updated constructor for changes in Axis class (DG);
* 01-Oct-2002 : Fixed errors reported by Checkstyle (DG);
* 04-Oct-2002 : Moved standardTickUnits from NumberAxis --> ValueAxis (DG);
* 08-Nov-2002 : Moved to new package com.jrefinery.chart.axis (DG);
* 19-Nov-2002 : Removed grid settings (now controlled by the plot) (DG);
* 27-Nov-2002 : Moved the 'inverted' attribute from NumberAxis to
* ValueAxis (DG);
* 03-Jan-2003 : Small fix to ensure auto-range minimum is observed
* immediately (DG);
* 14-Jan-2003 : Changed autoRangeMinimumSize from Number --> double (DG);
* 20-Jan-2003 : Replaced monolithic constructor (DG);
* 26-Mar-2003 : Implemented Serializable (DG);
* 09-May-2003 : Added AxisLocation parameter to translation methods (DG);
* 13-Aug-2003 : Implemented Cloneable (DG);
* 01-Sep-2003 : Fixed bug 793167 (setMaximumAxisValue exception) (DG);
* 02-Sep-2003 : Fixed bug 795366 (zooming on inverted axes) (DG);
* 08-Sep-2003 : Completed Serialization support (NB);
* 08-Sep-2003 : Renamed get/setMinimumValue --> get/setLowerBound,
* and get/setMaximumValue --> get/setUpperBound (DG);
* 27-Oct-2003 : Changed DEFAULT_AUTO_RANGE_MINIMUM_SIZE value - see bug ID
* 829606 (DG);
* 07-Nov-2003 : Changes to tick mechanism (DG);
* 06-Jan-2004 : Moved axis line attributes to Axis class (DG);
* 21-Jan-2004 : Removed redundant axisLineVisible attribute. Renamed
* translateJava2DToValue --> java2DToValue, and
* translateValueToJava2D --> valueToJava2D (DG);
* 23-Jan-2004 : Fixed setAxisLinePaint() and setAxisLineStroke() which had no
* effect ([email protected]);
* 07-Apr-2004 : Changed text bounds calculation (DG);
* 26-Apr-2004 : Added getter/setter methods for arrow shapes (DG);
* 18-May-2004 : Added methods to set axis range *including* current
* margins (DG);
* 02-Jun-2004 : Fixed bug in setRangeWithMargins() method (DG);
* 30-Sep-2004 : Moved drawRotatedString() from RefineryUtilities
* --> TextUtilities (DG);
* 11-Jan-2005 : Removed deprecated methods in preparation for 1.0.0
* release (DG);
* 21-Apr-2005 : Replaced Insets with RectangleInsets (DG);
* ------------- JFREECHART 1.0.x ---------------------------------------------
* 10-Oct-2006 : Source reformatting (DG);
* 22-Mar-2007 : Added new defaultAutoRange attribute (DG);
* 02-Aug-2007 : Check for major tick when drawing label (DG);
* 25-Sep-2008 : Added minor tick support, see patch 1934255 by Peter Kolb (DG);
* 21-Jan-2009 : Updated default behaviour of minor ticks (DG);
* 18-Mar-2008 : Added resizeRange2() method which provides more natural
* anchored zooming for mouse wheel support (DG);
* 26-Mar-2009 : In equals(), only check current range if autoRange is
* false (DG);
* 30-Mar-2009 : Added pan(double) method (DG);
* 15-Jun-2012 : Remove JCommon dependencies (DG);
*
*/
package org.jfree.chart.axis;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.Polygon;
import java.awt.Shape;
import java.awt.font.LineMetrics;
import java.awt.geom.AffineTransform;
import java.awt.geom.Line2D;
import java.awt.geom.Rectangle2D;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.List;
import org.jfree.chart.ui.RectangleEdge;
import org.jfree.chart.ui.RectangleInsets;
import org.jfree.chart.util.ObjectUtilities;
import org.jfree.chart.util.PublicCloneable;
import org.jfree.chart.event.AxisChangeEvent;
import org.jfree.chart.plot.Plot;
import org.jfree.chart.text.TextUtilities;
import org.jfree.chart.util.ParamChecks;
import org.jfree.chart.util.SerialUtilities;
import org.jfree.data.Range;
/**
* The base class for axes that display value data, where values are measured
* using the <code>double</code> primitive. The two key subclasses are
* {@link DateAxis} and {@link NumberAxis}.
*/
public abstract class ValueAxis extends Axis
implements Cloneable, PublicCloneable, Serializable {
/** For serialization. */
private static final long serialVersionUID = 3698345477322391456L;
/** The default axis range. */
public static final Range DEFAULT_RANGE = new Range(0.0, 1.0);
/** The default auto-range value. */
public static final boolean DEFAULT_AUTO_RANGE = true;
/** The default inverted flag setting. */
public static final boolean DEFAULT_INVERTED = false;
/** The default minimum auto range. */
public static final double DEFAULT_AUTO_RANGE_MINIMUM_SIZE = 0.00000001;
/** The default value for the lower margin (0.05 = 5%). */
public static final double DEFAULT_LOWER_MARGIN = 0.05;
/** The default value for the upper margin (0.05 = 5%). */
public static final double DEFAULT_UPPER_MARGIN = 0.05;
/** The default auto-tick-unit-selection value. */
public static final boolean DEFAULT_AUTO_TICK_UNIT_SELECTION = true;
/** The maximum tick count. */
public static final int MAXIMUM_TICK_COUNT = 500;
/**
* A flag that controls whether an arrow is drawn at the positive end of
* the axis line.
*/
private boolean positiveArrowVisible;
/**
* A flag that controls whether an arrow is drawn at the negative end of
* the axis line.
*/
private boolean negativeArrowVisible;
/** The shape used for an up arrow. */
private transient Shape upArrow;
/** The shape used for a down arrow. */
private transient Shape downArrow;
/** The shape used for a left arrow. */
private transient Shape leftArrow;
/** The shape used for a right arrow. */
private transient Shape rightArrow;
/** A flag that affects the orientation of the values on the axis. */
private boolean inverted;
/** The axis range. */
private Range range;
/**
* Flag that indicates whether the axis automatically scales to fit the
* chart data.
*/
private boolean autoRange;
/** The minimum size for the 'auto' axis range (excluding margins). */
private double autoRangeMinimumSize;
/**
* The default range is used when the dataset is empty and the axis needs
* to determine the auto range.
*
* @since 1.0.5
*/
private Range defaultAutoRange;
/**
* The upper margin percentage. This indicates the amount by which the
* maximum axis value exceeds the maximum data value (as a percentage of
* the range on the axis) when the axis range is determined automatically.
*/
private double upperMargin;
/**
* The lower margin. This is a percentage that indicates the amount by
* which the minimum axis value is "less than" the minimum data value when
* the axis range is determined automatically.
*/
private double lowerMargin;
/**
* If this value is positive, the amount is subtracted from the maximum
* data value to determine the lower axis range. This can be used to
* provide a fixed "window" on dynamic data.
*/
private double fixedAutoRange;
/**
* Flag that indicates whether or not the tick unit is selected
* automatically.
*/
private boolean autoTickUnitSelection;
/** The standard tick units for the axis. */
private TickUnitSource standardTickUnits;
/** An index into an array of standard tick values. */
private int autoTickIndex;
/**
* The number of minor ticks per major tick unit. This is an override
* field, if the value is > 0 it is used, otherwise the axis refers to the
* minorTickCount in the current tickUnit.
*/
private int minorTickCount;
/** A flag indicating whether or not tick labels are rotated to vertical. */
private boolean verticalTickLabels;
/**
* Constructs a value axis.
*
* @param label the axis label (<code>null</code> permitted).
* @param standardTickUnits the source for standard tick units
* (<code>null</code> permitted).
*/
protected ValueAxis(String label, TickUnitSource standardTickUnits) {
super(label);
this.positiveArrowVisible = false;
this.negativeArrowVisible = false;
this.range = DEFAULT_RANGE;
this.autoRange = DEFAULT_AUTO_RANGE;
this.defaultAutoRange = DEFAULT_RANGE;
this.inverted = DEFAULT_INVERTED;
this.autoRangeMinimumSize = DEFAULT_AUTO_RANGE_MINIMUM_SIZE;
this.lowerMargin = DEFAULT_LOWER_MARGIN;
this.upperMargin = DEFAULT_UPPER_MARGIN;
this.fixedAutoRange = 0.0;
this.autoTickUnitSelection = DEFAULT_AUTO_TICK_UNIT_SELECTION;
this.standardTickUnits = standardTickUnits;
Polygon p1 = new Polygon();
p1.addPoint(0, 0);
p1.addPoint(-2, 2);
p1.addPoint(2, 2);
this.upArrow = p1;
Polygon p2 = new Polygon();
p2.addPoint(0, 0);
p2.addPoint(-2, -2);
p2.addPoint(2, -2);
this.downArrow = p2;
Polygon p3 = new Polygon();
p3.addPoint(0, 0);
p3.addPoint(-2, -2);
p3.addPoint(-2, 2);
this.rightArrow = p3;
Polygon p4 = new Polygon();
p4.addPoint(0, 0);
p4.addPoint(2, -2);
p4.addPoint(2, 2);
this.leftArrow = p4;
this.verticalTickLabels = false;
this.minorTickCount = 0;
}
/**
* Returns <code>true</code> if the tick labels should be rotated (to
* vertical), and <code>false</code> otherwise.
*
* @return <code>true</code> or <code>false</code>.
*
* @see #setVerticalTickLabels(boolean)
*/
public boolean isVerticalTickLabels() {
return this.verticalTickLabels;
}
/**
* Sets the flag that controls whether the tick labels are displayed
* vertically (that is, rotated 90 degrees from horizontal). If the flag
* is changed, an {@link AxisChangeEvent} is sent to all registered
* listeners.
*
* @param flag the flag.
*
* @see #isVerticalTickLabels()
*/
public void setVerticalTickLabels(boolean flag) {
if (this.verticalTickLabels != flag) {
this.verticalTickLabels = flag;
fireChangeEvent();
}
}
/**
* Returns a flag that controls whether or not the axis line has an arrow
* drawn that points in the positive direction for the axis.
*
* @return A boolean.
*
* @see #setPositiveArrowVisible(boolean)
*/
public boolean isPositiveArrowVisible() {
return this.positiveArrowVisible;
}
/**
* Sets a flag that controls whether or not the axis lines has an arrow
* drawn that points in the positive direction for the axis, and sends an
* {@link AxisChangeEvent} to all registered listeners.
*
* @param visible the flag.
*
* @see #isPositiveArrowVisible()
*/
public void setPositiveArrowVisible(boolean visible) {
this.positiveArrowVisible = visible;
fireChangeEvent();
}
/**
* Returns a flag that controls whether or not the axis line has an arrow
* drawn that points in the negative direction for the axis.
*
* @return A boolean.
*
* @see #setNegativeArrowVisible(boolean)
*/
public boolean isNegativeArrowVisible() {
return this.negativeArrowVisible;
}
/**
* Sets a flag that controls whether or not the axis lines has an arrow
* drawn that points in the negative direction for the axis, and sends an
* {@link AxisChangeEvent} to all registered listeners.
*
* @param visible the flag.
*
* @see #setNegativeArrowVisible(boolean)
*/
public void setNegativeArrowVisible(boolean visible) {
this.negativeArrowVisible = visible;
fireChangeEvent();
}
/**
* Returns a shape that can be displayed as an arrow pointing upwards at
* the end of an axis line.
*
* @return A shape (never <code>null</code>).
*
* @see #setUpArrow(Shape)
*/
public Shape getUpArrow() {
return this.upArrow;
}
/**
* Sets the shape that can be displayed as an arrow pointing upwards at
* the end of an axis line and sends an {@link AxisChangeEvent} to all
* registered listeners.
*
* @param arrow the arrow shape (<code>null</code> not permitted).
*
* @see #getUpArrow()
*/
public void setUpArrow(Shape arrow) {
ParamChecks.nullNotPermitted(arrow, "arrow");
this.upArrow = arrow;
fireChangeEvent();
}
/**
* Returns a shape that can be displayed as an arrow pointing downwards at
* the end of an axis line.
*
* @return A shape (never <code>null</code>).
*
* @see #setDownArrow(Shape)
*/
public Shape getDownArrow() {
return this.downArrow;
}
/**
* Sets the shape that can be displayed as an arrow pointing downwards at
* the end of an axis line and sends an {@link AxisChangeEvent} to all
* registered listeners.
*
* @param arrow the arrow shape (<code>null</code> not permitted).
*
* @see #getDownArrow()
*/
public void setDownArrow(Shape arrow) {
ParamChecks.nullNotPermitted(arrow, "arrow");
this.downArrow = arrow;
fireChangeEvent();
}
/**
* Returns a shape that can be displayed as an arrow pointing left at the
* end of an axis line.
*
* @return A shape (never <code>null</code>).
*
* @see #setLeftArrow(Shape)
*/
public Shape getLeftArrow() {
return this.leftArrow;
}
/**
* Sets the shape that can be displayed as an arrow pointing left at the
* end of an axis line and sends an {@link AxisChangeEvent} to all
* registered listeners.
*
* @param arrow the arrow shape (<code>null</code> not permitted).
*
* @see #getLeftArrow()
*/
public void setLeftArrow(Shape arrow) {
ParamChecks.nullNotPermitted(arrow, "arrow");
this.leftArrow = arrow;
fireChangeEvent();
}
/**
* Returns a shape that can be displayed as an arrow pointing right at the
* end of an axis line.
*
* @return A shape (never <code>null</code>).
*
* @see #setRightArrow(Shape)
*/
public Shape getRightArrow() {
return this.rightArrow;
}
/**
* Sets the shape that can be displayed as an arrow pointing rightwards at
* the end of an axis line and sends an {@link AxisChangeEvent} to all
* registered listeners.
*
* @param arrow the arrow shape (<code>null</code> not permitted).
*
* @see #getRightArrow()
*/
public void setRightArrow(Shape arrow) {
ParamChecks.nullNotPermitted(arrow, "arrow");
this.rightArrow = arrow;
fireChangeEvent();
}
/**
* Draws an axis line at the current cursor position and edge.
*
* @param g2 the graphics device.
* @param cursor the cursor position.
* @param dataArea the data area.
* @param edge the edge.
*/
@Override
protected void drawAxisLine(Graphics2D g2, double cursor,
Rectangle2D dataArea, RectangleEdge edge) {
Line2D axisLine = null;
if (edge == RectangleEdge.TOP) {
axisLine = new Line2D.Double(dataArea.getX(), cursor,
dataArea.getMaxX(), cursor);
}
else if (edge == RectangleEdge.BOTTOM) {
axisLine = new Line2D.Double(dataArea.getX(), cursor,
dataArea.getMaxX(), cursor);
}
else if (edge == RectangleEdge.LEFT) {
axisLine = new Line2D.Double(cursor, dataArea.getY(), cursor,
dataArea.getMaxY());
}
else if (edge == RectangleEdge.RIGHT) {
axisLine = new Line2D.Double(cursor, dataArea.getY(), cursor,
dataArea.getMaxY());
}
g2.setPaint(getAxisLinePaint());
g2.setStroke(getAxisLineStroke());
g2.draw(axisLine);
boolean drawUpOrRight = false;
boolean drawDownOrLeft = false;
if (this.positiveArrowVisible) {
if (this.inverted) {
drawDownOrLeft = true;
}
else {
drawUpOrRight = true;
}
}
if (this.negativeArrowVisible) {
if (this.inverted) {
drawUpOrRight = true;
}
else {
drawDownOrLeft = true;
}
}
if (drawUpOrRight) {
double x = 0.0;
double y = 0.0;
Shape arrow = null;
if (edge == RectangleEdge.TOP || edge == RectangleEdge.BOTTOM) {
x = dataArea.getMaxX();
y = cursor;
arrow = this.rightArrow;
}
else if (edge == RectangleEdge.LEFT
|| edge == RectangleEdge.RIGHT) {
x = cursor;
y = dataArea.getMinY();
arrow = this.upArrow;
}
// draw the arrow...
AffineTransform transformer = new AffineTransform();
transformer.setToTranslation(x, y);
Shape shape = transformer.createTransformedShape(arrow);
g2.fill(shape);
g2.draw(shape);
}
if (drawDownOrLeft) {
double x = 0.0;
double y = 0.0;
Shape arrow = null;
if (edge == RectangleEdge.TOP || edge == RectangleEdge.BOTTOM) {
x = dataArea.getMinX();
y = cursor;
arrow = this.leftArrow;
}
else if (edge == RectangleEdge.LEFT
|| edge == RectangleEdge.RIGHT) {
x = cursor;
y = dataArea.getMaxY();
arrow = this.downArrow;
}
// draw the arrow...
AffineTransform transformer = new AffineTransform();
transformer.setToTranslation(x, y);
Shape shape = transformer.createTransformedShape(arrow);
g2.fill(shape);
g2.draw(shape);
}
}
/**
* Calculates the anchor point for a tick label.
*
* @param tick the tick.
* @param cursor the cursor.
* @param dataArea the data area.
* @param edge the edge on which the axis is drawn.
*
* @return The x and y coordinates of the anchor point.
*/
protected float[] calculateAnchorPoint(ValueTick tick, double cursor,
Rectangle2D dataArea, RectangleEdge edge) {
RectangleInsets insets = getTickLabelInsets();
float[] result = new float[2];
if (edge == RectangleEdge.TOP) {
result[0] = (float) valueToJava2D(tick.getValue(), dataArea, edge);
result[1] = (float) (cursor - insets.getBottom() - 2.0);
}
else if (edge == RectangleEdge.BOTTOM) {
result[0] = (float) valueToJava2D(tick.getValue(), dataArea, edge);
result[1] = (float) (cursor + insets.getTop() + 2.0);
}
else if (edge == RectangleEdge.LEFT) {
result[0] = (float) (cursor - insets.getLeft() - 2.0);
result[1] = (float) valueToJava2D(tick.getValue(), dataArea, edge);
}
else if (edge == RectangleEdge.RIGHT) {
result[0] = (float) (cursor + insets.getRight() + 2.0);
result[1] = (float) valueToJava2D(tick.getValue(), dataArea, edge);
}
return result;
}
/**
* Draws the axis line, tick marks and tick mark labels.
*
* @param g2 the graphics device.
* @param cursor the cursor.
* @param plotArea the plot area.
* @param dataArea the data area.
* @param edge the edge that the axis is aligned with.
*
* @return The width or height used to draw the axis.
*/
protected AxisState drawTickMarksAndLabels(Graphics2D g2,
double cursor, Rectangle2D plotArea, Rectangle2D dataArea,
RectangleEdge edge) {
AxisState state = new AxisState(cursor);
if (isAxisLineVisible()) {
drawAxisLine(g2, cursor, dataArea, edge);
}
List<ValueTick> ticks = refreshTicks(g2, state, dataArea, edge);
state.setTicks(ticks);
g2.setFont(getTickLabelFont());
for (ValueTick tick : ticks) {
if (isTickLabelsVisible()) {
g2.setPaint(getTickLabelPaint());
float[] anchorPoint = calculateAnchorPoint(tick, cursor,
dataArea, edge);
TextUtilities.drawRotatedString(tick.getText(), g2,
anchorPoint[0], anchorPoint[1], tick.getTextAnchor(),
tick.getAngle(), tick.getRotationAnchor());
}
if ((isTickMarksVisible() && tick.getTickType().equals(
TickType.MAJOR)) || (isMinorTickMarksVisible()
&& tick.getTickType().equals(TickType.MINOR))) {
double ol = (tick.getTickType().equals(TickType.MINOR))
? getMinorTickMarkOutsideLength()
: getTickMarkOutsideLength();
double il = (tick.getTickType().equals(TickType.MINOR))
? getMinorTickMarkInsideLength()
: getTickMarkInsideLength();
float xx = (float) valueToJava2D(tick.getValue(), dataArea,
edge);
Line2D mark = null;
g2.setStroke(getTickMarkStroke());
g2.setPaint(getTickMarkPaint());
if (edge == RectangleEdge.LEFT) {
mark = new Line2D.Double(cursor - ol, xx, cursor + il, xx);
} else if (edge == RectangleEdge.RIGHT) {
mark = new Line2D.Double(cursor + ol, xx, cursor - il, xx);
} else if (edge == RectangleEdge.TOP) {
mark = new Line2D.Double(xx, cursor - ol, xx, cursor + il);
} else if (edge == RectangleEdge.BOTTOM) {
mark = new Line2D.Double(xx, cursor + ol, xx, cursor - il);
}
g2.draw(mark);
}
}
// need to work out the space used by the tick labels...
// so we can update the cursor...
double used = 0.0;
if (isTickLabelsVisible()) {
if (edge == RectangleEdge.LEFT) {
used += findMaximumTickLabelWidth(ticks, g2, plotArea,
isVerticalTickLabels());
state.cursorLeft(used);
}
else if (edge == RectangleEdge.RIGHT) {
used = findMaximumTickLabelWidth(ticks, g2, plotArea,
isVerticalTickLabels());
state.cursorRight(used);
}
else if (edge == RectangleEdge.TOP) {
used = findMaximumTickLabelHeight(ticks, g2, plotArea,
isVerticalTickLabels());
state.cursorUp(used);
}
else if (edge == RectangleEdge.BOTTOM) {
used = findMaximumTickLabelHeight(ticks, g2, plotArea,
isVerticalTickLabels());
state.cursorDown(used);
}
}
return state;
}
/**
* Calculates the positions of the ticks for the axis, storing the results
* in the tick list (ready for drawing).
*
* @param g2 the graphics device.
* @param state the axis state.
* @param dataArea the area inside the axes.
* @param edge the edge on which the axis is located.
*
* @return The list of ticks.
*/
public abstract List<ValueTick> refreshTicks(Graphics2D g2, AxisState state,
Rectangle2D dataArea, RectangleEdge edge);
/**
* Returns the space required to draw the axis.
*
* @param g2 the graphics device.
* @param plot the plot that the axis belongs to.
* @param plotArea the area within which the plot should be drawn.
* @param edge the axis location.
* @param space the space already reserved (for other axes).
*
* @return The space required to draw the axis (including pre-reserved
* space).
*/
@Override
public AxisSpace reserveSpace(Graphics2D g2, Plot plot,
Rectangle2D plotArea, RectangleEdge edge, AxisSpace space) {
// create a new space object if one wasn't supplied...
if (space == null) {
space = new AxisSpace();
}
// if the axis is not visible, no additional space is required...
if (!isVisible()) {
return space;
}
// if the axis has a fixed dimension, return it...
double dimension = getFixedDimension();
if (dimension > 0.0) {
space.add(dimension, edge);
return space;
}
// calculate the max size of the tick labels (if visible)...
double tickLabelHeight = 0.0;
double tickLabelWidth = 0.0;
if (isTickLabelsVisible()) {
g2.setFont(getTickLabelFont());
List<ValueTick> ticks = refreshTicks(g2, new AxisState(), plotArea, edge);
if (RectangleEdge.isTopOrBottom(edge)) {
tickLabelHeight = findMaximumTickLabelHeight(ticks, g2,
plotArea, isVerticalTickLabels());
}
else if (RectangleEdge.isLeftOrRight(edge)) {
tickLabelWidth = findMaximumTickLabelWidth(ticks, g2, plotArea,
isVerticalTickLabels());
}
}
// get the axis label size and update the space object...
Rectangle2D labelEnclosure = getLabelEnclosure(g2, edge);
if (RectangleEdge.isTopOrBottom(edge)) {
double labelHeight = labelEnclosure.getHeight();
space.add(labelHeight + tickLabelHeight, edge);
}
else if (RectangleEdge.isLeftOrRight(edge)) {
double labelWidth = labelEnclosure.getWidth();
space.add(labelWidth + tickLabelWidth, edge);
}
return space;
}
/**
* A utility method for determining the height of the tallest tick label.
*
* @param ticks the ticks.
* @param g2 the graphics device.
* @param drawArea the area within which the plot and axes should be drawn.
* @param vertical a flag that indicates whether or not the tick labels
* are 'vertical'.
*
* @return The height of the tallest tick label.
*/
protected double findMaximumTickLabelHeight(List<ValueTick> ticks,
Graphics2D g2, Rectangle2D drawArea, boolean vertical) {
RectangleInsets insets = getTickLabelInsets();
Font font = getTickLabelFont();
double maxHeight = 0.0;
if (vertical) {
FontMetrics fm = g2.getFontMetrics(font);
for (Tick tick : ticks) {
Rectangle2D labelBounds = TextUtilities.getTextBounds(
tick.getText(), g2, fm);
if (labelBounds.getWidth() + insets.getTop()
+ insets.getBottom() > maxHeight) {
maxHeight = labelBounds.getWidth()
+ insets.getTop() + insets.getBottom();
}
}
}
else {
LineMetrics metrics = font.getLineMetrics("ABCxyz",
g2.getFontRenderContext());
maxHeight = metrics.getHeight()
+ insets.getTop() + insets.getBottom();
}
return maxHeight;
}
/**
* A utility method for determining the width of the widest tick label.
*
* @param ticks the ticks.
* @param g2 the graphics device.
* @param drawArea the area within which the plot and axes should be drawn.
* @param vertical a flag that indicates whether or not the tick labels
* are 'vertical'.
*
* @return The width of the tallest tick label.
*/
protected double findMaximumTickLabelWidth(List<ValueTick> ticks,
Graphics2D g2, Rectangle2D drawArea, boolean vertical) {
RectangleInsets insets = getTickLabelInsets();
Font font = getTickLabelFont();
double maxWidth = 0.0;
if (!vertical) {
FontMetrics fm = g2.getFontMetrics(font);
for (ValueTick tick : ticks) {
Rectangle2D labelBounds = TextUtilities.getTextBounds(
tick.getText(), g2, fm);
if (labelBounds.getWidth() + insets.getLeft()
+ insets.getRight() > maxWidth) {
maxWidth = labelBounds.getWidth()
+ insets.getLeft() + insets.getRight();
}
}
}
else {
LineMetrics metrics = font.getLineMetrics("ABCxyz",
g2.getFontRenderContext());
maxWidth = metrics.getHeight()
+ insets.getTop() + insets.getBottom();
}
return maxWidth;
}
/**
* Returns a flag that controls the direction of values on the axis.
* <P>
* For a regular axis, values increase from left to right (for a horizontal
* axis) and bottom to top (for a vertical axis). When the axis is
* 'inverted', the values increase in the opposite direction.
*
* @return The flag.
*
* @see #setInverted(boolean)
*/
public boolean isInverted() {
return this.inverted;
}
/**
* Sets a flag that controls the direction of values on the axis, and
* notifies registered listeners that the axis has changed.
*
* @param flag the flag.
*
* @see #isInverted()
*/
public void setInverted(boolean flag) {
if (this.inverted != flag) {
this.inverted = flag;
fireChangeEvent();
}
}
/**
* Returns the flag that controls whether or not the axis range is
* automatically adjusted to fit the data values.
*
* @return The flag.
*
* @see #setAutoRange(boolean)
*/
public boolean isAutoRange() {
return this.autoRange;
}
/**
* Sets a flag that determines whether or not the axis range is
* automatically adjusted to fit the data, and notifies registered
* listeners that the axis has been modified.
*
* @param auto the new value of the flag.
*
* @see #isAutoRange()
*/
public void setAutoRange(boolean auto) {
setAutoRange(auto, true);
}
/**
* Sets the auto range attribute. If the <code>notify</code> flag is set,
* an {@link AxisChangeEvent} is sent to registered listeners.
*
* @param auto the flag.
* @param notify notify listeners?
*
* @see #isAutoRange()
*/
protected void setAutoRange(boolean auto, boolean notify) {
if (this.autoRange != auto) {
this.autoRange = auto;
if (this.autoRange) {
autoAdjustRange();
}
if (notify) {
fireChangeEvent();
}
}
}
/**
* Returns the minimum size allowed for the axis range when it is
* automatically calculated.
*
* @return The minimum range.
*
* @see #setAutoRangeMinimumSize(double)
*/
public double getAutoRangeMinimumSize() {
return this.autoRangeMinimumSize;
}
/**
* Sets the auto range minimum size and sends an {@link AxisChangeEvent}
* to all registered listeners.
*
* @param size the size.
*
* @see #getAutoRangeMinimumSize()
*/
public void setAutoRangeMinimumSize(double size) {
setAutoRangeMinimumSize(size, true);
}
/**
* Sets the minimum size allowed for the axis range when it is
* automatically calculated.
* <p>
* If requested, an {@link AxisChangeEvent} is forwarded to all registered
* listeners.
*
* @param size the new minimum.
* @param notify notify listeners?
*/
public void setAutoRangeMinimumSize(double size, boolean notify) {
if (size <= 0.0) {
throw new IllegalArgumentException(
"NumberAxis.setAutoRangeMinimumSize(double): must be > 0.0.");
}
if (this.autoRangeMinimumSize != size) {
this.autoRangeMinimumSize = size;
if (this.autoRange) {
autoAdjustRange();
}
if (notify) {
fireChangeEvent();
}
}
}
/**
* Returns the default auto range.
*
* @return The default auto range (never <code>null</code>).
*
* @see #setDefaultAutoRange(Range)
*
* @since 1.0.5
*/
public Range getDefaultAutoRange() {
return this.defaultAutoRange;
}
/**
* Sets the default auto range and sends an {@link AxisChangeEvent} to all
* registered listeners.
*
* @param range the range (<code>null</code> not permitted).
*
* @see #getDefaultAutoRange()
*
* @since 1.0.5
*/
public void setDefaultAutoRange(Range range) {
ParamChecks.nullNotPermitted(range, "range");
this.defaultAutoRange = range;
fireChangeEvent();
}
/**
* Returns the lower margin for the axis, expressed as a percentage of the
* axis range. This controls the space added to the lower end of the axis
* when the axis range is automatically calculated (it is ignored when the
* axis range is set explicitly). The default value is 0.05 (five percent).
*
* @return The lower margin.
*
* @see #setLowerMargin(double)
*/
public double getLowerMargin() {
return this.lowerMargin;
}
/**
* Sets the lower margin for the axis (as a percentage of the axis range)
* and sends an {@link AxisChangeEvent} to all registered listeners. This
* margin is added only when the axis range is auto-calculated - if you set
* the axis range manually, the margin is ignored.
*
* @param margin the margin percentage (for example, 0.05 is five percent).
*
* @see #getLowerMargin()
* @see #setUpperMargin(double)
*/
public void setLowerMargin(double margin) {
this.lowerMargin = margin;
if (isAutoRange()) {
autoAdjustRange();
}
fireChangeEvent();
}
/**
* Returns the upper margin for the axis, expressed as a percentage of the
* axis range. This controls the space added to the lower end of the axis
* when the axis range is automatically calculated (it is ignored when the
* axis range is set explicitly). The default value is 0.05 (five percent).
*
* @return The upper margin.
*
* @see #setUpperMargin(double)
*/
public double getUpperMargin() {
return this.upperMargin;
}
/**
* Sets the upper margin for the axis (as a percentage of the axis range)
* and sends an {@link AxisChangeEvent} to all registered listeners. This
* margin is added only when the axis range is auto-calculated - if you set
* the axis range manually, the margin is ignored.
*
* @param margin the margin percentage (for example, 0.05 is five percent).
*
* @see #getLowerMargin()
* @see #setLowerMargin(double)
*/
public void setUpperMargin(double margin) {
this.upperMargin = margin;
if (isAutoRange()) {
autoAdjustRange();
}
fireChangeEvent();
}
/**
* Returns the fixed auto range.
*
* @return The length.
*
* @see #setFixedAutoRange(double)
*/
public double getFixedAutoRange() {
return this.fixedAutoRange;
}
/**
* Sets the fixed auto range for the axis.
*
* @param length the range length.
*
* @see #getFixedAutoRange()
*/
public void setFixedAutoRange(double length) {
this.fixedAutoRange = length;
if (isAutoRange()) {
autoAdjustRange();
}
fireChangeEvent();
}
/**
* Returns the lower bound of the axis range.
*
* @return The lower bound.
*
* @see #setLowerBound(double)
*/
public double getLowerBound() {
return this.range.getLowerBound();
}
/**
* Sets the lower bound for the axis range. An {@link AxisChangeEvent} is
* sent to all registered listeners.
*
* @param min the new minimum.
*
* @see #getLowerBound()
*/
public void setLowerBound(double min) {
if (this.range.getUpperBound() > min) {
setRange(new Range(min, this.range.getUpperBound()));
}
else {
setRange(new Range(min, min + 1.0));
}
}
/**
* Returns the upper bound for the axis range.
*
* @return The upper bound.
*
* @see #setUpperBound(double)
*/
public double getUpperBound() {
return this.range.getUpperBound();
}
/**
* Sets the upper bound for the axis range, and sends an
* {@link AxisChangeEvent} to all registered listeners.
*
* @param max the new maximum.
*
* @see #getUpperBound()
*/
public void setUpperBound(double max) {
if (this.range.getLowerBound() < max) {
setRange(new Range(this.range.getLowerBound(), max));
}
else {
setRange(max - 1.0, max);
}
}
/**
* Returns the range for the axis.
*
* @return The axis range (never <code>null</code>).
*
* @see #setRange(Range)
*/
public Range getRange() {
return this.range;
}
/**
* Sets the range attribute and sends an {@link AxisChangeEvent} to all
* registered listeners. As a side-effect, the auto-range flag is set to
* <code>false</code>.
*
* @param range the range (<code>null</code> not permitted).
*
* @see #getRange()
*/
public void setRange(Range range) {
// defer argument checking
setRange(range, true, true);
}
/**
* Sets the range for the axis, if requested, sends an
* {@link AxisChangeEvent} to all registered listeners. As a side-effect,
* the auto-range flag is set to <code>false</code> (optional).
*
* @param range the range (<code>null</code> not permitted).
* @param turnOffAutoRange a flag that controls whether or not the auto
* range is turned off.
* @param notify a flag that controls whether or not listeners are
* notified.
*
* @see #getRange()
*/
public void setRange(Range range, boolean turnOffAutoRange,
boolean notify) {
ParamChecks.nullNotPermitted(range, "range");
if (turnOffAutoRange) {
this.autoRange = false;
}
this.range = range;
if (notify) {
fireChangeEvent();
}
}
/**
* Sets the axis range and sends an {@link AxisChangeEvent} to all
* registered listeners. As a side-effect, the auto-range flag is set to
* <code>false</code>.
*
* @param lower the lower axis limit.
* @param upper the upper axis limit.
*
* @see #getRange()
* @see #setRange(Range)
*/
public void setRange(double lower, double upper) {
setRange(new Range(lower, upper));
}
/**
* Sets the range for the axis (after first adding the current margins to
* the specified range) and sends an {@link AxisChangeEvent} to all
* registered listeners.
*
* @param range the range (<code>null</code> not permitted).
*/
public void setRangeWithMargins(Range range) {
setRangeWithMargins(range, true, true);
}
/**
* Sets the range for the axis after first adding the current margins to
* the range and, if requested, sends an {@link AxisChangeEvent} to all
* registered listeners. As a side-effect, the auto-range flag is set to
* <code>false</code> (optional).
*
* @param range the range (excluding margins, <code>null</code> not
* permitted).
* @param turnOffAutoRange a flag that controls whether or not the auto
* range is turned off.
* @param notify a flag that controls whether or not listeners are
* notified.
*/
public void setRangeWithMargins(Range range, boolean turnOffAutoRange,
boolean notify) {
ParamChecks.nullNotPermitted(range, "range");
setRange(Range.expand(range, getLowerMargin(), getUpperMargin()),
turnOffAutoRange, notify);
}
/**
* Sets the axis range (after first adding the current margins to the
* range) and sends an {@link AxisChangeEvent} to all registered listeners.
* As a side-effect, the auto-range flag is set to <code>false</code>.
*
* @param lower the lower axis limit.
* @param upper the upper axis limit.
*/
public void setRangeWithMargins(double lower, double upper) {
setRangeWithMargins(new Range(lower, upper));
}
/**
* Sets the axis range, where the new range is 'size' in length, and
* centered on 'value'.
*
* @param value the central value.
* @param length the range length.
*/
public void setRangeAboutValue(double value, double length) {
setRange(new Range(value - length / 2, value + length / 2));
}
/**
* Returns a flag indicating whether or not the tick unit is automatically
* selected from a range of standard tick units.
*
* @return A flag indicating whether or not the tick unit is automatically
* selected.
*
* @see #setAutoTickUnitSelection(boolean)
*/
public boolean isAutoTickUnitSelection() {
return this.autoTickUnitSelection;
}
/**
* Sets a flag indicating whether or not the tick unit is automatically
* selected from a range of standard tick units. If the flag is changed,
* registered listeners are notified that the chart has changed.
*
* @param flag the new value of the flag.
*
* @see #isAutoTickUnitSelection()
*/
public void setAutoTickUnitSelection(boolean flag) {
setAutoTickUnitSelection(flag, true);
}
/**
* Sets a flag indicating whether or not the tick unit is automatically
* selected from a range of standard tick units.
*
* @param flag the new value of the flag.
* @param notify notify listeners?
*
* @see #isAutoTickUnitSelection()
*/
public void setAutoTickUnitSelection(boolean flag, boolean notify) {
if (this.autoTickUnitSelection != flag) {
this.autoTickUnitSelection = flag;
if (notify) {
fireChangeEvent();
}
}
}
/**
* Returns the source for obtaining standard tick units for the axis.
*
* @return The source (possibly <code>null</code>).
*
* @see #setStandardTickUnits(TickUnitSource)
*/
public TickUnitSource getStandardTickUnits() {
return this.standardTickUnits;
}
/**
* Sets the source for obtaining standard tick units for the axis and sends
* an {@link AxisChangeEvent} to all registered listeners. The axis will
* try to select the smallest tick unit from the source that does not cause
* the tick labels to overlap (see also the
* {@link #setAutoTickUnitSelection(boolean)} method.
*
* @param source the source for standard tick units (<code>null</code>
* permitted).
*
* @see #getStandardTickUnits()
*/
public void setStandardTickUnits(TickUnitSource source) {
this.standardTickUnits = source;
fireChangeEvent();
}
/**
* Returns the number of minor tick marks to display.
*
* @return The number of minor tick marks to display.
*
* @see #setMinorTickCount(int)
*
* @since 1.0.12
*/
public int getMinorTickCount() {
return this.minorTickCount;
}
/**
* Sets the number of minor tick marks to display, and sends an
* {@link AxisChangeEvent} to all registered listeners.
*
* @param count the count.
*
* @see #getMinorTickCount()
*
* @since 1.0.12
*/
public void setMinorTickCount(int count) {
this.minorTickCount = count;
fireChangeEvent();
}
/**
* Converts a data value to a coordinate in Java2D space, assuming that the
* axis runs along one edge of the specified dataArea.
* <p>
* Note that it is possible for the coordinate to fall outside the area.
*
* @param value the data value.
* @param area the area for plotting the data.
* @param edge the edge along which the axis lies.
*
* @return The Java2D coordinate.
*
* @see #java2DToValue(double, Rectangle2D, RectangleEdge)
*/
public abstract double valueToJava2D(double value, Rectangle2D area,
RectangleEdge edge);
/**
* Converts a length in data coordinates into the corresponding length in
* Java2D coordinates.
*
* @param length the length.
* @param area the plot area.
* @param edge the edge along which the axis lies.
*
* @return The length in Java2D coordinates.
*/
public double lengthToJava2D(double length, Rectangle2D area,
RectangleEdge edge) {
double zero = valueToJava2D(0.0, area, edge);
double l = valueToJava2D(length, area, edge);
return Math.abs(l - zero);
}
/**
* Converts a coordinate in Java2D space to the corresponding data value,
* assuming that the axis runs along one edge of the specified dataArea.
*
* @param java2DValue the coordinate in Java2D space.
* @param area the area in which the data is plotted.
* @param edge the edge along which the axis lies.
*
* @return The data value.
*
* @see #valueToJava2D(double, Rectangle2D, RectangleEdge)
*/
public abstract double java2DToValue(double java2DValue, Rectangle2D area,
RectangleEdge edge);
/**
* Automatically sets the axis range to fit the range of values in the
* dataset. Sometimes this can depend on the renderer used as well (for
* example, the renderer may "stack" values, requiring an axis range
* greater than otherwise necessary).
*/
protected abstract void autoAdjustRange();
/**
* Centers the axis range about the specified value and sends an
* {@link AxisChangeEvent} to all registered listeners.
*
* @param value the center value.
*/
public void centerRange(double value) {
double central = this.range.getCentralValue();
Range adjusted = new Range(this.range.getLowerBound() + value - central,
this.range.getUpperBound() + value - central);
setRange(adjusted);
}
/**
* Increases or decreases the axis range by the specified percentage about
* the central value and sends an {@link AxisChangeEvent} to all registered
* listeners.
* <P>
* To double the length of the axis range, use 200% (2.0).
* To halve the length of the axis range, use 50% (0.5).
*
* @param percent the resize factor.
*
* @see #resizeRange(double, double)
*/
public void resizeRange(double percent) {
resizeRange(percent, this.range.getCentralValue());
}
/**
* Increases or decreases the axis range by the specified percentage about
* the specified anchor value and sends an {@link AxisChangeEvent} to all
* registered listeners.
* <P>
* To double the length of the axis range, use 200% (2.0).
* To halve the length of the axis range, use 50% (0.5).
*
* @param percent the resize factor.
* @param anchorValue the new central value after the resize.
*
* @see #resizeRange(double)
*/
public void resizeRange(double percent, double anchorValue) {
if (percent > 0.0) {
double halfLength = this.range.getLength() * percent / 2;
Range adjusted = new Range(anchorValue - halfLength,
anchorValue + halfLength);
setRange(adjusted);
}
else {
setAutoRange(true);
}
}
/**
* Increases or decreases the axis range by the specified percentage about
* the specified anchor value and sends an {@link AxisChangeEvent} to all
* registered listeners.
* <P>
* To double the length of the axis range, use 200% (2.0).
* To halve the length of the axis range, use 50% (0.5).
*
* @param percent the resize factor.
* @param anchorValue the new central value after the resize.
*
* @see #resizeRange(double)
*
* @since 1.0.13
*/
public void resizeRange2(double percent, double anchorValue) {
if (percent > 0.0) {
double left = anchorValue - getLowerBound();
double right = getUpperBound() - anchorValue;
Range adjusted = new Range(anchorValue - left * percent,
anchorValue + right * percent);
setRange(adjusted);
}
else {
setAutoRange(true);
}
}
/**
* Zooms in on the current range.
*
* @param lowerPercent the new lower bound.
* @param upperPercent the new upper bound.
*/
public void zoomRange(double lowerPercent, double upperPercent) {
double start = this.range.getLowerBound();
double length = this.range.getLength();
Range adjusted;
if (isInverted()) {
adjusted = new Range(start + (length * (1 - upperPercent)),
start + (length * (1 - lowerPercent)));
}
else {
adjusted = new Range(start + length * lowerPercent,
start + length * upperPercent);
}
setRange(adjusted);
}
/**
* Slides the axis range by the specified percentage.
*
* @param percent the percentage.
*
* @since 1.0.13
*/
public void pan(double percent) {
Range r = getRange();
double length = range.getLength();
double adj = length * percent;
double lower = r.getLowerBound() + adj;
double upper = r.getUpperBound() + adj;
setRange(lower, upper);
}
/**
* Returns the auto tick index.
*
* @return The auto tick index.
*
* @see #setAutoTickIndex(int)
*/
protected int getAutoTickIndex() {
return this.autoTickIndex;
}
/**
* Sets the auto tick index.
*
* @param index the new value.
*
* @see #getAutoTickIndex()
*/
protected void setAutoTickIndex(int index) {
this.autoTickIndex = index;
}
/**
* Tests the axis 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 ValueAxis)) {
return false;
}
ValueAxis that = (ValueAxis) obj;
if (this.positiveArrowVisible != that.positiveArrowVisible) {
return false;
}
if (this.negativeArrowVisible != that.negativeArrowVisible) {
return false;
}
if (this.inverted != that.inverted) {
return false;
}
// if autoRange is true, then the current range is irrelevant
if (!this.autoRange && !ObjectUtilities.equal(this.range, that.range)) {
return false;
}
if (this.autoRange != that.autoRange) {
return false;
}
if (this.autoRangeMinimumSize != that.autoRangeMinimumSize) {
return false;
}
if (!this.defaultAutoRange.equals(that.defaultAutoRange)) {
return false;
}
if (this.upperMargin != that.upperMargin) {
return false;
}
if (this.lowerMargin != that.lowerMargin) {
return false;
}
if (this.fixedAutoRange != that.fixedAutoRange) {
return false;
}
if (this.autoTickUnitSelection != that.autoTickUnitSelection) {
return false;
}
if (!ObjectUtilities.equal(this.standardTickUnits,
that.standardTickUnits)) {
return false;
}
if (this.verticalTickLabels != that.verticalTickLabels) {
return false;
}
if (this.minorTickCount != that.minorTickCount) {
return false;
}
return super.equals(obj);
}
/**
* Returns a clone of the object.
*
* @return A clone.
*
* @throws CloneNotSupportedException if some component of the axis does
* not support cloning.
*/
@Override
public Object clone() throws CloneNotSupportedException {
ValueAxis clone = (ValueAxis) super.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.upArrow, stream);
SerialUtilities.writeShape(this.downArrow, stream);
SerialUtilities.writeShape(this.leftArrow, stream);
SerialUtilities.writeShape(this.rightArrow, 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.upArrow = SerialUtilities.readShape(stream);
this.downArrow = SerialUtilities.readShape(stream);
this.leftArrow = SerialUtilities.readShape(stream);
this.rightArrow = SerialUtilities.readShape(stream);
}
}
| 58,096 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
CategoryAnchor.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/axis/CategoryAnchor.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.]
*
* -------------------
* CategoryAnchor.java
* -------------------
* (C) Copyright 2003-2008, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes:
* --------
* 04-Jul-2003 : Version 1 (DG);
*
*/
package org.jfree.chart.axis;
/**
* Used to indicate one of three positions within a category:
* <code>START</code>, <code>MIDDLE</code> and <code>END</code>.
*/
public enum CategoryAnchor {
/** Start of period. */
START("CategoryAnchor.START"),
/** Middle of period. */
MIDDLE("CategoryAnchor.MIDDLE"),
/** End of period. */
END("CategoryAnchor.END");
/** The name. */
private String name;
/**
* Private constructor.
*
* @param name the name.
*/
private CategoryAnchor(String name) {
this.name = name;
}
/**
* Returns a string representing the object.
*
* @return The string.
*/
@Override
public String toString() {
return this.name;
}
}
| 2,276 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
AxisSpace.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/axis/AxisSpace.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.]
*
* --------------
* AxisSpace.java
* --------------
* (C) Copyright 2003-2012, by Object Refinery Limited and Contributors.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 03-Jul-2003 : Version 1 (DG);
* 14-Aug-2003 : Implemented Cloneable (DG);
* 18-Aug-2003 : Implemented Serializable (DG);
* 17-Mar-2004 : Added a toString() method for debugging (DG);
* 07-Jan-2005 : Updated equals() method (DG);
* 11-Jan-2005 : Removed deprecated methods in preparation for 1.0.0
* release (DG);
* 16-Jun-2012 : Removed JCommon dependencies (DG);
*
*/
package org.jfree.chart.axis;
import java.awt.geom.Rectangle2D;
import java.io.Serializable;
import org.jfree.chart.ui.RectangleEdge;
import org.jfree.chart.util.PublicCloneable;
/**
* A record that contains the space required at each edge of a plot.
*/
public class AxisSpace implements Cloneable, PublicCloneable, Serializable {
/** For serialization. */
private static final long serialVersionUID = -2490732595134766305L;
/** The top space. */
private double top;
/** The bottom space. */
private double bottom;
/** The left space. */
private double left;
/** The right space. */
private double right;
/**
* Creates a new axis space record.
*/
public AxisSpace() {
this.top = 0.0;
this.bottom = 0.0;
this.left = 0.0;
this.right = 0.0;
}
/**
* Returns the space reserved for axes at the top of the plot area.
*
* @return The space (in Java2D units).
*/
public double getTop() {
return this.top;
}
/**
* Sets the space reserved for axes at the top of the plot area.
*
* @param space the space (in Java2D units).
*/
public void setTop(double space) {
this.top = space;
}
/**
* Returns the space reserved for axes at the bottom of the plot area.
*
* @return The space (in Java2D units).
*/
public double getBottom() {
return this.bottom;
}
/**
* Sets the space reserved for axes at the bottom of the plot area.
*
* @param space the space (in Java2D units).
*/
public void setBottom(double space) {
this.bottom = space;
}
/**
* Returns the space reserved for axes at the left of the plot area.
*
* @return The space (in Java2D units).
*/
public double getLeft() {
return this.left;
}
/**
* Sets the space reserved for axes at the left of the plot area.
*
* @param space the space (in Java2D units).
*/
public void setLeft(double space) {
this.left = space;
}
/**
* Returns the space reserved for axes at the right of the plot area.
*
* @return The space (in Java2D units).
*/
public double getRight() {
return this.right;
}
/**
* Sets the space reserved for axes at the right of the plot area.
*
* @param space the space (in Java2D units).
*/
public void setRight(double space) {
this.right = space;
}
/**
* Adds space to the top, bottom, left or right edge of the plot area.
*
* @param space the space (in Java2D units).
* @param edge the edge (<code>null</code> not permitted).
*/
public void add(double space, RectangleEdge edge) {
if (edge == null) {
throw new IllegalArgumentException("Null 'edge' argument.");
}
if (edge == RectangleEdge.TOP) {
this.top += space;
}
else if (edge == RectangleEdge.BOTTOM) {
this.bottom += space;
}
else if (edge == RectangleEdge.LEFT) {
this.left += space;
}
else if (edge == RectangleEdge.RIGHT) {
this.right += space;
}
else {
throw new IllegalStateException("Unrecognised 'edge' argument.");
}
}
/**
* Ensures that this object reserves at least as much space as another.
*
* @param space the other space.
*/
public void ensureAtLeast(AxisSpace space) {
this.top = Math.max(this.top, space.top);
this.bottom = Math.max(this.bottom, space.bottom);
this.left = Math.max(this.left, space.left);
this.right = Math.max(this.right, space.right);
}
/**
* Ensures there is a minimum amount of space at the edge corresponding to
* the specified axis location.
*
* @param space the space.
* @param edge the location.
*/
public void ensureAtLeast(double space, RectangleEdge edge) {
if (edge == RectangleEdge.TOP) {
if (this.top < space) {
this.top = space;
}
}
else if (edge == RectangleEdge.BOTTOM) {
if (this.bottom < space) {
this.bottom = space;
}
}
else if (edge == RectangleEdge.LEFT) {
if (this.left < space) {
this.left = space;
}
}
else if (edge == RectangleEdge.RIGHT) {
if (this.right < space) {
this.right = space;
}
}
else {
throw new IllegalStateException(
"AxisSpace.ensureAtLeast(): unrecognised AxisLocation."
);
}
}
/**
* Shrinks an area by the space attributes.
*
* @param area the area to shrink.
* @param result an optional carrier for the result.
*
* @return The result.
*/
public Rectangle2D shrink(Rectangle2D area, Rectangle2D result) {
if (result == null) {
result = new Rectangle2D.Double();
}
result.setRect(
area.getX() + this.left,
area.getY() + this.top,
area.getWidth() - this.left - this.right,
area.getHeight() - this.top - this.bottom
);
return result;
}
/**
* Expands an area by the amount of space represented by this object.
*
* @param area the area to expand.
* @param result an optional carrier for the result.
*
* @return The result.
*/
public Rectangle2D expand(Rectangle2D area, Rectangle2D result) {
if (result == null) {
result = new Rectangle2D.Double();
}
result.setRect(
area.getX() - this.left,
area.getY() - this.top,
area.getWidth() + this.left + this.right,
area.getHeight() + this.top + this.bottom
);
return result;
}
/**
* Calculates the reserved area.
*
* @param area the area.
* @param edge the edge.
*
* @return The reserved area.
*/
public Rectangle2D reserved(Rectangle2D area, RectangleEdge edge) {
Rectangle2D result = null;
if (edge == RectangleEdge.TOP) {
result = new Rectangle2D.Double(
area.getX(), area.getY(), area.getWidth(), this.top
);
}
else if (edge == RectangleEdge.BOTTOM) {
result = new Rectangle2D.Double(
area.getX(), area.getMaxY() - this.top,
area.getWidth(), this.bottom
);
}
else if (edge == RectangleEdge.LEFT) {
result = new Rectangle2D.Double(
area.getX(), area.getY(), this.left, area.getHeight()
);
}
else if (edge == RectangleEdge.RIGHT) {
result = new Rectangle2D.Double(
area.getMaxX() - this.right, area.getY(),
this.right, area.getHeight()
);
}
return result;
}
/**
* Returns a clone of the object.
*
* @return A clone.
*
* @throws CloneNotSupportedException This class won't throw this exception,
* but subclasses (if any) might.
*/
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
/**
* Tests this object for equality with another object.
*
* @param obj the object to compare against.
*
* @return <code>true</code> or <code>false</code>.
*/
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof AxisSpace)) {
return false;
}
AxisSpace that = (AxisSpace) obj;
if (this.top != that.top) {
return false;
}
if (this.bottom != that.bottom) {
return false;
}
if (this.left != that.left) {
return false;
}
if (this.right != that.right) {
return false;
}
return true;
}
/**
* Returns a hash code for this object.
*
* @return A hash code.
*/
@Override
public int hashCode() {
int result = 23;
long l = Double.doubleToLongBits(this.top);
result = 37 * result + (int) (l ^ (l >>> 32));
l = Double.doubleToLongBits(this.bottom);
result = 37 * result + (int) (l ^ (l >>> 32));
l = Double.doubleToLongBits(this.left);
result = 37 * result + (int) (l ^ (l >>> 32));
l = Double.doubleToLongBits(this.right);
result = 37 * result + (int) (l ^ (l >>> 32));
return result;
}
/**
* Returns a string representing the object (for debugging purposes).
*
* @return A string.
*/
@Override
public String toString() {
return super.toString() + "[left=" + this.left + ",right=" + this.right
+ ",top=" + this.top + ",bottom=" + this.bottom + "]";
}
}
| 11,041 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
CategoryTick.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/axis/CategoryTick.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.]
*
* -----------------
* CategoryTick.java
* -----------------
* (C) Copyright 2003-2012, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 07-Nov-2003 : Version 1 (DG);
* 13-May-2004 : Added equals() method (DG);
* 17-Jun-2012 : Removed JCommon dependencies (DG);
*
*/
package org.jfree.chart.axis;
import org.jfree.chart.ui.TextAnchor;
import org.jfree.chart.util.ObjectUtilities;
import org.jfree.chart.text.TextBlock;
import org.jfree.chart.text.TextBlockAnchor;
/**
* A tick for a {@link CategoryAxis}.
*/
public class CategoryTick extends Tick {
/** The category. */
private Comparable category;
/** The label. */
private TextBlock label;
/** The label anchor. */
private TextBlockAnchor labelAnchor;
/**
* Creates a new tick.
*
* @param category the category.
* @param label the label.
* @param labelAnchor the label anchor.
* @param rotationAnchor the rotation anchor.
* @param angle the rotation angle (in radians).
*/
public CategoryTick(Comparable category,
TextBlock label,
TextBlockAnchor labelAnchor,
TextAnchor rotationAnchor,
double angle) {
super("", TextAnchor.CENTER, rotationAnchor, angle);
this.category = category;
this.label = label;
this.labelAnchor = labelAnchor;
}
/**
* Returns the category.
*
* @return The category.
*/
public Comparable getCategory() {
return this.category;
}
/**
* Returns the label.
*
* @return The label.
*/
public TextBlock getLabel() {
return this.label;
}
/**
* Returns the label anchor.
*
* @return The label anchor.
*/
public TextBlockAnchor getLabelAnchor() {
return this.labelAnchor;
}
/**
* Tests this category tick 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 CategoryTick && super.equals(obj)) {
CategoryTick that = (CategoryTick) obj;
if (!ObjectUtilities.equal(this.category, that.category)) {
return false;
}
if (!ObjectUtilities.equal(this.label, that.label)) {
return false;
}
if (!ObjectUtilities.equal(this.labelAnchor, that.labelAnchor)) {
return false;
}
return true;
}
return false;
}
/**
* Returns a hash code for this object.
*
* @return A hash code.
*/
@Override
public int hashCode() {
int result = 41;
result = 37 * result + this.category.hashCode();
result = 37 * result + this.label.hashCode();
result = 37 * result + this.labelAnchor.hashCode();
return result;
}
}
| 4,408 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
CategoryLabelPositions.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/axis/CategoryLabelPositions.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.]
*
* ---------------------------
* CategoryLabelPositions.java
* ---------------------------
* (C) Copyright 2004-2012, by Object Refinery Limited and Contributors.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 06-Jan-2004 : Version 1 (DG);
* 17-Feb-2004 : Added equals() method (DG);
* 05-Nov-2004 : Adjusted settings for UP_90 and DOWN_90 (DG);
* 16-Jun-2012 : Removed JCommon dependencies (DG);
*
*/
package org.jfree.chart.axis;
import java.io.Serializable;
import org.jfree.chart.ui.RectangleAnchor;
import org.jfree.chart.ui.RectangleEdge;
import org.jfree.chart.ui.TextAnchor;
import org.jfree.chart.text.TextBlockAnchor;
/**
* Records the label positions for a category axis. Instances of this class
* are immutable.
*/
public class CategoryLabelPositions implements Serializable {
/** For serialization. */
private static final long serialVersionUID = -8999557901920364580L;
/** STANDARD category label positions. */
public static final CategoryLabelPositions
STANDARD = new CategoryLabelPositions(
new CategoryLabelPosition(
RectangleAnchor.BOTTOM, TextBlockAnchor.BOTTOM_CENTER
), // TOP
new CategoryLabelPosition(
RectangleAnchor.TOP, TextBlockAnchor.TOP_CENTER
), // BOTTOM
new CategoryLabelPosition(
RectangleAnchor.RIGHT, TextBlockAnchor.CENTER_RIGHT,
CategoryLabelWidthType.RANGE, 0.30f
), // LEFT
new CategoryLabelPosition(
RectangleAnchor.LEFT, TextBlockAnchor.CENTER_LEFT,
CategoryLabelWidthType.RANGE, 0.30f
) // RIGHT
);
/** UP_90 category label positions. */
public static final CategoryLabelPositions
UP_90 = new CategoryLabelPositions(
new CategoryLabelPosition(
RectangleAnchor.BOTTOM, TextBlockAnchor.CENTER_LEFT,
TextAnchor.CENTER_LEFT, -Math.PI / 2.0,
CategoryLabelWidthType.RANGE, 0.30f
), // TOP
new CategoryLabelPosition(
RectangleAnchor.TOP, TextBlockAnchor.CENTER_RIGHT,
TextAnchor.CENTER_RIGHT, -Math.PI / 2.0,
CategoryLabelWidthType.RANGE, 0.30f
), // BOTTOM
new CategoryLabelPosition(
RectangleAnchor.RIGHT, TextBlockAnchor.BOTTOM_CENTER,
TextAnchor.BOTTOM_CENTER, -Math.PI / 2.0,
CategoryLabelWidthType.CATEGORY, 0.9f
), // LEFT
new CategoryLabelPosition(
RectangleAnchor.LEFT, TextBlockAnchor.TOP_CENTER,
TextAnchor.TOP_CENTER, -Math.PI / 2.0,
CategoryLabelWidthType.CATEGORY, 0.90f
) // RIGHT
);
/** DOWN_90 category label positions. */
public static final CategoryLabelPositions
DOWN_90 = new CategoryLabelPositions(
new CategoryLabelPosition(
RectangleAnchor.BOTTOM, TextBlockAnchor.CENTER_RIGHT,
TextAnchor.CENTER_RIGHT, Math.PI / 2.0,
CategoryLabelWidthType.RANGE, 0.30f
), // TOP
new CategoryLabelPosition(
RectangleAnchor.TOP, TextBlockAnchor.CENTER_LEFT,
TextAnchor.CENTER_LEFT, Math.PI / 2.0,
CategoryLabelWidthType.RANGE, 0.30f
), // BOTTOM
new CategoryLabelPosition(
RectangleAnchor.RIGHT, TextBlockAnchor.TOP_CENTER,
TextAnchor.TOP_CENTER, Math.PI / 2.0,
CategoryLabelWidthType.CATEGORY, 0.90f
), // LEFT
new CategoryLabelPosition(
RectangleAnchor.LEFT, TextBlockAnchor.BOTTOM_CENTER,
TextAnchor.BOTTOM_CENTER, Math.PI / 2.0,
CategoryLabelWidthType.CATEGORY, 0.90f
) // RIGHT
);
/** UP_45 category label positions. */
public static final CategoryLabelPositions UP_45
= createUpRotationLabelPositions(Math.PI / 4.0);
/** DOWN_45 category label positions. */
public static final CategoryLabelPositions DOWN_45
= createDownRotationLabelPositions(Math.PI / 4.0);
/**
* Creates a new instance where the category labels angled upwards by the
* specified amount.
*
* @param angle the rotation angle (should be < Math.PI / 2.0).
*
* @return A category label position specification.
*/
public static CategoryLabelPositions createUpRotationLabelPositions(
double angle) {
return new CategoryLabelPositions(
new CategoryLabelPosition(
RectangleAnchor.BOTTOM, TextBlockAnchor.BOTTOM_LEFT,
TextAnchor.BOTTOM_LEFT, -angle,
CategoryLabelWidthType.RANGE, 0.50f
), // TOP
new CategoryLabelPosition(
RectangleAnchor.TOP, TextBlockAnchor.TOP_RIGHT,
TextAnchor.TOP_RIGHT, -angle,
CategoryLabelWidthType.RANGE, 0.50f
), // BOTTOM
new CategoryLabelPosition(
RectangleAnchor.RIGHT, TextBlockAnchor.BOTTOM_RIGHT,
TextAnchor.BOTTOM_RIGHT, -angle,
CategoryLabelWidthType.RANGE, 0.50f
), // LEFT
new CategoryLabelPosition(
RectangleAnchor.LEFT, TextBlockAnchor.TOP_LEFT,
TextAnchor.TOP_LEFT, -angle,
CategoryLabelWidthType.RANGE, 0.50f
) // RIGHT
);
}
/**
* Creates a new instance where the category labels angled downwards by the
* specified amount.
*
* @param angle the rotation angle (should be < Math.PI / 2.0).
*
* @return A category label position specification.
*/
public static CategoryLabelPositions createDownRotationLabelPositions(
double angle) {
return new CategoryLabelPositions(
new CategoryLabelPosition(
RectangleAnchor.BOTTOM, TextBlockAnchor.BOTTOM_RIGHT,
TextAnchor.BOTTOM_RIGHT, angle,
CategoryLabelWidthType.RANGE, 0.50f
), // TOP
new CategoryLabelPosition(
RectangleAnchor.TOP, TextBlockAnchor.TOP_LEFT,
TextAnchor.TOP_LEFT, angle,
CategoryLabelWidthType.RANGE, 0.50f
), // BOTTOM
new CategoryLabelPosition(
RectangleAnchor.RIGHT, TextBlockAnchor.TOP_RIGHT,
TextAnchor.TOP_RIGHT, angle,
CategoryLabelWidthType.RANGE, 0.50f
), // LEFT
new CategoryLabelPosition(
RectangleAnchor.LEFT, TextBlockAnchor.BOTTOM_LEFT,
TextAnchor.BOTTOM_LEFT, angle,
CategoryLabelWidthType.RANGE, 0.50f
) // RIGHT
);
}
/**
* The label positioning details used when an axis is at the top of a
* chart.
*/
private CategoryLabelPosition positionForAxisAtTop;
/**
* The label positioning details used when an axis is at the bottom of a
* chart.
*/
private CategoryLabelPosition positionForAxisAtBottom;
/**
* The label positioning details used when an axis is at the left of a
* chart.
*/
private CategoryLabelPosition positionForAxisAtLeft;
/**
* The label positioning details used when an axis is at the right of a
* chart.
*/
private CategoryLabelPosition positionForAxisAtRight;
/**
* Default constructor.
*/
public CategoryLabelPositions() {
this.positionForAxisAtTop = new CategoryLabelPosition();
this.positionForAxisAtBottom = new CategoryLabelPosition();
this.positionForAxisAtLeft = new CategoryLabelPosition();
this.positionForAxisAtRight = new CategoryLabelPosition();
}
/**
* Creates a new position specification.
*
* @param top the label position info used when an axis is at the top
* (<code>null</code> not permitted).
* @param bottom the label position info used when an axis is at the
* bottom (<code>null</code> not permitted).
* @param left the label position info used when an axis is at the left
* (<code>null</code> not permitted).
* @param right the label position info used when an axis is at the right
* (<code>null</code> not permitted).
*/
public CategoryLabelPositions(CategoryLabelPosition top,
CategoryLabelPosition bottom,
CategoryLabelPosition left,
CategoryLabelPosition right) {
if (top == null) {
throw new IllegalArgumentException("Null 'top' argument.");
}
if (bottom == null) {
throw new IllegalArgumentException("Null 'bottom' argument.");
}
if (left == null) {
throw new IllegalArgumentException("Null 'left' argument.");
}
if (right == null) {
throw new IllegalArgumentException("Null 'right' argument.");
}
this.positionForAxisAtTop = top;
this.positionForAxisAtBottom = bottom;
this.positionForAxisAtLeft = left;
this.positionForAxisAtRight = right;
}
/**
* Returns the category label position specification for an axis at the
* given location.
*
* @param edge the axis location.
*
* @return The category label position specification.
*/
public CategoryLabelPosition getLabelPosition(RectangleEdge edge) {
CategoryLabelPosition result = null;
if (edge == RectangleEdge.TOP) {
result = this.positionForAxisAtTop;
}
else if (edge == RectangleEdge.BOTTOM) {
result = this.positionForAxisAtBottom;
}
else if (edge == RectangleEdge.LEFT) {
result = this.positionForAxisAtLeft;
}
else if (edge == RectangleEdge.RIGHT) {
result = this.positionForAxisAtRight;
}
return result;
}
/**
* Returns a new instance based on an existing instance but with the top
* position changed.
*
* @param base the base (<code>null</code> not permitted).
* @param top the top position (<code>null</code> not permitted).
*
* @return A new instance (never <code>null</code>).
*/
public static CategoryLabelPositions replaceTopPosition(
CategoryLabelPositions base, CategoryLabelPosition top) {
if (base == null) {
throw new IllegalArgumentException("Null 'base' argument.");
}
if (top == null) {
throw new IllegalArgumentException("Null 'top' argument.");
}
return new CategoryLabelPositions(
top,
base.getLabelPosition(RectangleEdge.BOTTOM),
base.getLabelPosition(RectangleEdge.LEFT),
base.getLabelPosition(RectangleEdge.RIGHT)
);
}
/**
* Returns a new instance based on an existing instance but with the bottom
* position changed.
*
* @param base the base (<code>null</code> not permitted).
* @param bottom the bottom position (<code>null</code> not permitted).
*
* @return A new instance (never <code>null</code>).
*/
public static CategoryLabelPositions replaceBottomPosition(
CategoryLabelPositions base, CategoryLabelPosition bottom) {
if (base == null) {
throw new IllegalArgumentException("Null 'base' argument.");
}
if (bottom == null) {
throw new IllegalArgumentException("Null 'bottom' argument.");
}
return new CategoryLabelPositions(
base.getLabelPosition(RectangleEdge.TOP),
bottom,
base.getLabelPosition(RectangleEdge.LEFT),
base.getLabelPosition(RectangleEdge.RIGHT)
);
}
/**
* Returns a new instance based on an existing instance but with the left
* position changed.
*
* @param base the base (<code>null</code> not permitted).
* @param left the left position (<code>null</code> not permitted).
*
* @return A new instance (never <code>null</code>).
*/
public static CategoryLabelPositions replaceLeftPosition(
CategoryLabelPositions base, CategoryLabelPosition left) {
if (base == null) {
throw new IllegalArgumentException("Null 'base' argument.");
}
if (left == null) {
throw new IllegalArgumentException("Null 'left' argument.");
}
return new CategoryLabelPositions(
base.getLabelPosition(RectangleEdge.TOP),
base.getLabelPosition(RectangleEdge.BOTTOM),
left,
base.getLabelPosition(RectangleEdge.RIGHT)
);
}
/**
* Returns a new instance based on an existing instance but with the right
* position changed.
*
* @param base the base (<code>null</code> not permitted).
* @param right the right position (<code>null</code> not permitted).
*
* @return A new instance (never <code>null</code>).
*/
public static CategoryLabelPositions replaceRightPosition(
CategoryLabelPositions base, CategoryLabelPosition right) {
if (base == null) {
throw new IllegalArgumentException("Null 'base' argument.");
}
if (right == null) {
throw new IllegalArgumentException("Null 'right' argument.");
}
return new CategoryLabelPositions(
base.getLabelPosition(RectangleEdge.TOP),
base.getLabelPosition(RectangleEdge.BOTTOM),
base.getLabelPosition(RectangleEdge.LEFT),
right
);
}
/**
* Returns <code>true</code> if this object is equal to the specified
* object, and <code>false</code> otherwise.
*
* @param obj the other object.
*
* @return A boolean.
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof CategoryLabelPositions)) {
return false;
}
CategoryLabelPositions that = (CategoryLabelPositions) obj;
if (!this.positionForAxisAtTop.equals(that.positionForAxisAtTop)) {
return false;
}
if (!this.positionForAxisAtBottom.equals(
that.positionForAxisAtBottom)) {
return false;
}
if (!this.positionForAxisAtLeft.equals(that.positionForAxisAtLeft)) {
return false;
}
if (!this.positionForAxisAtRight.equals(that.positionForAxisAtRight)) {
return false;
}
return true;
}
/**
* Returns a hash code for this object.
*
* @return A hash code.
*/
@Override
public int hashCode() {
int result = 19;
result = 37 * result + this.positionForAxisAtTop.hashCode();
result = 37 * result + this.positionForAxisAtBottom.hashCode();
result = 37 * result + this.positionForAxisAtLeft.hashCode();
result = 37 * result + this.positionForAxisAtRight.hashCode();
return result;
}
}
| 16,671 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
AxisLocation.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/axis/AxisLocation.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.]
*
* -----------------
* AxisLocation.java
* -----------------
* (C) Copyright 2003-2008, by Object Refinery Limited and Contributors.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): Nick Guenther;
*
* Changes:
* --------
* 02-May-2003 : Version 1 (DG);
* 03-Jul-2003 : Added isTopOrBottom() and isLeftOrRight() methods (DG);
* 13-Aug-2003 : Fixed readResolve() bug (id=788202) (DG);
* 24-Mar-2004 : Added static getOpposite() method (DG);
* ------------- JFREECHART 1.0.x ---------------------------------------------
* 22-Mar-2007 : Added getOpposite() method, suggested by Nick Guenther (DG);
*
*/
package org.jfree.chart.axis;
/**
* Used to indicate the location of an axis on a 2D plot, prior to knowing the
* orientation of the plot.
*/
public enum AxisLocation {
/** Axis at the top or left. */
TOP_OR_LEFT("AxisLocation.TOP_OR_LEFT"),
/** Axis at the top or right. */
TOP_OR_RIGHT("AxisLocation.TOP_OR_RIGHT"),
/** Axis at the bottom or left. */
BOTTOM_OR_LEFT("AxisLocation.BOTTOM_OR_LEFT"),
/** Axis at the bottom or right. */
BOTTOM_OR_RIGHT("AxisLocation.BOTTOM_OR_RIGHT");
/** The name. */
private String name;
/**
* Private constructor.
*
* @param name the name.
*/
private AxisLocation(String name) {
this.name = name;
}
/**
* Returns the location that is opposite to this location.
*
* @return The opposite location.
*
* @since 1.0.5
*/
public AxisLocation getOpposite() {
return getOpposite(this);
}
/**
* Returns a string representing the object.
*
* @return The string.
*/
@Override
public String toString() {
return this.name;
}
/**
* Returns the location that is opposite to the supplied location.
*
* @param location the location (<code>null</code> not permitted).
*
* @return The opposite location.
*/
public static AxisLocation getOpposite(AxisLocation location) {
if (location == null) {
throw new IllegalArgumentException("Null 'location' argument.");
}
AxisLocation result;
if (location == AxisLocation.TOP_OR_LEFT) {
result = AxisLocation.BOTTOM_OR_RIGHT;
}
else if (location == AxisLocation.TOP_OR_RIGHT) {
result = AxisLocation.BOTTOM_OR_LEFT;
}
else if (location == AxisLocation.BOTTOM_OR_LEFT) {
result = AxisLocation.TOP_OR_RIGHT;
}
else if (location == AxisLocation.BOTTOM_OR_RIGHT) {
result = AxisLocation.TOP_OR_LEFT;
}
else {
throw new IllegalStateException("AxisLocation not recognised.");
}
return result;
}
}
| 4,043 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
NumberTick.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/axis/NumberTick.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.]
*
* ---------------
* NumberTick.java
* ---------------
* (C) Copyright 2003-2014, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 07-Nov-2003 : Version 1 (DG);
* 02-Aug-2007 : Added new constructor with tick type (DG);
* 17-Jun-2012 : Removed JCommon dependencies (DG);
*
*/
package org.jfree.chart.axis;
import org.jfree.chart.ui.TextAnchor;
/**
* A numerical tick.
*/
public class NumberTick extends ValueTick {
/** The number. */
private Number number;
/**
* Creates a new tick.
*
* @param number the number (<code>null</code> not permitted).
* @param label the label.
* @param textAnchor the part of the label that is aligned with the anchor
* point.
* @param rotationAnchor defines the rotation point relative to the text.
* @param angle the rotation angle (in radians).
*/
public NumberTick(Number number, String label,
TextAnchor textAnchor,
TextAnchor rotationAnchor, double angle) {
super(number.doubleValue(), label, textAnchor, rotationAnchor, angle);
this.number = number;
}
/**
* Creates a new tick.
*
* @param tickType the tick type.
* @param value the value.
* @param label the label.
* @param textAnchor the part of the label that is aligned with the anchor
* point.
* @param rotationAnchor defines the rotation point relative to the text.
* @param angle the rotation angle (in radians).
*
* @since 1.0.7
*/
public NumberTick(TickType tickType, double value, String label,
TextAnchor textAnchor,
TextAnchor rotationAnchor, double angle) {
super(tickType, value, label, textAnchor, rotationAnchor, angle);
this.number = value;
}
/**
* Returns the number.
*
* @return The number.
*/
public Number getNumber() {
return this.number;
}
}
| 3,341 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
PeriodAxis.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/axis/PeriodAxis.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.]
*
* ---------------
* PeriodAxis.java
* ---------------
* (C) Copyright 2004-2013, by Object Refinery Limited and Contributors.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 01-Jun-2004 : Version 1 (DG);
* 16-Sep-2004 : Fixed bug in equals() method, added clone() method and
* PublicCloneable interface (DG);
* 25-Nov-2004 : Updates to support major and minor tick marks (DG);
* 25-Feb-2005 : Fixed some tick mark bugs (DG);
* 15-Apr-2005 : Fixed some more tick mark bugs (DG);
* 26-Apr-2005 : Removed LOGGER (DG);
* 16-Jun-2005 : Fixed zooming (DG);
* 15-Sep-2005 : Changed configure() method to check autoRange flag,
* and added ticks to state (DG);
* ------------- JFREECHART 1.0.x ---------------------------------------------
* 06-Oct-2006 : Updated for deprecations in RegularTimePeriod and
* subclasses (DG);
* 22-Mar-2007 : Use new defaultAutoRange attribute (DG);
* 31-Jul-2007 : Fix for inverted axis labelling (see bug 1763413) (DG);
* 08-Apr-2008 : Notify listeners in setRange(Range, boolean, boolean) - fixes
* bug 1932146 (DG);
* 16-Jan-2009 : Fixed bug 2490803, a problem in the setRange() method (DG);
* 02-Mar-2009 : Added locale - see patch 2569670 by Benjamin Bignell (DG);
* 02-Mar-2009 : Fixed draw() method to check tickMarksVisible and
* tickLabelsVisible (DG);
* 19-May-2009 : Fixed FindBugs warnings, patch by Michal Wozniak (DG);
* 17-Jun-2012 : Removed JCommon dependencies (DG);
*
*/
package org.jfree.chart.axis;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.Stroke;
import java.awt.geom.Line2D;
import java.awt.geom.Rectangle2D;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.lang.reflect.Constructor;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
import org.jfree.chart.ui.RectangleEdge;
import org.jfree.chart.ui.TextAnchor;
import org.jfree.chart.util.PublicCloneable;
import org.jfree.chart.event.AxisChangeEvent;
import org.jfree.chart.plot.Plot;
import org.jfree.chart.plot.PlotRenderingInfo;
import org.jfree.chart.plot.ValueAxisPlot;
import org.jfree.chart.text.TextUtilities;
import org.jfree.chart.util.ParamChecks;
import org.jfree.chart.util.SerialUtilities;
import org.jfree.data.Range;
import org.jfree.data.time.Day;
import org.jfree.data.time.Month;
import org.jfree.data.time.RegularTimePeriod;
import org.jfree.data.time.Year;
/**
* An axis that displays a date scale based on a
* {@link org.jfree.data.time.RegularTimePeriod}. This axis works when
* displayed across the bottom or top of a plot, but is broken for display at
* the left or right of charts.
*/
public class PeriodAxis extends ValueAxis
implements Cloneable, PublicCloneable, Serializable {
/** For serialization. */
private static final long serialVersionUID = 8353295532075872069L;
/** The first time period in the overall range. */
private RegularTimePeriod first;
/** The last time period in the overall range. */
private RegularTimePeriod last;
/**
* The time zone used to convert 'first' and 'last' to absolute
* milliseconds.
*/
private TimeZone timeZone;
/**
* The locale (never <code>null</code>).
*
* @since 1.0.13
*/
private Locale locale;
/**
* A calendar used for date manipulations in the current time zone and
* locale.
*/
private Calendar calendar;
/**
* The {@link RegularTimePeriod} subclass used to automatically determine
* the axis range.
*/
private Class autoRangeTimePeriodClass;
/**
* Indicates the {@link RegularTimePeriod} subclass that is used to
* determine the spacing of the major tick marks.
*/
private Class majorTickTimePeriodClass;
/**
* A flag that indicates whether or not tick marks are visible for the
* axis.
*/
private boolean minorTickMarksVisible;
/**
* Indicates the {@link RegularTimePeriod} subclass that is used to
* determine the spacing of the minor tick marks.
*/
private Class minorTickTimePeriodClass;
/** The length of the tick mark inside the data area (zero permitted). */
private float minorTickMarkInsideLength = 0.0f;
/** The length of the tick mark outside the data area (zero permitted). */
private float minorTickMarkOutsideLength = 2.0f;
/** The stroke used to draw tick marks. */
private transient Stroke minorTickMarkStroke = new BasicStroke(0.5f);
/** The paint used to draw tick marks. */
private transient Paint minorTickMarkPaint = Color.BLACK;
/** Info for each labeling band. */
private PeriodAxisLabelInfo[] labelInfo;
/**
* Creates a new axis.
*
* @param label the axis label.
*/
public PeriodAxis(String label) {
this(label, new Day(), new Day());
}
/**
* Creates a new axis.
*
* @param label the axis label (<code>null</code> permitted).
* @param first the first time period in the axis range
* (<code>null</code> not permitted).
* @param last the last time period in the axis range
* (<code>null</code> not permitted).
*/
public PeriodAxis(String label,
RegularTimePeriod first, RegularTimePeriod last) {
this(label, first, last, TimeZone.getDefault(), Locale.getDefault());
}
/**
* Creates a new axis.
*
* @param label the axis label (<code>null</code> permitted).
* @param first the first time period in the axis range
* (<code>null</code> not permitted).
* @param last the last time period in the axis range
* (<code>null</code> not permitted).
* @param timeZone the time zone (<code>null</code> not permitted).
* @param locale the locale (<code>null</code> not permitted).
*
* @since 1.0.13
*/
public PeriodAxis(String label, RegularTimePeriod first,
RegularTimePeriod last, TimeZone timeZone, Locale locale) {
super(label, null);
ParamChecks.nullNotPermitted(timeZone, "timeZone");
ParamChecks.nullNotPermitted(locale, "locale");
this.first = first;
this.last = last;
this.timeZone = timeZone;
this.locale = locale;
this.calendar = Calendar.getInstance(timeZone, locale);
this.first.peg(this.calendar);
this.last.peg(this.calendar);
this.autoRangeTimePeriodClass = first.getClass();
this.majorTickTimePeriodClass = first.getClass();
this.minorTickMarksVisible = false;
this.minorTickTimePeriodClass = RegularTimePeriod.downsize(
this.majorTickTimePeriodClass);
setAutoRange(true);
this.labelInfo = new PeriodAxisLabelInfo[2];
SimpleDateFormat df0 = new SimpleDateFormat("MMM", locale);
df0.setTimeZone(timeZone);
this.labelInfo[0] = new PeriodAxisLabelInfo(Month.class, df0);
SimpleDateFormat df1 = new SimpleDateFormat("yyyy", locale);
df1.setTimeZone(timeZone);
this.labelInfo[1] = new PeriodAxisLabelInfo(Year.class, df1);
}
/**
* Returns the first time period in the axis range.
*
* @return The first time period (never <code>null</code>).
*/
public RegularTimePeriod getFirst() {
return this.first;
}
/**
* Sets the first time period in the axis range and sends an
* {@link AxisChangeEvent} to all registered listeners.
*
* @param first the time period (<code>null</code> not permitted).
*/
public void setFirst(RegularTimePeriod first) {
ParamChecks.nullNotPermitted(first, "first");
this.first = first;
this.first.peg(this.calendar);
fireChangeEvent();
}
/**
* Returns the last time period in the axis range.
*
* @return The last time period (never <code>null</code>).
*/
public RegularTimePeriod getLast() {
return this.last;
}
/**
* Sets the last time period in the axis range and sends an
* {@link AxisChangeEvent} to all registered listeners.
*
* @param last the time period (<code>null</code> not permitted).
*/
public void setLast(RegularTimePeriod last) {
ParamChecks.nullNotPermitted(last, "last");
this.last = last;
this.last.peg(this.calendar);
fireChangeEvent();
}
/**
* Returns the time zone used to convert the periods defining the axis
* range into absolute milliseconds.
*
* @return The time zone (never <code>null</code>).
*/
public TimeZone getTimeZone() {
return this.timeZone;
}
/**
* Sets the time zone that is used to convert the time periods into
* absolute milliseconds.
*
* @param zone the time zone (<code>null</code> not permitted).
*/
public void setTimeZone(TimeZone zone) {
ParamChecks.nullNotPermitted(zone, "zone");
this.timeZone = zone;
this.calendar = Calendar.getInstance(zone, this.locale);
this.first.peg(this.calendar);
this.last.peg(this.calendar);
fireChangeEvent();
}
/**
* Returns the locale for this axis.
*
* @return The locale (never (<code>null</code>).
*
* @since 1.0.13
*/
public Locale getLocale() {
return this.locale;
}
/**
* Returns the class used to create the first and last time periods for
* the axis range when the auto-range flag is set to <code>true</code>.
*
* @return The class (never <code>null</code>).
*/
public Class getAutoRangeTimePeriodClass() {
return this.autoRangeTimePeriodClass;
}
/**
* Sets the class used to create the first and last time periods for the
* axis range when the auto-range flag is set to <code>true</code> and
* sends an {@link AxisChangeEvent} to all registered listeners.
*
* @param c the class (<code>null</code> not permitted).
*/
public void setAutoRangeTimePeriodClass(Class c) {
ParamChecks.nullNotPermitted(c, "c");
this.autoRangeTimePeriodClass = c;
fireChangeEvent();
}
/**
* Returns the class that controls the spacing of the major tick marks.
*
* @return The class (never <code>null</code>).
*/
public Class getMajorTickTimePeriodClass() {
return this.majorTickTimePeriodClass;
}
/**
* Sets the class that controls the spacing of the major tick marks, and
* sends an {@link AxisChangeEvent} to all registered listeners.
*
* @param c the class (a subclass of {@link RegularTimePeriod} is
* expected).
*/
public void setMajorTickTimePeriodClass(Class c) {
ParamChecks.nullNotPermitted(c, "c");
this.majorTickTimePeriodClass = c;
fireChangeEvent();
}
/**
* Returns the flag that controls whether or not minor tick marks
* are displayed for the axis.
*
* @return A boolean.
*/
@Override
public boolean isMinorTickMarksVisible() {
return this.minorTickMarksVisible;
}
/**
* Sets the flag that controls whether or not minor tick marks
* are displayed for the axis, and sends a {@link AxisChangeEvent}
* to all registered listeners.
*
* @param visible the flag.
*/
@Override
public void setMinorTickMarksVisible(boolean visible) {
this.minorTickMarksVisible = visible;
fireChangeEvent();
}
/**
* Returns the class that controls the spacing of the minor tick marks.
*
* @return The class (never <code>null</code>).
*/
public Class getMinorTickTimePeriodClass() {
return this.minorTickTimePeriodClass;
}
/**
* Sets the class that controls the spacing of the minor tick marks, and
* sends an {@link AxisChangeEvent} to all registered listeners.
*
* @param c the class (a subclass of {@link RegularTimePeriod} is
* expected).
*/
public void setMinorTickTimePeriodClass(Class c) {
ParamChecks.nullNotPermitted(c, "c");
this.minorTickTimePeriodClass = c;
fireChangeEvent();
}
/**
* Returns the stroke used to display minor tick marks, if they are
* visible.
*
* @return A stroke (never <code>null</code>).
*/
public Stroke getMinorTickMarkStroke() {
return this.minorTickMarkStroke;
}
/**
* Sets the stroke used to display minor tick marks, if they are
* visible, and sends a {@link AxisChangeEvent} to all registered
* listeners.
*
* @param stroke the stroke (<code>null</code> not permitted).
*/
public void setMinorTickMarkStroke(Stroke stroke) {
ParamChecks.nullNotPermitted(stroke, "stroke");
this.minorTickMarkStroke = stroke;
fireChangeEvent();
}
/**
* Returns the paint used to display minor tick marks, if they are
* visible.
*
* @return A paint (never <code>null</code>).
*/
public Paint getMinorTickMarkPaint() {
return this.minorTickMarkPaint;
}
/**
* Sets the paint used to display minor tick marks, if they are
* visible, and sends a {@link AxisChangeEvent} to all registered
* listeners.
*
* @param paint the paint (<code>null</code> not permitted).
*/
public void setMinorTickMarkPaint(Paint paint) {
ParamChecks.nullNotPermitted(paint, "paint");
this.minorTickMarkPaint = paint;
fireChangeEvent();
}
/**
* Returns the inside length for the minor tick marks.
*
* @return The length.
*/
@Override
public float getMinorTickMarkInsideLength() {
return this.minorTickMarkInsideLength;
}
/**
* Sets the inside length of the minor tick marks and sends an
* {@link AxisChangeEvent} to all registered listeners.
*
* @param length the length.
*/
@Override
public void setMinorTickMarkInsideLength(float length) {
this.minorTickMarkInsideLength = length;
fireChangeEvent();
}
/**
* Returns the outside length for the minor tick marks.
*
* @return The length.
*/
@Override
public float getMinorTickMarkOutsideLength() {
return this.minorTickMarkOutsideLength;
}
/**
* Sets the outside length of the minor tick marks and sends an
* {@link AxisChangeEvent} to all registered listeners.
*
* @param length the length.
*/
@Override
public void setMinorTickMarkOutsideLength(float length) {
this.minorTickMarkOutsideLength = length;
fireChangeEvent();
}
/**
* Returns an array of label info records.
*
* @return An array.
*/
public PeriodAxisLabelInfo[] getLabelInfo() {
return this.labelInfo;
}
/**
* Sets the array of label info records and sends an
* {@link AxisChangeEvent} to all registered listeners.
*
* @param info the info.
*/
public void setLabelInfo(PeriodAxisLabelInfo[] info) {
this.labelInfo = info;
fireChangeEvent();
}
/**
* Sets the range for the axis, if requested, sends an
* {@link AxisChangeEvent} to all registered listeners. As a side-effect,
* the auto-range flag is set to <code>false</code> (optional).
*
* @param range the range (<code>null</code> not permitted).
* @param turnOffAutoRange a flag that controls whether or not the auto
* range is turned off.
* @param notify a flag that controls whether or not listeners are
* notified.
*/
@Override
public void setRange(Range range, boolean turnOffAutoRange,
boolean notify) {
long upper = Math.round(range.getUpperBound());
long lower = Math.round(range.getLowerBound());
this.first = createInstance(this.autoRangeTimePeriodClass,
new Date(lower), this.timeZone, this.locale);
this.last = createInstance(this.autoRangeTimePeriodClass,
new Date(upper), this.timeZone, this.locale);
super.setRange(new Range(this.first.getFirstMillisecond(),
this.last.getLastMillisecond() + 1.0), turnOffAutoRange,
notify);
}
/**
* Configures the axis to work with the current plot. Override this method
* to perform any special processing (such as auto-rescaling).
*/
@Override
public void configure() {
if (this.isAutoRange()) {
autoAdjustRange();
}
}
/**
* Estimates the space (height or width) required to draw the axis.
*
* @param g2 the graphics device.
* @param plot the plot that the axis belongs to.
* @param plotArea the area within which the plot (including axes) should
* be drawn.
* @param edge the axis location.
* @param space space already reserved.
*
* @return The space required to draw the axis (including pre-reserved
* space).
*/
@Override
public AxisSpace reserveSpace(Graphics2D g2, Plot plot,
Rectangle2D plotArea, RectangleEdge edge,
AxisSpace space) {
// create a new space object if one wasn't supplied...
if (space == null) {
space = new AxisSpace();
}
// if the axis is not visible, no additional space is required...
if (!isVisible()) {
return space;
}
// if the axis has a fixed dimension, return it...
double dimension = getFixedDimension();
if (dimension > 0.0) {
space.ensureAtLeast(dimension, edge);
}
// get the axis label size and update the space object...
Rectangle2D labelEnclosure = getLabelEnclosure(g2, edge);
double labelHeight, labelWidth;
double tickLabelBandsDimension = 0.0;
for (PeriodAxisLabelInfo info : this.labelInfo) {
FontMetrics fm = g2.getFontMetrics(info.getLabelFont());
tickLabelBandsDimension
+= info.getPadding().extendHeight(fm.getHeight());
}
if (RectangleEdge.isTopOrBottom(edge)) {
labelHeight = labelEnclosure.getHeight();
space.add(labelHeight + tickLabelBandsDimension, edge);
}
else if (RectangleEdge.isLeftOrRight(edge)) {
labelWidth = labelEnclosure.getWidth();
space.add(labelWidth + tickLabelBandsDimension, edge);
}
// add space for the outer tick labels, if any...
double tickMarkSpace = 0.0;
if (isTickMarksVisible()) {
tickMarkSpace = getTickMarkOutsideLength();
}
if (this.minorTickMarksVisible) {
tickMarkSpace = Math.max(tickMarkSpace,
this.minorTickMarkOutsideLength);
}
space.add(tickMarkSpace, edge);
return space;
}
/**
* Draws the axis on a Java 2D graphics device (such as the screen or a
* printer).
*
* @param g2 the graphics device (<code>null</code> not permitted).
* @param cursor the cursor location (determines where to draw the axis).
* @param plotArea the area within which the axes and plot should be drawn.
* @param dataArea the area within which the data should be drawn.
* @param edge the axis location (<code>null</code> not permitted).
* @param plotState collects information about the plot
* (<code>null</code> permitted).
*
* @return The axis state (never <code>null</code>).
*/
@Override
public AxisState draw(Graphics2D g2, double cursor, Rectangle2D plotArea,
Rectangle2D dataArea, RectangleEdge edge,
PlotRenderingInfo plotState) {
AxisState axisState = new AxisState(cursor);
if (isAxisLineVisible()) {
drawAxisLine(g2, cursor, dataArea, edge);
}
if (isTickMarksVisible()) {
drawTickMarks(g2, axisState, dataArea, edge);
}
if (isTickLabelsVisible()) {
for (int band = 0; band < this.labelInfo.length; band++) {
axisState = drawTickLabels(band, g2, axisState, dataArea, edge);
}
}
// draw the axis label (note that 'state' is passed in *and*
// returned)...
axisState = drawLabel(getLabel(), g2, plotArea, dataArea, edge,
axisState);
return axisState;
}
/**
* Draws the tick marks for the axis.
*
* @param g2 the graphics device.
* @param state the axis state.
* @param dataArea the data area.
* @param edge the edge.
*/
protected void drawTickMarks(Graphics2D g2, AxisState state,
Rectangle2D dataArea,
RectangleEdge edge) {
if (RectangleEdge.isTopOrBottom(edge)) {
drawTickMarksHorizontal(g2, state, dataArea, edge);
}
else if (RectangleEdge.isLeftOrRight(edge)) {
drawTickMarksVertical(g2, state, dataArea, edge);
}
}
/**
* Draws the major and minor tick marks for an axis that lies at the top or
* bottom of the plot.
*
* @param g2 the graphics device.
* @param state the axis state.
* @param dataArea the data area.
* @param edge the edge.
*/
protected void drawTickMarksHorizontal(Graphics2D g2, AxisState state,
Rectangle2D dataArea,
RectangleEdge edge) {
List<ValueTick> ticks = new ArrayList<ValueTick>();
double x0;
double y0 = state.getCursor();
double insideLength = getTickMarkInsideLength();
double outsideLength = getTickMarkOutsideLength();
RegularTimePeriod t = createInstance(this.majorTickTimePeriodClass,
this.first.getStart(), getTimeZone(), this.locale);
long t0 = t.getFirstMillisecond();
Line2D inside = null;
Line2D outside = null;
long firstOnAxis = getFirst().getFirstMillisecond();
long lastOnAxis = getLast().getLastMillisecond() + 1;
while (t0 <= lastOnAxis) {
ticks.add(new NumberTick((double) t0, "", TextAnchor.CENTER,
TextAnchor.CENTER, 0.0));
x0 = valueToJava2D(t0, dataArea, edge);
if (edge == RectangleEdge.TOP) {
inside = new Line2D.Double(x0, y0, x0, y0 + insideLength);
outside = new Line2D.Double(x0, y0, x0, y0 - outsideLength);
}
else if (edge == RectangleEdge.BOTTOM) {
inside = new Line2D.Double(x0, y0, x0, y0 - insideLength);
outside = new Line2D.Double(x0, y0, x0, y0 + outsideLength);
}
if (t0 >= firstOnAxis) {
g2.setPaint(getTickMarkPaint());
g2.setStroke(getTickMarkStroke());
g2.draw(inside);
g2.draw(outside);
}
// draw minor tick marks
if (this.minorTickMarksVisible) {
RegularTimePeriod tminor = createInstance(
this.minorTickTimePeriodClass, new Date(t0),
getTimeZone(), this.locale);
long tt0 = tminor.getFirstMillisecond();
while (tt0 < t.getLastMillisecond()
&& tt0 < lastOnAxis) {
double xx0 = valueToJava2D(tt0, dataArea, edge);
if (edge == RectangleEdge.TOP) {
inside = new Line2D.Double(xx0, y0, xx0,
y0 + this.minorTickMarkInsideLength);
outside = new Line2D.Double(xx0, y0, xx0,
y0 - this.minorTickMarkOutsideLength);
}
else if (edge == RectangleEdge.BOTTOM) {
inside = new Line2D.Double(xx0, y0, xx0,
y0 - this.minorTickMarkInsideLength);
outside = new Line2D.Double(xx0, y0, xx0,
y0 + this.minorTickMarkOutsideLength);
}
if (tt0 >= firstOnAxis) {
g2.setPaint(this.minorTickMarkPaint);
g2.setStroke(this.minorTickMarkStroke);
g2.draw(inside);
g2.draw(outside);
}
tminor = tminor.next();
tminor.peg(this.calendar);
tt0 = tminor.getFirstMillisecond();
}
}
t = t.next();
t.peg(this.calendar);
t0 = t.getFirstMillisecond();
}
if (edge == RectangleEdge.TOP) {
state.cursorUp(Math.max(outsideLength,
this.minorTickMarkOutsideLength));
}
else if (edge == RectangleEdge.BOTTOM) {
state.cursorDown(Math.max(outsideLength,
this.minorTickMarkOutsideLength));
}
state.setTicks(ticks);
}
/**
* Draws the tick marks for a vertical axis.
*
* @param g2 the graphics device.
* @param state the axis state.
* @param dataArea the data area.
* @param edge the edge.
*/
protected void drawTickMarksVertical(Graphics2D g2, AxisState state,
Rectangle2D dataArea,
RectangleEdge edge) {
// FIXME: implement this...
}
/**
* Draws the tick labels for one "band" of time periods.
*
* @param band the band index (zero-based).
* @param g2 the graphics device.
* @param state the axis state.
* @param dataArea the data area.
* @param edge the edge where the axis is located.
*
* @return The updated axis state.
*/
protected AxisState drawTickLabels(int band, Graphics2D g2, AxisState state,
Rectangle2D dataArea, RectangleEdge edge) {
// work out the initial gap
double delta1 = 0.0;
FontMetrics fm = g2.getFontMetrics(this.labelInfo[band].getLabelFont());
if (edge == RectangleEdge.BOTTOM) {
delta1 = this.labelInfo[band].getPadding().calculateTopOutset(
fm.getHeight());
}
else if (edge == RectangleEdge.TOP) {
delta1 = this.labelInfo[band].getPadding().calculateBottomOutset(
fm.getHeight());
}
state.moveCursor(delta1, edge);
long axisMin = this.first.getFirstMillisecond();
long axisMax = this.last.getLastMillisecond();
g2.setFont(this.labelInfo[band].getLabelFont());
g2.setPaint(this.labelInfo[band].getLabelPaint());
// work out the number of periods to skip for labelling
RegularTimePeriod p1 = this.labelInfo[band].createInstance(
new Date(axisMin), this.timeZone, this.locale);
RegularTimePeriod p2 = this.labelInfo[band].createInstance(
new Date(axisMax), this.timeZone, this.locale);
DateFormat df = this.labelInfo[band].getDateFormat();
df.setTimeZone(this.timeZone);
String label1 = df.format(new Date(p1.getMiddleMillisecond()));
String label2 = df.format(new Date(p2.getMiddleMillisecond()));
Rectangle2D b1 = TextUtilities.getTextBounds(label1, g2,
g2.getFontMetrics());
Rectangle2D b2 = TextUtilities.getTextBounds(label2, g2,
g2.getFontMetrics());
double w = Math.max(b1.getWidth(), b2.getWidth());
long ww = Math.round(java2DToValue(dataArea.getX() + w + 5.0,
dataArea, edge));
if (isInverted()) {
ww = axisMax - ww;
}
else {
ww = ww - axisMin;
}
long length = p1.getLastMillisecond()
- p1.getFirstMillisecond();
int periods = (int) (ww / length) + 1;
RegularTimePeriod p = this.labelInfo[band].createInstance(
new Date(axisMin), this.timeZone, this.locale);
Rectangle2D b = null;
long lastXX = 0L;
float y = (float) (state.getCursor());
TextAnchor anchor = TextAnchor.TOP_CENTER;
float yDelta = (float) b1.getHeight();
if (edge == RectangleEdge.TOP) {
anchor = TextAnchor.BOTTOM_CENTER;
yDelta = -yDelta;
}
while (p.getFirstMillisecond() <= axisMax) {
float x = (float) valueToJava2D(p.getMiddleMillisecond(), dataArea,
edge);
String label = df.format(new Date(p.getMiddleMillisecond()));
long first = p.getFirstMillisecond();
long last = p.getLastMillisecond();
if (last > axisMax) {
// this is the last period, but it is only partially visible
// so check that the label will fit before displaying it...
Rectangle2D bb = TextUtilities.getTextBounds(label, g2,
g2.getFontMetrics());
if ((x + bb.getWidth() / 2) > dataArea.getMaxX()) {
float xstart = (float) valueToJava2D(Math.max(first,
axisMin), dataArea, edge);
if (bb.getWidth() < (dataArea.getMaxX() - xstart)) {
x = ((float) dataArea.getMaxX() + xstart) / 2.0f;
}
else {
label = null;
}
}
}
if (first < axisMin) {
// this is the first period, but it is only partially visible
// so check that the label will fit before displaying it...
Rectangle2D bb = TextUtilities.getTextBounds(label, g2,
g2.getFontMetrics());
if ((x - bb.getWidth() / 2) < dataArea.getX()) {
float xlast = (float) valueToJava2D(Math.min(last,
axisMax), dataArea, edge);
if (bb.getWidth() < (xlast - dataArea.getX())) {
x = (xlast + (float) dataArea.getX()) / 2.0f;
}
else {
label = null;
}
}
}
if (label != null) {
g2.setPaint(this.labelInfo[band].getLabelPaint());
b = TextUtilities.drawAlignedString(label, g2, x, y, anchor);
}
if (lastXX > 0L) {
if (this.labelInfo[band].getDrawDividers()) {
long nextXX = p.getFirstMillisecond();
long mid = (lastXX + nextXX) / 2;
float mid2d = (float) valueToJava2D(mid, dataArea, edge);
g2.setStroke(this.labelInfo[band].getDividerStroke());
g2.setPaint(this.labelInfo[band].getDividerPaint());
g2.draw(new Line2D.Float(mid2d, y, mid2d, y + yDelta));
}
}
lastXX = last;
for (int i = 0; i < periods; i++) {
p = p.next();
}
p.peg(this.calendar);
}
double used = 0.0;
if (b != null) {
used = b.getHeight();
// work out the trailing gap
if (edge == RectangleEdge.BOTTOM) {
used += this.labelInfo[band].getPadding().calculateBottomOutset(
fm.getHeight());
}
else if (edge == RectangleEdge.TOP) {
used += this.labelInfo[band].getPadding().calculateTopOutset(
fm.getHeight());
}
}
state.moveCursor(used, edge);
return state;
}
/**
* Calculates the positions of the ticks for the axis, storing the results
* in the tick list (ready for drawing).
*
* @param g2 the graphics device.
* @param state the axis state.
* @param dataArea the area inside the axes.
* @param edge the edge on which the axis is located.
*
* @return The list of ticks.
*/
@Override
public List<ValueTick> refreshTicks(Graphics2D g2, AxisState state,
Rectangle2D dataArea, RectangleEdge edge) {
return Collections.EMPTY_LIST;
}
/**
* Converts a data value to a coordinate in Java2D space, assuming that the
* axis runs along one edge of the specified dataArea.
* <p>
* Note that it is possible for the coordinate to fall outside the area.
*
* @param value the data value.
* @param area the area for plotting the data.
* @param edge the edge along which the axis lies.
*
* @return The Java2D coordinate.
*/
@Override
public double valueToJava2D(double value, Rectangle2D area,
RectangleEdge edge) {
double result = Double.NaN;
double axisMin = this.first.getFirstMillisecond();
double axisMax = this.last.getLastMillisecond();
if (RectangleEdge.isTopOrBottom(edge)) {
double minX = area.getX();
double maxX = area.getMaxX();
if (isInverted()) {
result = maxX + ((value - axisMin) / (axisMax - axisMin))
* (minX - maxX);
}
else {
result = minX + ((value - axisMin) / (axisMax - axisMin))
* (maxX - minX);
}
}
else if (RectangleEdge.isLeftOrRight(edge)) {
double minY = area.getMinY();
double maxY = area.getMaxY();
if (isInverted()) {
result = minY + (((value - axisMin) / (axisMax - axisMin))
* (maxY - minY));
}
else {
result = maxY - (((value - axisMin) / (axisMax - axisMin))
* (maxY - minY));
}
}
return result;
}
/**
* Converts a coordinate in Java2D space to the corresponding data value,
* assuming that the axis runs along one edge of the specified dataArea.
*
* @param java2DValue the coordinate in Java2D space.
* @param area the area in which the data is plotted.
* @param edge the edge along which the axis lies.
*
* @return The data value.
*/
@Override
public double java2DToValue(double java2DValue, Rectangle2D area,
RectangleEdge edge) {
double result;
double min = 0.0;
double max = 0.0;
double axisMin = this.first.getFirstMillisecond();
double axisMax = this.last.getLastMillisecond();
if (RectangleEdge.isTopOrBottom(edge)) {
min = area.getX();
max = area.getMaxX();
}
else if (RectangleEdge.isLeftOrRight(edge)) {
min = area.getMaxY();
max = area.getY();
}
if (isInverted()) {
result = axisMax - ((java2DValue - min) / (max - min)
* (axisMax - axisMin));
}
else {
result = axisMin + ((java2DValue - min) / (max - min)
* (axisMax - axisMin));
}
return result;
}
/**
* Rescales the axis to ensure that all data is visible.
*/
@Override
protected void autoAdjustRange() {
Plot plot = getPlot();
if (plot == null) {
return; // no plot, no data
}
if (plot instanceof ValueAxisPlot) {
ValueAxisPlot vap = (ValueAxisPlot) plot;
Range r = vap.getDataRange(this);
if (r == null) {
r = getDefaultAutoRange();
}
long upper = Math.round(r.getUpperBound());
long lower = Math.round(r.getLowerBound());
this.first = createInstance(this.autoRangeTimePeriodClass,
new Date(lower), this.timeZone, this.locale);
this.last = createInstance(this.autoRangeTimePeriodClass,
new Date(upper), this.timeZone, this.locale);
setRange(r, false, false);
}
}
/**
* Tests the axis 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 PeriodAxis)) {
return false;
}
PeriodAxis that = (PeriodAxis) obj;
if (!this.first.equals(that.first)) {
return false;
}
if (!this.last.equals(that.last)) {
return false;
}
if (!this.timeZone.equals(that.timeZone)) {
return false;
}
if (!this.locale.equals(that.locale)) {
return false;
}
if (!this.autoRangeTimePeriodClass.equals(
that.autoRangeTimePeriodClass)) {
return false;
}
if (!(isMinorTickMarksVisible() == that.isMinorTickMarksVisible())) {
return false;
}
if (!this.majorTickTimePeriodClass.equals(
that.majorTickTimePeriodClass)) {
return false;
}
if (!this.minorTickTimePeriodClass.equals(
that.minorTickTimePeriodClass)) {
return false;
}
if (!this.minorTickMarkPaint.equals(that.minorTickMarkPaint)) {
return false;
}
if (!this.minorTickMarkStroke.equals(that.minorTickMarkStroke)) {
return false;
}
if (!Arrays.equals(this.labelInfo, that.labelInfo)) {
return false;
}
return super.equals(obj);
}
@Override
public int hashCode() {
return super.hashCode();
}
/**
* Returns a clone of the axis.
*
* @return A clone.
*
* @throws CloneNotSupportedException this class is cloneable, but
* subclasses may not be.
*/
@Override
public Object clone() throws CloneNotSupportedException {
PeriodAxis clone = (PeriodAxis) super.clone();
clone.timeZone = (TimeZone) this.timeZone.clone();
clone.labelInfo = (PeriodAxisLabelInfo[]) this.labelInfo.clone();
return clone;
}
/**
* A utility method used to create a particular subclass of the
* {@link RegularTimePeriod} class that includes the specified millisecond,
* assuming the specified time zone.
*
* @param periodClass the class.
* @param millisecond the time.
* @param zone the time zone.
* @param locale the locale.
*
* @return The time period.
*/
private RegularTimePeriod createInstance(Class periodClass,
Date millisecond, TimeZone zone, Locale locale) {
RegularTimePeriod result = null;
try {
Constructor c = periodClass.getDeclaredConstructor(new Class[] {
Date.class, TimeZone.class, Locale.class});
result = (RegularTimePeriod) c.newInstance(new Object[] {
millisecond, zone, locale});
}
catch (Exception e) {
try {
Constructor c = periodClass.getDeclaredConstructor(new Class[] {
Date.class});
result = (RegularTimePeriod) c.newInstance(new Object[] {
millisecond});
}
catch (Exception e2) {
// do nothing
}
}
return result;
}
/**
* Provides serialization support.
*
* @param stream the output stream.
*
* @throws IOException if there is an I/O error.
*/
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
SerialUtilities.writeStroke(this.minorTickMarkStroke, stream);
SerialUtilities.writePaint(this.minorTickMarkPaint, 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.minorTickMarkStroke = SerialUtilities.readStroke(stream);
this.minorTickMarkPaint = SerialUtilities.readPaint(stream);
}
}
| 42,693 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
CategoryAxis3D.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/axis/CategoryAxis3D.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.]
*
* -------------------
* CategoryAxis3D.java
* -------------------
* (C) Copyright 2003-2012, by Klaus Rheinwald and Contributors.
*
* Original Author: Klaus Rheinwald;
* Contributor(s): Tin Luu,
* David Gilbert (for Object Refinery Limited);
* Adriaan Joubert;
*
* Changes
* -------
* 19-Feb-2003 : File creation;
* 21-Mar-2003 : Added to JFreeChart CVS, see bug id 685501 for code
* contribution from KR (DG);
* 26-Mar-2003 : Implemented Serializable (DG);
* 13-May-2003 : Renamed HorizontalCategoryAxis3D --> CategoryAxis3D, and
* modified to take into account the plot orientation (DG);
* 14-Aug-2003 : Implemented Cloneable (DG);
* 21-Aug-2003 : Fixed draw() method bugs (DG);
* 22-Mar-2004 : Added workaround for bug 920959 (null pointer exception with
* no renderer) (DG);
* ------------- JFREECHART 1.0.x ---------------------------------------------
* 18-Aug-2006 : Fix for bug drawing category labels, thanks to Adriaan
* Joubert (1277726) (DG);
* 16-Apr-2009 : Draw axis line and tick marks (DG);
* 16-Jun-2012 : Removed JCommon dependencies (DG);
*
*/
package org.jfree.chart.axis;
import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;
import java.io.Serializable;
import org.jfree.chart.Effect3D;
import org.jfree.chart.ui.RectangleEdge;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotRenderingInfo;
import org.jfree.chart.renderer.category.CategoryItemRenderer;
/**
* An axis that displays categories and has a 3D effect.
* Used for bar charts and line charts.
*/
public class CategoryAxis3D extends CategoryAxis
implements Cloneable, Serializable {
/** For serialization. */
private static final long serialVersionUID = 4114732251353700972L;
/**
* Creates a new axis.
*/
public CategoryAxis3D() {
this(null);
}
/**
* Creates a new axis using default attribute values.
*
* @param label the axis label (<code>null</code> permitted).
*/
public CategoryAxis3D(String label) {
super(label);
}
/**
* Draws the axis on a Java 2D graphics device (such as the screen or a
* printer).
*
* @param g2 the graphics device (<code>null</code> not permitted).
* @param cursor the cursor location.
* @param plotArea the area within which the axis should be drawn
* (<code>null</code> not permitted).
* @param dataArea the area within which the plot is being drawn
* (<code>null</code> not permitted).
* @param edge the location of the axis (<code>null</code> not permitted).
* @param plotState collects information about the plot (<code>null</code>
* permitted).
*
* @return The axis state (never <code>null</code>).
*/
@Override
public AxisState draw(Graphics2D g2,
double cursor,
Rectangle2D plotArea,
Rectangle2D dataArea,
RectangleEdge edge,
PlotRenderingInfo plotState) {
// if the axis is not visible, don't draw it...
if (!isVisible()) {
return new AxisState(cursor);
}
// calculate the adjusted data area taking into account the 3D effect...
// this assumes that there is a 3D renderer, all this 3D effect is a
// bit of an ugly hack...
CategoryPlot plot = (CategoryPlot) getPlot();
Rectangle2D adjustedDataArea = new Rectangle2D.Double();
if (plot.getRenderer() instanceof Effect3D) {
Effect3D e3D = (Effect3D) plot.getRenderer();
double adjustedX = dataArea.getMinX();
double adjustedY = dataArea.getMinY();
double adjustedW = dataArea.getWidth() - e3D.getXOffset();
double adjustedH = dataArea.getHeight() - e3D.getYOffset();
if (edge == RectangleEdge.LEFT || edge == RectangleEdge.BOTTOM) {
adjustedY += e3D.getYOffset();
}
else if (edge == RectangleEdge.RIGHT || edge == RectangleEdge.TOP) {
adjustedX += e3D.getXOffset();
}
adjustedDataArea.setRect(adjustedX, adjustedY, adjustedW,
adjustedH);
}
else {
adjustedDataArea.setRect(dataArea);
}
if (isAxisLineVisible()) {
drawAxisLine(g2, cursor, adjustedDataArea, edge);
}
// draw the category labels and axis label
AxisState state = new AxisState(cursor);
if (isTickMarksVisible()) {
drawTickMarks(g2, cursor, adjustedDataArea, edge, state);
}
state = drawCategoryLabels(g2, plotArea, adjustedDataArea, edge,
state, plotState);
state = drawLabel(getLabel(), g2, plotArea, dataArea, edge, state);
return state;
}
/**
* Returns the Java 2D coordinate for a category.
*
* @param anchor the anchor point.
* @param category the category index.
* @param categoryCount the category count.
* @param area the data area.
* @param edge the location of the axis.
*
* @return The coordinate.
*/
@Override
public double getCategoryJava2DCoordinate(CategoryAnchor anchor,
int category,
int categoryCount,
Rectangle2D area,
RectangleEdge edge) {
double result = 0.0;
Rectangle2D adjustedArea = area;
CategoryPlot plot = (CategoryPlot) getPlot();
CategoryItemRenderer renderer = plot.getRenderer();
if (renderer instanceof Effect3D) {
Effect3D e3D = (Effect3D) renderer;
double adjustedX = area.getMinX();
double adjustedY = area.getMinY();
double adjustedW = area.getWidth() - e3D.getXOffset();
double adjustedH = area.getHeight() - e3D.getYOffset();
if (edge == RectangleEdge.LEFT || edge == RectangleEdge.BOTTOM) {
adjustedY += e3D.getYOffset();
}
else if (edge == RectangleEdge.RIGHT || edge == RectangleEdge.TOP) {
adjustedX += e3D.getXOffset();
}
adjustedArea = new Rectangle2D.Double(adjustedX, adjustedY,
adjustedW, adjustedH);
}
if (anchor == CategoryAnchor.START) {
result = getCategoryStart(category, categoryCount, adjustedArea,
edge);
}
else if (anchor == CategoryAnchor.MIDDLE) {
result = getCategoryMiddle(category, categoryCount, adjustedArea,
edge);
}
else if (anchor == CategoryAnchor.END) {
result = getCategoryEnd(category, categoryCount, adjustedArea,
edge);
}
return result;
}
/**
* Returns a clone of the axis.
*
* @return A clone.
*
* @throws CloneNotSupportedException If the axis is not cloneable for
* some reason.
*/
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
| 8,652 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
SubCategoryAxis.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/axis/SubCategoryAxis.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.]
*
* --------------------
* SubCategoryAxis.java
* --------------------
* (C) Copyright 2004-2012, by Object Refinery Limited.
*
* Original Author: David Gilbert;
* Contributor(s): Adriaan Joubert;
*
* Changes
* -------
* 12-May-2004 : Version 1 (DG);
* 30-Sep-2004 : Moved drawRotatedString() from RefineryUtilities
* --> TextUtilities (DG);
* 26-Apr-2005 : Removed logger (DG);
* ------------- JFREECHART 1.0.x ---------------------------------------------
* 18-Aug-2006 : Fix for bug drawing category labels, thanks to Adriaan
* Joubert (1277726) (DG);
* 30-May-2007 : Added argument check and event notification to
* addSubCategory() (DG);
* 13-Nov-2008 : Fix NullPointerException when dataset is null - see bug
* report 2275695 (DG);
* 17-Jun-2012 : Removed JCommon dependencies (DG);
*
*/
package org.jfree.chart.axis;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.geom.Rectangle2D;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.List;
import org.jfree.chart.ui.RectangleEdge;
import org.jfree.chart.ui.TextAnchor;
import org.jfree.chart.event.AxisChangeEvent;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.Plot;
import org.jfree.chart.plot.PlotRenderingInfo;
import org.jfree.chart.text.TextUtilities;
import org.jfree.chart.util.SerialUtilities;
import org.jfree.data.category.CategoryDataset;
/**
* A specialised category axis that can display sub-categories.
*/
public class SubCategoryAxis extends CategoryAxis
implements Cloneable, Serializable {
/** For serialization. */
private static final long serialVersionUID = -1279463299793228344L;
/** Storage for the sub-categories (these need to be set manually). */
private List<Comparable> subCategories;
/** The font for the sub-category labels. */
private Font subLabelFont = new Font("SansSerif", Font.PLAIN, 10);
/** The paint for the sub-category labels. */
private transient Paint subLabelPaint = Color.BLACK;
/**
* Creates a new axis.
*
* @param label the axis label.
*/
public SubCategoryAxis(String label) {
super(label);
this.subCategories = new java.util.ArrayList<Comparable>();
}
/**
* Adds a sub-category to the axis and sends an {@link AxisChangeEvent} to
* all registered listeners.
*
* @param subCategory the sub-category (<code>null</code> not permitted).
*/
public void addSubCategory(Comparable subCategory) {
if (subCategory == null) {
throw new IllegalArgumentException("Null 'subcategory' axis.");
}
this.subCategories.add(subCategory);
notifyListeners(new AxisChangeEvent(this));
}
/**
* Returns the font used to display the sub-category labels.
*
* @return The font (never <code>null</code>).
*
* @see #setSubLabelFont(Font)
*/
public Font getSubLabelFont() {
return this.subLabelFont;
}
/**
* Sets the font used to display the sub-category labels and sends an
* {@link AxisChangeEvent} to all registered listeners.
*
* @param font the font (<code>null</code> not permitted).
*
* @see #getSubLabelFont()
*/
public void setSubLabelFont(Font font) {
if (font == null) {
throw new IllegalArgumentException("Null 'font' argument.");
}
this.subLabelFont = font;
notifyListeners(new AxisChangeEvent(this));
}
/**
* Returns the paint used to display the sub-category labels.
*
* @return The paint (never <code>null</code>).
*
* @see #setSubLabelPaint(Paint)
*/
public Paint getSubLabelPaint() {
return this.subLabelPaint;
}
/**
* Sets the paint used to display the sub-category labels and sends an
* {@link AxisChangeEvent} to all registered listeners.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getSubLabelPaint()
*/
public void setSubLabelPaint(Paint paint) {
if (paint == null) {
throw new IllegalArgumentException("Null 'paint' argument.");
}
this.subLabelPaint = paint;
notifyListeners(new AxisChangeEvent(this));
}
/**
* Estimates the space required for the axis, given a specific drawing area.
*
* @param g2 the graphics device (used to obtain font information).
* @param plot the plot that the axis belongs to.
* @param plotArea the area within which the axis should be drawn.
* @param edge the axis location (top or bottom).
* @param space the space already reserved.
*
* @return The space required to draw the axis.
*/
@Override
public AxisSpace reserveSpace(Graphics2D g2, Plot plot,
Rectangle2D plotArea,
RectangleEdge edge, AxisSpace space) {
// create a new space object if one wasn't supplied...
if (space == null) {
space = new AxisSpace();
}
// if the axis is not visible, no additional space is required...
if (!isVisible()) {
return space;
}
space = super.reserveSpace(g2, plot, plotArea, edge, space);
double maxdim = getMaxDim(g2, edge);
if (RectangleEdge.isTopOrBottom(edge)) {
space.add(maxdim, edge);
}
else if (RectangleEdge.isLeftOrRight(edge)) {
space.add(maxdim, edge);
}
return space;
}
/**
* Returns the maximum of the relevant dimension (height or width) of the
* subcategory labels.
*
* @param g2 the graphics device.
* @param edge the edge.
*
* @return The maximum dimension.
*/
private double getMaxDim(Graphics2D g2, RectangleEdge edge) {
double result = 0.0;
g2.setFont(this.subLabelFont);
FontMetrics fm = g2.getFontMetrics();
for (Comparable subcategory : this.subCategories) {
String label = subcategory.toString();
Rectangle2D bounds = TextUtilities.getTextBounds(label, g2, fm);
double dim = 0.0;
if (RectangleEdge.isLeftOrRight(edge)) {
dim = bounds.getWidth();
} else { // must be top or bottom
dim = bounds.getHeight();
}
result = Math.max(result, dim);
}
return result;
}
/**
* Draws the axis on a Java 2D graphics device (such as the screen or a
* printer).
*
* @param g2 the graphics device (<code>null</code> not permitted).
* @param cursor the cursor location.
* @param plotArea the area within which the axis should be drawn
* (<code>null</code> not permitted).
* @param dataArea the area within which the plot is being drawn
* (<code>null</code> not permitted).
* @param edge the location of the axis (<code>null</code> not permitted).
* @param plotState collects information about the plot
* (<code>null</code> permitted).
*
* @return The axis state (never <code>null</code>).
*/
@Override
public AxisState draw(Graphics2D g2,
double cursor,
Rectangle2D plotArea,
Rectangle2D dataArea,
RectangleEdge edge,
PlotRenderingInfo plotState) {
// if the axis is not visible, don't draw it...
if (!isVisible()) {
return new AxisState(cursor);
}
if (isAxisLineVisible()) {
drawAxisLine(g2, cursor, dataArea, edge);
}
// draw the category labels and axis label
AxisState state = new AxisState(cursor);
state = drawSubCategoryLabels(g2, plotArea, dataArea, edge, state,
plotState);
state = drawCategoryLabels(g2, plotArea, dataArea, edge, state,
plotState);
state = drawLabel(getLabel(), g2, plotArea, dataArea, edge, state);
return state;
}
/**
* Draws the category labels and returns the updated axis state.
*
* @param g2 the graphics device (<code>null</code> not permitted).
* @param plotArea the plot area (<code>null</code> not permitted).
* @param dataArea the area inside the axes (<code>null</code> not
* permitted).
* @param edge the axis location (<code>null</code> not permitted).
* @param state the axis state (<code>null</code> not permitted).
* @param plotState collects information about the plot (<code>null</code>
* permitted).
*
* @return The updated axis state (never <code>null</code>).
*/
protected AxisState drawSubCategoryLabels(Graphics2D g2,
Rectangle2D plotArea,
Rectangle2D dataArea,
RectangleEdge edge,
AxisState state,
PlotRenderingInfo plotState) {
if (state == null) {
throw new IllegalArgumentException("Null 'state' argument.");
}
g2.setFont(this.subLabelFont);
g2.setPaint(this.subLabelPaint);
CategoryPlot plot = (CategoryPlot) getPlot();
int categoryCount = 0;
CategoryDataset dataset = plot.getDataset();
if (dataset != null) {
categoryCount = dataset.getColumnCount();
}
double maxdim = getMaxDim(g2, edge);
for (int categoryIndex = 0; categoryIndex < categoryCount;
categoryIndex++) {
double x0 = 0.0;
double x1 = 0.0;
double y0 = 0.0;
double y1 = 0.0;
if (edge == RectangleEdge.TOP) {
x0 = getCategoryStart(categoryIndex, categoryCount, dataArea,
edge);
x1 = getCategoryEnd(categoryIndex, categoryCount, dataArea,
edge);
y1 = state.getCursor();
y0 = y1 - maxdim;
}
else if (edge == RectangleEdge.BOTTOM) {
x0 = getCategoryStart(categoryIndex, categoryCount, dataArea,
edge);
x1 = getCategoryEnd(categoryIndex, categoryCount, dataArea,
edge);
y0 = state.getCursor();
y1 = y0 + maxdim;
}
else if (edge == RectangleEdge.LEFT) {
y0 = getCategoryStart(categoryIndex, categoryCount, dataArea,
edge);
y1 = getCategoryEnd(categoryIndex, categoryCount, dataArea,
edge);
x1 = state.getCursor();
x0 = x1 - maxdim;
}
else if (edge == RectangleEdge.RIGHT) {
y0 = getCategoryStart(categoryIndex, categoryCount, dataArea,
edge);
y1 = getCategoryEnd(categoryIndex, categoryCount, dataArea,
edge);
x0 = state.getCursor();
x1 = x0 + maxdim;
}
Rectangle2D area = new Rectangle2D.Double(x0, y0, (x1 - x0),
(y1 - y0));
int subCategoryCount = this.subCategories.size();
float width = (float) ((x1 - x0) / subCategoryCount);
float height = (float) ((y1 - y0) / subCategoryCount);
float xx = 0.0f;
float yy = 0.0f;
for (int i = 0; i < subCategoryCount; i++) {
if (RectangleEdge.isTopOrBottom(edge)) {
xx = (float) (x0 + (i + 0.5) * width);
yy = (float) area.getCenterY();
}
else {
xx = (float) area.getCenterX();
yy = (float) (y0 + (i + 0.5) * height);
}
String label = this.subCategories.get(i).toString();
TextUtilities.drawRotatedString(label, g2, xx, yy,
TextAnchor.CENTER, 0.0, TextAnchor.CENTER);
}
}
if (edge.equals(RectangleEdge.TOP)) {
double h = maxdim;
state.cursorUp(h);
}
else if (edge.equals(RectangleEdge.BOTTOM)) {
double h = maxdim;
state.cursorDown(h);
}
else if (edge == RectangleEdge.LEFT) {
double w = maxdim;
state.cursorLeft(w);
}
else if (edge == RectangleEdge.RIGHT) {
double w = maxdim;
state.cursorRight(w);
}
return state;
}
/**
* Tests the axis 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 SubCategoryAxis && super.equals(obj)) {
SubCategoryAxis axis = (SubCategoryAxis) obj;
if (!this.subCategories.equals(axis.subCategories)) {
return false;
}
if (!this.subLabelFont.equals(axis.subLabelFont)) {
return false;
}
if (!this.subLabelPaint.equals(axis.subLabelPaint)) {
return false;
}
return true;
}
return false;
}
/**
* 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.subLabelPaint, 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.subLabelPaint = SerialUtilities.readPaint(stream);
}
}
| 15,925 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
NumberAxis.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/axis/NumberAxis.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.]
*
* ---------------
* NumberAxis.java
* ---------------
* (C) Copyright 2000-2012, by Object Refinery Limited and Contributors.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): Laurence Vanhelsuwe;
* Peter Kolb (patches 1934255 and 2603321);
*
* Changes
* -------
* 18-Sep-2001 : Added standard header and fixed DOS encoding problem (DG);
* 22-Sep-2001 : Changed setMinimumAxisValue() and setMaximumAxisValue() so
* that they clear the autoRange flag (DG);
* 27-Nov-2001 : Removed old, redundant code (DG);
* 30-Nov-2001 : Added accessor methods for the standard tick units (DG);
* 08-Jan-2002 : Added setAxisRange() method (since renamed setRange()) (DG);
* 16-Jan-2002 : Added setTickUnit() method. Extended ValueAxis to support an
* optional cross-hair (DG);
* 08-Feb-2002 : Fixes bug to ensure the autorange is recalculated if the
* setAutoRangeIncludesZero flag is changed (DG);
* 25-Feb-2002 : Added a new flag autoRangeStickyZero to provide further
* control over margins in the auto-range mechanism. Updated
* constructors. Updated import statements. Moved the
* createStandardTickUnits() method to the TickUnits class (DG);
* 19-Apr-2002 : Updated Javadoc comments (DG);
* 01-May-2002 : Updated for changes to TickUnit class, removed valueToString()
* method (DG);
* 25-Jul-2002 : Moved the lower and upper margin attributes, and the
* auto-range minimum size, up one level to the ValueAxis
* class (DG);
* 05-Sep-2002 : Updated constructor to match changes in Axis class (DG);
* 01-Oct-2002 : Fixed errors reported by Checkstyle (DG);
* 04-Oct-2002 : Moved standardTickUnits from NumberAxis --> ValueAxis (DG);
* 24-Oct-2002 : Added a number format override (DG);
* 08-Nov-2002 : Moved to new package com.jrefinery.chart.axis (DG);
* 19-Nov-2002 : Removed grid settings (now controlled by the plot) (DG);
* 14-Jan-2003 : Changed autoRangeMinimumSize from Number --> double, and moved
* crosshair settings to the plot classes (DG);
* 20-Jan-2003 : Removed the monolithic constructor (DG);
* 26-Mar-2003 : Implemented Serializable (DG);
* 16-Jul-2003 : Reworked to allow for multiple secondary axes (DG);
* 13-Aug-2003 : Implemented Cloneable (DG);
* 07-Oct-2003 : Fixed bug (815028) in the auto range calculation (DG);
* 29-Oct-2003 : Added workaround for font alignment in PDF output (DG);
* 07-Nov-2003 : Modified to use NumberTick class (DG);
* 21-Jan-2004 : Renamed translateJava2DToValue --> java2DToValue, and
* translateValueToJava2D --> valueToJava2D (DG);
* 03-Mar-2004 : Added plotState to draw() method (DG);
* 07-Apr-2004 : Changed string width calculation (DG);
* 11-Jan-2005 : Removed deprecated methods in preparation for 1.0.0
* release (DG);
* 28-Mar-2005 : Renamed autoRangeIncludesZero() --> getAutoRangeIncludesZero()
* and autoRangeStickyZero() --> getAutoRangeStickyZero() (DG);
* 21-Apr-2005 : Removed redundant argument from selectAutoTickUnit() (DG);
* 22-Apr-2005 : Renamed refreshHorizontalTicks --> refreshTicksHorizontal
* (and likewise the vertical version) for consistency with
* other axis classes (DG);
* ------------- JFREECHART 1.0.x ---------------------------------------------
* 10-Feb-2006 : Added some API doc comments in respect of bug 821046 (DG);
* 20-Feb-2006 : Modified equals() method to check rangeType field (fixes bug
* 1435461) (DG);
* 04-Sep-2006 : Fix auto range calculation for the case where all data values
* are constant and large (see bug report 1549218) (DG);
* 11-Dec-2006 : Fix bug in auto-tick unit selection with tick format override,
* see bug 1608371 (DG);
* 22-Mar-2007 : Use new defaultAutoRange attribute (DG);
* 25-Sep-2008 : Added minor tick support, see patch 1934255 by Peter Kolb (DG);
* 21-Jan-2009 : Default minor tick counts will now come from the tick unit
* collection (DG);
* 19-Mar-2009 : Added entity support - see patch 2603321 by Peter Kolb (DG);
* 16-Jun-2012 : Removed JCommon dependencies (DG);
*
*/
package org.jfree.chart.axis;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.font.FontRenderContext;
import java.awt.font.LineMetrics;
import java.awt.geom.Rectangle2D;
import java.io.Serializable;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.List;
import java.util.Locale;
import org.jfree.chart.ui.RectangleEdge;
import org.jfree.chart.ui.RectangleInsets;
import org.jfree.chart.ui.TextAnchor;
import org.jfree.chart.util.ObjectUtilities;
import org.jfree.chart.event.AxisChangeEvent;
import org.jfree.chart.plot.Plot;
import org.jfree.chart.plot.PlotRenderingInfo;
import org.jfree.chart.plot.ValueAxisPlot;
import org.jfree.data.Range;
import org.jfree.data.RangeType;
/**
* An axis for displaying numerical data.
* <P>
* If the axis is set up to automatically determine its range to fit the data,
* you can ensure that the range includes zero (statisticians usually prefer
* this) by setting the <code>autoRangeIncludesZero</code> flag to
* <code>true</code>.
* <P>
* The <code>NumberAxis</code> class has a mechanism for automatically
* selecting a tick unit that is appropriate for the current axis range. This
* mechanism is an adaptation of code suggested by Laurence Vanhelsuwe.
*/
public class NumberAxis extends ValueAxis implements Cloneable, Serializable {
/** For serialization. */
private static final long serialVersionUID = 2805933088476185789L;
/** The default value for the autoRangeIncludesZero flag. */
public static final boolean DEFAULT_AUTO_RANGE_INCLUDES_ZERO = true;
/** The default value for the autoRangeStickyZero flag. */
public static final boolean DEFAULT_AUTO_RANGE_STICKY_ZERO = true;
/** The default tick unit. */
public static final NumberTickUnit DEFAULT_TICK_UNIT = new NumberTickUnit(
1.0, new DecimalFormat("0"));
/** The default setting for the vertical tick labels flag. */
public static final boolean DEFAULT_VERTICAL_TICK_LABELS = false;
/**
* The range type (can be used to force the axis to display only positive
* values or only negative values).
*/
private RangeType rangeType;
/**
* A flag that affects the axis range when the range is determined
* automatically. If the auto range does NOT include zero and this flag
* is TRUE, then the range is changed to include zero.
*/
private boolean autoRangeIncludesZero;
/**
* A flag that affects the size of the margins added to the axis range when
* the range is determined automatically. If the value 0 falls within the
* margin and this flag is TRUE, then the margin is truncated at zero.
*/
private boolean autoRangeStickyZero;
/** The tick unit for the axis. */
private NumberTickUnit tickUnit;
/** The override number format. */
private NumberFormat numberFormatOverride;
/** An optional band for marking regions on the axis. */
private MarkerAxisBand markerBand;
/**
* Default constructor.
*/
public NumberAxis() {
this(null);
}
/**
* Constructs a number axis, using default values where necessary.
*
* @param label the axis label (<code>null</code> permitted).
*/
public NumberAxis(String label) {
super(label, NumberAxis.createStandardTickUnits());
this.rangeType = RangeType.FULL;
this.autoRangeIncludesZero = DEFAULT_AUTO_RANGE_INCLUDES_ZERO;
this.autoRangeStickyZero = DEFAULT_AUTO_RANGE_STICKY_ZERO;
this.tickUnit = DEFAULT_TICK_UNIT;
this.numberFormatOverride = null;
this.markerBand = null;
}
/**
* Returns the axis range type.
*
* @return The axis range type (never <code>null</code>).
*
* @see #setRangeType(RangeType)
*/
public RangeType getRangeType() {
return this.rangeType;
}
/**
* Sets the axis range type.
*
* @param rangeType the range type (<code>null</code> not permitted).
*
* @see #getRangeType()
*/
public void setRangeType(RangeType rangeType) {
if (rangeType == null) {
throw new IllegalArgumentException("Null 'rangeType' argument.");
}
this.rangeType = rangeType;
notifyListeners(new AxisChangeEvent(this));
}
/**
* Returns the flag that indicates whether or not the automatic axis range
* (if indeed it is determined automatically) is forced to include zero.
*
* @return The flag.
*/
public boolean getAutoRangeIncludesZero() {
return this.autoRangeIncludesZero;
}
/**
* Sets the flag that indicates whether or not the axis range, if
* automatically calculated, is forced to include zero.
* <p>
* If the flag is changed to <code>true</code>, the axis range is
* recalculated.
* <p>
* Any change to the flag will trigger an {@link AxisChangeEvent}.
*
* @param flag the new value of the flag.
*
* @see #getAutoRangeIncludesZero()
*/
public void setAutoRangeIncludesZero(boolean flag) {
if (this.autoRangeIncludesZero != flag) {
this.autoRangeIncludesZero = flag;
if (isAutoRange()) {
autoAdjustRange();
}
notifyListeners(new AxisChangeEvent(this));
}
}
/**
* Returns a flag that affects the auto-range when zero falls outside the
* data range but inside the margins defined for the axis.
*
* @return The flag.
*
* @see #setAutoRangeStickyZero(boolean)
*/
public boolean getAutoRangeStickyZero() {
return this.autoRangeStickyZero;
}
/**
* Sets a flag that affects the auto-range when zero falls outside the data
* range but inside the margins defined for the axis.
*
* @param flag the new flag.
*
* @see #getAutoRangeStickyZero()
*/
public void setAutoRangeStickyZero(boolean flag) {
if (this.autoRangeStickyZero != flag) {
this.autoRangeStickyZero = flag;
if (isAutoRange()) {
autoAdjustRange();
}
notifyListeners(new AxisChangeEvent(this));
}
}
/**
* Returns the tick unit for the axis.
* <p>
* Note: if the <code>autoTickUnitSelection</code> flag is
* <code>true</code> the tick unit may be changed while the axis is being
* drawn, so in that case the return value from this method may be
* irrelevant if the method is called before the axis has been drawn.
*
* @return The tick unit for the axis.
*
* @see #setTickUnit(NumberTickUnit)
* @see ValueAxis#isAutoTickUnitSelection()
*/
public NumberTickUnit getTickUnit() {
return this.tickUnit;
}
/**
* Sets the tick unit for the axis and sends an {@link AxisChangeEvent} to
* all registered listeners. A side effect of calling this method is that
* the "auto-select" feature for tick units is switched off (you can
* restore it using the {@link ValueAxis#setAutoTickUnitSelection(boolean)}
* method).
*
* @param unit the new tick unit (<code>null</code> not permitted).
*
* @see #getTickUnit()
* @see #setTickUnit(NumberTickUnit, boolean, boolean)
*/
public void setTickUnit(NumberTickUnit unit) {
// defer argument checking...
setTickUnit(unit, true, true);
}
/**
* Sets the tick unit for the axis and, if requested, sends an
* {@link AxisChangeEvent} to all registered listeners. In addition, an
* option is provided to turn off the "auto-select" feature for tick units
* (you can restore it using the
* {@link ValueAxis#setAutoTickUnitSelection(boolean)} method).
*
* @param unit the new tick unit (<code>null</code> not permitted).
* @param notify notify listeners?
* @param turnOffAutoSelect turn off the auto-tick selection?
*/
public void setTickUnit(NumberTickUnit unit, boolean notify,
boolean turnOffAutoSelect) {
if (unit == null) {
throw new IllegalArgumentException("Null 'unit' argument.");
}
this.tickUnit = unit;
if (turnOffAutoSelect) {
setAutoTickUnitSelection(false, false);
}
if (notify) {
notifyListeners(new AxisChangeEvent(this));
}
}
/**
* Returns the number format override. If this is non-null, then it will
* be used to format the numbers on the axis.
*
* @return The number formatter (possibly <code>null</code>).
*
* @see #setNumberFormatOverride(NumberFormat)
*/
public NumberFormat getNumberFormatOverride() {
return this.numberFormatOverride;
}
/**
* Sets the number format override. If this is non-null, then it will be
* used to format the numbers on the axis.
*
* @param formatter the number formatter (<code>null</code> permitted).
*
* @see #getNumberFormatOverride()
*/
public void setNumberFormatOverride(NumberFormat formatter) {
this.numberFormatOverride = formatter;
notifyListeners(new AxisChangeEvent(this));
}
/**
* Returns the (optional) marker band for the axis.
*
* @return The marker band (possibly <code>null</code>).
*
* @see #setMarkerBand(MarkerAxisBand)
*/
public MarkerAxisBand getMarkerBand() {
return this.markerBand;
}
/**
* Sets the marker band for the axis.
* <P>
* The marker band is optional, leave it set to <code>null</code> if you
* don't require it.
*
* @param band the new band (<code>null</code> permitted).
*
* @see #getMarkerBand()
*/
public void setMarkerBand(MarkerAxisBand band) {
this.markerBand = band;
notifyListeners(new AxisChangeEvent(this));
}
/**
* Configures the axis to work with the specified plot. If the axis has
* auto-scaling, then sets the maximum and minimum values.
*/
@Override
public void configure() {
if (isAutoRange()) {
autoAdjustRange();
}
}
/**
* Rescales the axis to ensure that all data is visible.
*/
@Override
protected void autoAdjustRange() {
Plot plot = getPlot();
if (plot == null) {
return; // no plot, no data
}
if (plot instanceof ValueAxisPlot) {
ValueAxisPlot vap = (ValueAxisPlot) plot;
Range r = vap.getDataRange(this);
if (r == null) {
r = getDefaultAutoRange();
}
double upper = r.getUpperBound();
double lower = r.getLowerBound();
if (this.rangeType == RangeType.POSITIVE) {
lower = Math.max(0.0, lower);
upper = Math.max(0.0, upper);
}
else if (this.rangeType == RangeType.NEGATIVE) {
lower = Math.min(0.0, lower);
upper = Math.min(0.0, upper);
}
if (getAutoRangeIncludesZero()) {
lower = Math.min(lower, 0.0);
upper = Math.max(upper, 0.0);
}
double range = upper - lower;
// if fixed auto range, then derive lower bound...
double fixedAutoRange = getFixedAutoRange();
if (fixedAutoRange > 0.0) {
lower = upper - fixedAutoRange;
}
else {
// ensure the autorange is at least <minRange> in size...
double minRange = getAutoRangeMinimumSize();
if (range < minRange) {
double expand = (minRange - range) / 2;
upper = upper + expand;
lower = lower - expand;
if (lower == upper) { // see bug report 1549218
double adjust = Math.abs(lower) / 10.0;
lower = lower - adjust;
upper = upper + adjust;
}
if (this.rangeType == RangeType.POSITIVE) {
if (lower < 0.0) {
upper = upper - lower;
lower = 0.0;
}
}
else if (this.rangeType == RangeType.NEGATIVE) {
if (upper > 0.0) {
lower = lower - upper;
upper = 0.0;
}
}
}
if (getAutoRangeStickyZero()) {
if (upper <= 0.0) {
upper = Math.min(0.0, upper + getUpperMargin() * range);
}
else {
upper = upper + getUpperMargin() * range;
}
if (lower >= 0.0) {
lower = Math.max(0.0, lower - getLowerMargin() * range);
}
else {
lower = lower - getLowerMargin() * range;
}
}
else {
upper = upper + getUpperMargin() * range;
lower = lower - getLowerMargin() * range;
}
}
setRange(new Range(lower, upper), false, false);
}
}
/**
* Converts a data value to a coordinate in Java2D space, assuming that the
* axis runs along one edge of the specified dataArea.
* <p>
* Note that it is possible for the coordinate to fall outside the plotArea.
*
* @param value the data value.
* @param area the area for plotting the data.
* @param edge the axis location.
*
* @return The Java2D coordinate.
*
* @see #java2DToValue(double, Rectangle2D, RectangleEdge)
*/
@Override
public double valueToJava2D(double value, Rectangle2D area,
RectangleEdge edge) {
Range range = getRange();
double axisMin = range.getLowerBound();
double axisMax = range.getUpperBound();
double min = 0.0;
double max = 0.0;
if (RectangleEdge.isTopOrBottom(edge)) {
min = area.getX();
max = area.getMaxX();
}
else if (RectangleEdge.isLeftOrRight(edge)) {
max = area.getMinY();
min = area.getMaxY();
}
if (isInverted()) {
return max
- ((value - axisMin) / (axisMax - axisMin)) * (max - min);
}
else {
return min
+ ((value - axisMin) / (axisMax - axisMin)) * (max - min);
}
}
/**
* Converts a coordinate in Java2D space to the corresponding data value,
* assuming that the axis runs along one edge of the specified dataArea.
*
* @param java2DValue the coordinate in Java2D space.
* @param area the area in which the data is plotted.
* @param edge the location.
*
* @return The data value.
*
* @see #valueToJava2D(double, Rectangle2D, RectangleEdge)
*/
@Override
public double java2DToValue(double java2DValue, Rectangle2D area,
RectangleEdge edge) {
Range range = getRange();
double axisMin = range.getLowerBound();
double axisMax = range.getUpperBound();
double min = 0.0;
double max = 0.0;
if (RectangleEdge.isTopOrBottom(edge)) {
min = area.getX();
max = area.getMaxX();
}
else if (RectangleEdge.isLeftOrRight(edge)) {
min = area.getMaxY();
max = area.getY();
}
if (isInverted()) {
return axisMax
- (java2DValue - min) / (max - min) * (axisMax - axisMin);
}
else {
return axisMin
+ (java2DValue - min) / (max - min) * (axisMax - axisMin);
}
}
/**
* Calculates the value of the lowest visible tick on the axis.
*
* @return The value of the lowest visible tick on the axis.
*
* @see #calculateHighestVisibleTickValue()
*/
protected double calculateLowestVisibleTickValue() {
double unit = getTickUnit().getSize();
double index = Math.ceil(getRange().getLowerBound() / unit);
return index * unit;
}
/**
* Calculates the value of the highest visible tick on the axis.
*
* @return The value of the highest visible tick on the axis.
*
* @see #calculateLowestVisibleTickValue()
*/
protected double calculateHighestVisibleTickValue() {
double unit = getTickUnit().getSize();
double index = Math.floor(getRange().getUpperBound() / unit);
return index * unit;
}
/**
* Calculates the number of visible ticks.
*
* @return The number of visible ticks on the axis.
*/
protected int calculateVisibleTickCount() {
double unit = getTickUnit().getSize();
Range range = getRange();
return (int) (Math.floor(range.getUpperBound() / unit)
- Math.ceil(range.getLowerBound() / unit) + 1);
}
/**
* Draws the axis on a Java 2D graphics device (such as the screen or a
* printer).
*
* @param g2 the graphics device (<code>null</code> not permitted).
* @param cursor the cursor location.
* @param plotArea the area within which the axes and data should be drawn
* (<code>null</code> not permitted).
* @param dataArea the area within which the data should be drawn
* (<code>null</code> not permitted).
* @param edge the location of the axis (<code>null</code> not permitted).
* @param plotState collects information about the plot
* (<code>null</code> permitted).
*
* @return The axis state (never <code>null</code>).
*/
@Override
public AxisState draw(Graphics2D g2, double cursor, Rectangle2D plotArea,
Rectangle2D dataArea, RectangleEdge edge,
PlotRenderingInfo plotState) {
AxisState state;
// if the axis is not visible, don't draw it...
if (!isVisible()) {
state = new AxisState(cursor);
// even though the axis is not visible, we need ticks for the
// gridlines...
List<ValueTick> ticks = refreshTicks(g2, state, dataArea, edge);
state.setTicks(ticks);
return state;
}
// draw the tick marks and labels...
state = drawTickMarksAndLabels(g2, cursor, plotArea, dataArea, edge);
// // draw the marker band (if there is one)...
// if (getMarkerBand() != null) {
// if (edge == RectangleEdge.BOTTOM) {
// cursor = cursor - getMarkerBand().getHeight(g2);
// }
// getMarkerBand().draw(g2, plotArea, dataArea, 0, cursor);
// }
// draw the axis label...
state = drawLabel(getLabel(), g2, plotArea, dataArea, edge, state);
createAndAddEntity(cursor, state, dataArea, edge, plotState);
return state;
}
/**
* Creates the standard tick units.
* <P>
* If you don't like these defaults, create your own instance of TickUnits
* and then pass it to the setStandardTickUnits() method in the
* NumberAxis class.
*
* @return The standard tick units.
*
* @see #setStandardTickUnits(TickUnitSource)
* @see #createIntegerTickUnits()
*/
public static TickUnitSource createStandardTickUnits() {
TickUnits units = new TickUnits();
DecimalFormat df000 = new DecimalFormat("0.0000000000");
DecimalFormat df00 = new DecimalFormat("0.000000000");
DecimalFormat df0 = new DecimalFormat("0.00000000");
DecimalFormat df1 = new DecimalFormat("0.0000000");
DecimalFormat df2 = new DecimalFormat("0.000000");
DecimalFormat df3 = new DecimalFormat("0.00000");
DecimalFormat df4 = new DecimalFormat("0.0000");
DecimalFormat df5 = new DecimalFormat("0.000");
DecimalFormat df6 = new DecimalFormat("0.00");
DecimalFormat df7 = new DecimalFormat("0.0");
DecimalFormat df8 = new DecimalFormat("#,##0");
DecimalFormat df9 = new DecimalFormat("#,###,##0");
DecimalFormat df10 = new DecimalFormat("#,###,###,##0");
// we can add the units in any order, the TickUnits collection will
// sort them...
units.add(new NumberTickUnit(0.000000001, df00, 2));
units.add(new NumberTickUnit(0.00000001, df0, 2));
units.add(new NumberTickUnit(0.0000001, df1, 2));
units.add(new NumberTickUnit(0.000001, df2, 2));
units.add(new NumberTickUnit(0.00001, df3, 2));
units.add(new NumberTickUnit(0.0001, df4, 2));
units.add(new NumberTickUnit(0.001, df5, 2));
units.add(new NumberTickUnit(0.01, df6, 2));
units.add(new NumberTickUnit(0.1, df7, 2));
units.add(new NumberTickUnit(1, df8, 2));
units.add(new NumberTickUnit(10, df8, 2));
units.add(new NumberTickUnit(100, df8, 2));
units.add(new NumberTickUnit(1000, df8, 2));
units.add(new NumberTickUnit(10000, df8, 2));
units.add(new NumberTickUnit(100000, df8, 2));
units.add(new NumberTickUnit(1000000, df9, 2));
units.add(new NumberTickUnit(10000000, df9, 2));
units.add(new NumberTickUnit(100000000, df9, 2));
units.add(new NumberTickUnit(1000000000, df10, 2));
units.add(new NumberTickUnit(10000000000.0, df10, 2));
units.add(new NumberTickUnit(100000000000.0, df10, 2));
units.add(new NumberTickUnit(0.0000000025, df000, 5));
units.add(new NumberTickUnit(0.000000025, df00, 5));
units.add(new NumberTickUnit(0.00000025, df0, 5));
units.add(new NumberTickUnit(0.0000025, df1, 5));
units.add(new NumberTickUnit(0.000025, df2, 5));
units.add(new NumberTickUnit(0.00025, df3, 5));
units.add(new NumberTickUnit(0.0025, df4, 5));
units.add(new NumberTickUnit(0.025, df5, 5));
units.add(new NumberTickUnit(0.25, df6, 5));
units.add(new NumberTickUnit(2.5, df7, 5));
units.add(new NumberTickUnit(25, df8, 5));
units.add(new NumberTickUnit(250, df8, 5));
units.add(new NumberTickUnit(2500, df8, 5));
units.add(new NumberTickUnit(25000, df8, 5));
units.add(new NumberTickUnit(250000, df8, 5));
units.add(new NumberTickUnit(2500000, df9, 5));
units.add(new NumberTickUnit(25000000, df9, 5));
units.add(new NumberTickUnit(250000000, df9, 5));
units.add(new NumberTickUnit(2500000000.0, df10, 5));
units.add(new NumberTickUnit(25000000000.0, df10, 5));
units.add(new NumberTickUnit(250000000000.0, df10, 5));
units.add(new NumberTickUnit(0.000000005, df00, 5));
units.add(new NumberTickUnit(0.00000005, df0, 5));
units.add(new NumberTickUnit(0.0000005, df1, 5));
units.add(new NumberTickUnit(0.000005, df2, 5));
units.add(new NumberTickUnit(0.00005, df3, 5));
units.add(new NumberTickUnit(0.0005, df4, 5));
units.add(new NumberTickUnit(0.005, df5, 5));
units.add(new NumberTickUnit(0.05, df6, 5));
units.add(new NumberTickUnit(0.5, df7, 5));
units.add(new NumberTickUnit(5L, df8, 5));
units.add(new NumberTickUnit(50L, df8, 5));
units.add(new NumberTickUnit(500L, df8, 5));
units.add(new NumberTickUnit(5000L, df8, 5));
units.add(new NumberTickUnit(50000L, df8, 5));
units.add(new NumberTickUnit(500000L, df8, 5));
units.add(new NumberTickUnit(5000000L, df9, 5));
units.add(new NumberTickUnit(50000000L, df9, 5));
units.add(new NumberTickUnit(500000000L, df9, 5));
units.add(new NumberTickUnit(5000000000L, df10, 5));
units.add(new NumberTickUnit(50000000000L, df10, 5));
units.add(new NumberTickUnit(500000000000L, df10, 5));
return units;
}
/**
* Returns a collection of tick units for integer values.
*
* @return A collection of tick units for integer values.
*
* @see #setStandardTickUnits(TickUnitSource)
* @see #createStandardTickUnits()
*/
public static TickUnitSource createIntegerTickUnits() {
TickUnits units = new TickUnits();
DecimalFormat df0 = new DecimalFormat("0");
DecimalFormat df1 = new DecimalFormat("#,##0");
units.add(new NumberTickUnit(1, df0, 2));
units.add(new NumberTickUnit(2, df0, 2));
units.add(new NumberTickUnit(5, df0, 5));
units.add(new NumberTickUnit(10, df0, 2));
units.add(new NumberTickUnit(20, df0, 2));
units.add(new NumberTickUnit(50, df0, 5));
units.add(new NumberTickUnit(100, df0, 2));
units.add(new NumberTickUnit(200, df0, 2));
units.add(new NumberTickUnit(500, df0, 5));
units.add(new NumberTickUnit(1000, df1, 2));
units.add(new NumberTickUnit(2000, df1, 2));
units.add(new NumberTickUnit(5000, df1, 5));
units.add(new NumberTickUnit(10000, df1, 2));
units.add(new NumberTickUnit(20000, df1, 2));
units.add(new NumberTickUnit(50000, df1, 5));
units.add(new NumberTickUnit(100000, df1, 2));
units.add(new NumberTickUnit(200000, df1, 2));
units.add(new NumberTickUnit(500000, df1, 5));
units.add(new NumberTickUnit(1000000, df1, 2));
units.add(new NumberTickUnit(2000000, df1, 2));
units.add(new NumberTickUnit(5000000, df1, 5));
units.add(new NumberTickUnit(10000000, df1, 2));
units.add(new NumberTickUnit(20000000, df1, 2));
units.add(new NumberTickUnit(50000000, df1, 5));
units.add(new NumberTickUnit(100000000, df1, 2));
units.add(new NumberTickUnit(200000000, df1, 2));
units.add(new NumberTickUnit(500000000, df1, 5));
units.add(new NumberTickUnit(1000000000, df1, 2));
units.add(new NumberTickUnit(2000000000, df1, 2));
units.add(new NumberTickUnit(5000000000.0, df1, 5));
units.add(new NumberTickUnit(10000000000.0, df1, 2));
return units;
}
/**
* Creates a collection of standard tick units. The supplied locale is
* used to create the number formatter (a localised instance of
* <code>NumberFormat</code>).
* <P>
* If you don't like these defaults, create your own instance of
* {@link TickUnits} and then pass it to the
* <code>setStandardTickUnits()</code> method.
*
* @param locale the locale.
*
* @return A tick unit collection.
*
* @see #setStandardTickUnits(TickUnitSource)
*/
public static TickUnitSource createStandardTickUnits(Locale locale) {
TickUnits units = new TickUnits();
NumberFormat numberFormat = NumberFormat.getNumberInstance(locale);
// we can add the units in any order, the TickUnits collection will
// sort them...
units.add(new NumberTickUnit(0.0000001, numberFormat, 2));
units.add(new NumberTickUnit(0.000001, numberFormat, 2));
units.add(new NumberTickUnit(0.00001, numberFormat, 2));
units.add(new NumberTickUnit(0.0001, numberFormat, 2));
units.add(new NumberTickUnit(0.001, numberFormat, 2));
units.add(new NumberTickUnit(0.01, numberFormat, 2));
units.add(new NumberTickUnit(0.1, numberFormat, 2));
units.add(new NumberTickUnit(1, numberFormat, 2));
units.add(new NumberTickUnit(10, numberFormat, 2));
units.add(new NumberTickUnit(100, numberFormat, 2));
units.add(new NumberTickUnit(1000, numberFormat, 2));
units.add(new NumberTickUnit(10000, numberFormat, 2));
units.add(new NumberTickUnit(100000, numberFormat, 2));
units.add(new NumberTickUnit(1000000, numberFormat, 2));
units.add(new NumberTickUnit(10000000, numberFormat, 2));
units.add(new NumberTickUnit(100000000, numberFormat, 2));
units.add(new NumberTickUnit(1000000000, numberFormat, 2));
units.add(new NumberTickUnit(10000000000.0, numberFormat, 2));
units.add(new NumberTickUnit(0.00000025, numberFormat, 5));
units.add(new NumberTickUnit(0.0000025, numberFormat, 5));
units.add(new NumberTickUnit(0.000025, numberFormat, 5));
units.add(new NumberTickUnit(0.00025, numberFormat, 5));
units.add(new NumberTickUnit(0.0025, numberFormat, 5));
units.add(new NumberTickUnit(0.025, numberFormat, 5));
units.add(new NumberTickUnit(0.25, numberFormat, 5));
units.add(new NumberTickUnit(2.5, numberFormat, 5));
units.add(new NumberTickUnit(25, numberFormat, 5));
units.add(new NumberTickUnit(250, numberFormat, 5));
units.add(new NumberTickUnit(2500, numberFormat, 5));
units.add(new NumberTickUnit(25000, numberFormat, 5));
units.add(new NumberTickUnit(250000, numberFormat, 5));
units.add(new NumberTickUnit(2500000, numberFormat, 5));
units.add(new NumberTickUnit(25000000, numberFormat, 5));
units.add(new NumberTickUnit(250000000, numberFormat, 5));
units.add(new NumberTickUnit(2500000000.0, numberFormat, 5));
units.add(new NumberTickUnit(25000000000.0, numberFormat, 5));
units.add(new NumberTickUnit(0.0000005, numberFormat, 5));
units.add(new NumberTickUnit(0.000005, numberFormat, 5));
units.add(new NumberTickUnit(0.00005, numberFormat, 5));
units.add(new NumberTickUnit(0.0005, numberFormat, 5));
units.add(new NumberTickUnit(0.005, numberFormat, 5));
units.add(new NumberTickUnit(0.05, numberFormat, 5));
units.add(new NumberTickUnit(0.5, numberFormat, 5));
units.add(new NumberTickUnit(5L, numberFormat, 5));
units.add(new NumberTickUnit(50L, numberFormat, 5));
units.add(new NumberTickUnit(500L, numberFormat, 5));
units.add(new NumberTickUnit(5000L, numberFormat, 5));
units.add(new NumberTickUnit(50000L, numberFormat, 5));
units.add(new NumberTickUnit(500000L, numberFormat, 5));
units.add(new NumberTickUnit(5000000L, numberFormat, 5));
units.add(new NumberTickUnit(50000000L, numberFormat, 5));
units.add(new NumberTickUnit(500000000L, numberFormat, 5));
units.add(new NumberTickUnit(5000000000L, numberFormat, 5));
units.add(new NumberTickUnit(50000000000L, numberFormat, 5));
return units;
}
/**
* Returns a collection of tick units for integer values.
* Uses a given Locale to create the DecimalFormats.
*
* @param locale the locale to use to represent Numbers.
*
* @return A collection of tick units for integer values.
*
* @see #setStandardTickUnits(TickUnitSource)
*/
public static TickUnitSource createIntegerTickUnits(Locale locale) {
TickUnits units = new TickUnits();
NumberFormat numberFormat = NumberFormat.getNumberInstance(locale);
units.add(new NumberTickUnit(1, numberFormat, 2));
units.add(new NumberTickUnit(2, numberFormat, 2));
units.add(new NumberTickUnit(5, numberFormat, 5));
units.add(new NumberTickUnit(10, numberFormat, 2));
units.add(new NumberTickUnit(20, numberFormat, 2));
units.add(new NumberTickUnit(50, numberFormat, 5));
units.add(new NumberTickUnit(100, numberFormat, 2));
units.add(new NumberTickUnit(200, numberFormat, 2));
units.add(new NumberTickUnit(500, numberFormat, 5));
units.add(new NumberTickUnit(1000, numberFormat, 2));
units.add(new NumberTickUnit(2000, numberFormat, 2));
units.add(new NumberTickUnit(5000, numberFormat, 5));
units.add(new NumberTickUnit(10000, numberFormat, 2));
units.add(new NumberTickUnit(20000, numberFormat, 2));
units.add(new NumberTickUnit(50000, numberFormat, 5));
units.add(new NumberTickUnit(100000, numberFormat, 2));
units.add(new NumberTickUnit(200000, numberFormat, 2));
units.add(new NumberTickUnit(500000, numberFormat, 5));
units.add(new NumberTickUnit(1000000, numberFormat, 2));
units.add(new NumberTickUnit(2000000, numberFormat, 2));
units.add(new NumberTickUnit(5000000, numberFormat, 5));
units.add(new NumberTickUnit(10000000, numberFormat, 2));
units.add(new NumberTickUnit(20000000, numberFormat, 2));
units.add(new NumberTickUnit(50000000, numberFormat, 5));
units.add(new NumberTickUnit(100000000, numberFormat, 2));
units.add(new NumberTickUnit(200000000, numberFormat, 2));
units.add(new NumberTickUnit(500000000, numberFormat, 5));
units.add(new NumberTickUnit(1000000000, numberFormat, 2));
units.add(new NumberTickUnit(2000000000, numberFormat, 2));
units.add(new NumberTickUnit(5000000000.0, numberFormat, 5));
units.add(new NumberTickUnit(10000000000.0, numberFormat, 2));
return units;
}
/**
* Estimates the maximum tick label height.
*
* @param g2 the graphics device.
*
* @return The maximum height.
*/
protected double estimateMaximumTickLabelHeight(Graphics2D g2) {
RectangleInsets tickLabelInsets = getTickLabelInsets();
double result = tickLabelInsets.getTop() + tickLabelInsets.getBottom();
Font tickLabelFont = getTickLabelFont();
FontRenderContext frc = g2.getFontRenderContext();
result += tickLabelFont.getLineMetrics("123", frc).getHeight();
return result;
}
/**
* Estimates the maximum width of the tick labels, assuming the specified
* tick unit is used.
* <P>
* Rather than computing the string bounds of every tick on the axis, we
* just look at two values: the lower bound and the upper bound for the
* axis. These two values will usually be representative.
*
* @param g2 the graphics device.
* @param unit the tick unit to use for calculation.
*
* @return The estimated maximum width of the tick labels.
*/
protected double estimateMaximumTickLabelWidth(Graphics2D g2,
TickUnit unit) {
RectangleInsets tickLabelInsets = getTickLabelInsets();
double result = tickLabelInsets.getLeft() + tickLabelInsets.getRight();
if (isVerticalTickLabels()) {
// all tick labels have the same width (equal to the height of the
// font)...
FontRenderContext frc = g2.getFontRenderContext();
LineMetrics lm = getTickLabelFont().getLineMetrics("0", frc);
result += lm.getHeight();
}
else {
// look at lower and upper bounds...
FontMetrics fm = g2.getFontMetrics(getTickLabelFont());
Range range = getRange();
double lower = range.getLowerBound();
double upper = range.getUpperBound();
String lowerStr;
String upperStr;
NumberFormat formatter = getNumberFormatOverride();
if (formatter != null) {
lowerStr = formatter.format(lower);
upperStr = formatter.format(upper);
}
else {
lowerStr = unit.valueToString(lower);
upperStr = unit.valueToString(upper);
}
double w1 = fm.stringWidth(lowerStr);
double w2 = fm.stringWidth(upperStr);
result += Math.max(w1, w2);
}
return result;
}
/**
* Selects an appropriate tick value for the axis. The strategy is to
* display as many ticks as possible (selected from an array of 'standard'
* tick units) without the labels overlapping.
*
* @param g2 the graphics device.
* @param dataArea the area defined by the axes.
* @param edge the axis location.
*/
protected void selectAutoTickUnit(Graphics2D g2,
Rectangle2D dataArea,
RectangleEdge edge) {
if (RectangleEdge.isTopOrBottom(edge)) {
selectHorizontalAutoTickUnit(g2, dataArea, edge);
}
else if (RectangleEdge.isLeftOrRight(edge)) {
selectVerticalAutoTickUnit(g2, dataArea, edge);
}
}
/**
* Selects an appropriate tick value for the axis. The strategy is to
* display as many ticks as possible (selected from an array of 'standard'
* tick units) without the labels overlapping.
*
* @param g2 the graphics device.
* @param dataArea the area defined by the axes.
* @param edge the axis location.
*/
protected void selectHorizontalAutoTickUnit(Graphics2D g2,
Rectangle2D dataArea,
RectangleEdge edge) {
double tickLabelWidth = estimateMaximumTickLabelWidth(g2,
getTickUnit());
// start with the current tick unit...
TickUnitSource tickUnits = getStandardTickUnits();
TickUnit unit1 = tickUnits.getCeilingTickUnit(getTickUnit());
double unit1Width = lengthToJava2D(unit1.getSize(), dataArea, edge);
// then extrapolate...
double guess = (tickLabelWidth / unit1Width) * unit1.getSize();
NumberTickUnit unit2 = (NumberTickUnit) tickUnits.getCeilingTickUnit(
guess);
double unit2Width = lengthToJava2D(unit2.getSize(), dataArea, edge);
tickLabelWidth = estimateMaximumTickLabelWidth(g2, unit2);
if (tickLabelWidth > unit2Width) {
unit2 = (NumberTickUnit) tickUnits.getLargerTickUnit(unit2);
}
setTickUnit(unit2, false, false);
}
/**
* Selects an appropriate tick value for the axis. The strategy is to
* display as many ticks as possible (selected from an array of 'standard'
* tick units) without the labels overlapping.
*
* @param g2 the graphics device.
* @param dataArea the area in which the plot should be drawn.
* @param edge the axis location.
*/
protected void selectVerticalAutoTickUnit(Graphics2D g2,
Rectangle2D dataArea,
RectangleEdge edge) {
double tickLabelHeight = estimateMaximumTickLabelHeight(g2);
// start with the current tick unit...
TickUnitSource tickUnits = getStandardTickUnits();
TickUnit unit1 = tickUnits.getCeilingTickUnit(getTickUnit());
double unitHeight = lengthToJava2D(unit1.getSize(), dataArea, edge);
// then extrapolate...
double guess = (tickLabelHeight / unitHeight) * unit1.getSize();
NumberTickUnit unit2
= (NumberTickUnit) tickUnits.getCeilingTickUnit(guess);
double unit2Height = lengthToJava2D(unit2.getSize(), dataArea, edge);
tickLabelHeight = estimateMaximumTickLabelHeight(g2);
if (tickLabelHeight > unit2Height) {
unit2 = (NumberTickUnit) tickUnits.getLargerTickUnit(unit2);
}
setTickUnit(unit2, false, false);
}
/**
* Calculates the positions of the tick labels for the axis, storing the
* results in the tick label list (ready for drawing).
*
* @param g2 the graphics device.
* @param state the axis state.
* @param dataArea the area in which the plot should be drawn.
* @param edge the location of the axis.
*
* @return A list of ticks.
*
*/
@Override
public List<ValueTick> refreshTicks(Graphics2D g2,
AxisState state,
Rectangle2D dataArea,
RectangleEdge edge) {
List<ValueTick> result = new java.util.ArrayList<ValueTick>();
if (RectangleEdge.isTopOrBottom(edge)) {
result = refreshTicksHorizontal(g2, dataArea, edge);
}
else if (RectangleEdge.isLeftOrRight(edge)) {
result = refreshTicksVertical(g2, dataArea, edge);
}
return result;
}
/**
* Calculates the positions of the tick labels for the axis, storing the
* results in the tick label list (ready for drawing).
*
* @param g2 the graphics device.
* @param dataArea the area in which the data should be drawn.
* @param edge the location of the axis.
*
* @return A list of ticks.
*/
protected List<ValueTick> refreshTicksHorizontal(Graphics2D g2,
Rectangle2D dataArea, RectangleEdge edge) {
List<ValueTick> result = new java.util.ArrayList<ValueTick>();
Font tickLabelFont = getTickLabelFont();
g2.setFont(tickLabelFont);
if (isAutoTickUnitSelection()) {
selectAutoTickUnit(g2, dataArea, edge);
}
TickUnit tu = getTickUnit();
double size = tu.getSize();
int count = calculateVisibleTickCount();
double lowestTickValue = calculateLowestVisibleTickValue();
if (count <= ValueAxis.MAXIMUM_TICK_COUNT) {
int minorTickSpaces = getMinorTickCount();
if (minorTickSpaces <= 0) {
minorTickSpaces = tu.getMinorTickCount();
}
for (int minorTick = 1; minorTick < minorTickSpaces; minorTick++) {
double minorTickValue = lowestTickValue
- size * minorTick / minorTickSpaces;
if (getRange().contains(minorTickValue)) {
result.add(new NumberTick(TickType.MINOR, minorTickValue,
"", TextAnchor.TOP_CENTER, TextAnchor.CENTER,
0.0));
}
}
for (int i = 0; i < count; i++) {
double currentTickValue = lowestTickValue + (i * size);
String tickLabel;
NumberFormat formatter = getNumberFormatOverride();
if (formatter != null) {
tickLabel = formatter.format(currentTickValue);
}
else {
tickLabel = getTickUnit().valueToString(currentTickValue);
}
TextAnchor anchor;
TextAnchor rotationAnchor;
double angle = 0.0;
if (isVerticalTickLabels()) {
anchor = TextAnchor.CENTER_RIGHT;
rotationAnchor = TextAnchor.CENTER_RIGHT;
if (edge == RectangleEdge.TOP) {
angle = Math.PI / 2.0;
}
else {
angle = -Math.PI / 2.0;
}
}
else {
if (edge == RectangleEdge.TOP) {
anchor = TextAnchor.BOTTOM_CENTER;
rotationAnchor = TextAnchor.BOTTOM_CENTER;
}
else {
anchor = TextAnchor.TOP_CENTER;
rotationAnchor = TextAnchor.TOP_CENTER;
}
}
result.add(new NumberTick(currentTickValue,
tickLabel, anchor, rotationAnchor, angle));
double nextTickValue = lowestTickValue + ((i + 1) * size);
for (int minorTick = 1; minorTick < minorTickSpaces;
minorTick++) {
double minorTickValue = currentTickValue
+ (nextTickValue - currentTickValue)
* minorTick / minorTickSpaces;
if (getRange().contains(minorTickValue)) {
result.add(new NumberTick(TickType.MINOR,
minorTickValue, "", TextAnchor.TOP_CENTER,
TextAnchor.CENTER, 0.0));
}
}
}
}
return result;
}
/**
* Calculates the positions of the tick labels for the axis, storing the
* results in the tick label list (ready for drawing).
*
* @param g2 the graphics device.
* @param dataArea the area in which the plot should be drawn.
* @param edge the location of the axis.
*
* @return A list of ticks.
*/
protected List<ValueTick> refreshTicksVertical(Graphics2D g2,
Rectangle2D dataArea, RectangleEdge edge) {
List<ValueTick> result = new java.util.ArrayList<ValueTick>();
result.clear();
Font tickLabelFont = getTickLabelFont();
g2.setFont(tickLabelFont);
if (isAutoTickUnitSelection()) {
selectAutoTickUnit(g2, dataArea, edge);
}
TickUnit tu = getTickUnit();
double size = tu.getSize();
int count = calculateVisibleTickCount();
double lowestTickValue = calculateLowestVisibleTickValue();
if (count <= ValueAxis.MAXIMUM_TICK_COUNT) {
int minorTickSpaces = getMinorTickCount();
if (minorTickSpaces <= 0) {
minorTickSpaces = tu.getMinorTickCount();
}
for (int minorTick = 1; minorTick < minorTickSpaces; minorTick++) {
double minorTickValue = lowestTickValue
- size * minorTick / minorTickSpaces;
if (getRange().contains(minorTickValue)) {
result.add(new NumberTick(TickType.MINOR, minorTickValue,
"", TextAnchor.TOP_CENTER, TextAnchor.CENTER,
0.0));
}
}
for (int i = 0; i < count; i++) {
double currentTickValue = lowestTickValue + (i * size);
String tickLabel;
NumberFormat formatter = getNumberFormatOverride();
if (formatter != null) {
tickLabel = formatter.format(currentTickValue);
}
else {
tickLabel = getTickUnit().valueToString(currentTickValue);
}
TextAnchor anchor;
TextAnchor rotationAnchor;
double angle = 0.0;
if (isVerticalTickLabels()) {
if (edge == RectangleEdge.LEFT) {
anchor = TextAnchor.BOTTOM_CENTER;
rotationAnchor = TextAnchor.BOTTOM_CENTER;
angle = -Math.PI / 2.0;
}
else {
anchor = TextAnchor.BOTTOM_CENTER;
rotationAnchor = TextAnchor.BOTTOM_CENTER;
angle = Math.PI / 2.0;
}
}
else {
if (edge == RectangleEdge.LEFT) {
anchor = TextAnchor.CENTER_RIGHT;
rotationAnchor = TextAnchor.CENTER_RIGHT;
}
else {
anchor = TextAnchor.CENTER_LEFT;
rotationAnchor = TextAnchor.CENTER_LEFT;
}
}
result.add(new NumberTick(currentTickValue,
tickLabel, anchor, rotationAnchor, angle));
double nextTickValue = lowestTickValue + ((i + 1) * size);
for (int minorTick = 1; minorTick < minorTickSpaces;
minorTick++) {
double minorTickValue = currentTickValue
+ (nextTickValue - currentTickValue)
* minorTick / minorTickSpaces;
if (getRange().contains(minorTickValue)) {
result.add(new NumberTick(TickType.MINOR,
minorTickValue, "", TextAnchor.TOP_CENTER,
TextAnchor.CENTER, 0.0));
}
}
}
}
return result;
}
/**
* Returns a clone of the axis.
*
* @return A clone
*
* @throws CloneNotSupportedException if some component of the axis does
* not support cloning.
*/
@Override
public Object clone() throws CloneNotSupportedException {
NumberAxis clone = (NumberAxis) super.clone();
if (this.numberFormatOverride != null) {
clone.numberFormatOverride
= (NumberFormat) this.numberFormatOverride.clone();
}
return clone;
}
/**
* Tests the axis 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 NumberAxis)) {
return false;
}
NumberAxis that = (NumberAxis) obj;
if (this.autoRangeIncludesZero != that.autoRangeIncludesZero) {
return false;
}
if (this.autoRangeStickyZero != that.autoRangeStickyZero) {
return false;
}
if (!ObjectUtilities.equal(this.tickUnit, that.tickUnit)) {
return false;
}
if (!ObjectUtilities.equal(this.numberFormatOverride,
that.numberFormatOverride)) {
return false;
}
if (!this.rangeType.equals(that.rangeType)) {
return false;
}
return super.equals(obj);
}
@Override
public int hashCode() {
return super.hashCode();
}
}
| 55,652 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
MonthDateFormat.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/axis/MonthDateFormat.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.]
*
* --------------------
* MonthDateFormat.java
* --------------------
* (C) Copyright 2005-2008, by Object Refinery Limited and Contributors.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes:
* --------
* 10-May-2005 : Version 1 (DG);
*
*/
package org.jfree.chart.axis;
import java.text.DateFormat;
import java.text.DateFormatSymbols;
import java.text.FieldPosition;
import java.text.NumberFormat;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.TimeZone;
import org.jfree.data.time.Month;
/**
* A formatter that formats dates to show the initial letter(s) of the month
* name and, as an option, the year for the first or last month of each year.
*/
public class MonthDateFormat extends DateFormat {
/** The symbols used for the months. */
private String[] months;
/** Flags that control which months will have the year appended. */
private boolean[] showYear;
/** The year formatter. */
private DateFormat yearFormatter;
/**
* Creates a new instance for the default time zone.
*/
public MonthDateFormat() {
this(TimeZone.getDefault());
}
/**
* Creates a new instance for the specified time zone.
*
* @param zone the time zone (<code>null</code> not permitted).
*/
public MonthDateFormat(TimeZone zone) {
this(zone, Locale.getDefault(), 1, true, false);
}
/**
* Creates a new instance for the specified time zone.
*
* @param locale the locale used to obtain the month
* names (<code>null</code> not permitted).
*/
public MonthDateFormat(Locale locale) {
this(TimeZone.getDefault(), locale, 1, true, false);
}
/**
* Creates a new instance for the specified time zone.
*
* @param zone the time zone (<code>null</code> not permitted).
* @param chars the maximum number of characters to use from the month
* names (that are obtained from the date symbols of the
* default locale). If this value is <= 0, the entire
* month name is used in each case.
*/
public MonthDateFormat(TimeZone zone, int chars) {
this(zone, Locale.getDefault(), chars, true, false);
}
/**
* Creates a new instance for the specified time zone.
*
* @param locale the locale (<code>null</code> not permitted).
* @param chars the maximum number of characters to use from the month
* names (that are obtained from the date symbols of the
* default locale). If this value is <= 0, the entire
* month name is used in each case.
*/
public MonthDateFormat(Locale locale, int chars) {
this(TimeZone.getDefault(), locale, chars, true, false);
}
/**
* Creates a new formatter.
*
* @param zone the time zone used to extract the month and year from dates
* passed to this formatter (<code>null</code> not permitted).
* @param locale the locale used to determine the month names
* (<code>null</code> not permitted).
* @param chars the maximum number of characters to use from the month
* names, or zero to indicate that the entire month name
* should be used.
* @param showYearForJan a flag that controls whether or not the year is
* appended to the symbol for the first month of
* each year.
* @param showYearForDec a flag that controls whether or not the year is
* appended to the symbol for the last month of
* each year.
*/
public MonthDateFormat(TimeZone zone, Locale locale, int chars,
boolean showYearForJan, boolean showYearForDec) {
this(zone, locale, chars, new boolean[] {showYearForJan, false, false,
false, false, false, false, false, false, false, false, false,
showYearForDec}, new SimpleDateFormat("yy"));
}
/**
* Creates a new formatter.
*
* @param zone the time zone used to extract the month and year from dates
* passed to this formatter (<code>null</code> not permitted).
* @param locale the locale used to determine the month names
* (<code>null</code> not permitted).
* @param chars the maximum number of characters to use from the month
* names, or zero to indicate that the entire month name
* should be used.
* @param showYear an array of flags that control whether or not the
* year is displayed for a particular month.
* @param yearFormatter the year formatter.
*/
public MonthDateFormat(TimeZone zone, Locale locale, int chars,
boolean[] showYear, DateFormat yearFormatter) {
if (locale == null) {
throw new IllegalArgumentException("Null 'locale' argument.");
}
DateFormatSymbols dfs = new DateFormatSymbols(locale);
String[] monthsFromLocale = dfs.getMonths();
this.months = new String[12];
for (int i = 0; i < 12; i++) {
if (chars > 0) {
this.months[i] = monthsFromLocale[i].substring(0,
Math.min(chars, monthsFromLocale[i].length()));
}
else {
this.months[i] = monthsFromLocale[i];
}
}
this.calendar = new GregorianCalendar(zone);
this.showYear = showYear;
this.yearFormatter = yearFormatter;
// the following is never used, but it seems that DateFormat requires
// it to be non-null. It isn't well covered in the spec, refer to
// bug parade 5061189 for more info.
this.numberFormat = NumberFormat.getNumberInstance();
}
/**
* Formats the given date.
*
* @param date the date.
* @param toAppendTo the string buffer.
* @param fieldPosition the field position.
*
* @return The formatted date.
*/
@Override
public StringBuffer format(Date date, StringBuffer toAppendTo,
FieldPosition fieldPosition) {
this.calendar.setTime(date);
int month = this.calendar.get(Calendar.MONTH);
toAppendTo.append(this.months[month]);
if (this.showYear[month]) {
toAppendTo.append(this.yearFormatter.format(date));
}
return toAppendTo;
}
/**
* Parses the given string (not implemented).
*
* @param source the date string.
* @param pos the parse position.
*
* @return <code>null</code>, as this method has not been implemented.
*/
@Override
public Date parse(String source, ParsePosition pos) {
return null;
}
/**
* Tests this formatter for equality with an arbitrary object.
*
* @param obj the object.
*
* @return A boolean.
*/
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof MonthDateFormat)) {
return false;
}
if (!super.equals(obj)) {
return false;
}
MonthDateFormat that = (MonthDateFormat) obj;
if (!Arrays.equals(this.months, that.months)) {
return false;
}
if (!Arrays.equals(this.showYear, that.showYear)) {
return false;
}
if (!this.yearFormatter.equals(that.yearFormatter)) {
return false;
}
return true;
}
/**
* Some test code.
*
* @param args ignored.
*/
public static void main(String[] args) {
MonthDateFormat mdf = new MonthDateFormat(Locale.UK, 2);
System.out.println("UK:");
System.out.println(mdf.format(new Month(1, 2005).getStart()));
System.out.println(mdf.format(new Month(2, 2005).getStart()));
System.out.println(mdf.format(new Month(3, 2005).getStart()));
System.out.println(mdf.format(new Month(4, 2005).getStart()));
System.out.println(mdf.format(new Month(5, 2005).getStart()));
System.out.println(mdf.format(new Month(6, 2005).getStart()));
System.out.println(mdf.format(new Month(7, 2005).getStart()));
System.out.println(mdf.format(new Month(8, 2005).getStart()));
System.out.println(mdf.format(new Month(9, 2005).getStart()));
System.out.println(mdf.format(new Month(10, 2005).getStart()));
System.out.println(mdf.format(new Month(11, 2005).getStart()));
System.out.println(mdf.format(new Month(12, 2005).getStart()));
System.out.println();
mdf = new MonthDateFormat(Locale.GERMANY, 2);
System.out.println("GERMANY:");
System.out.println(mdf.format(new Month(1, 2005).getStart()));
System.out.println(mdf.format(new Month(2, 2005).getStart()));
System.out.println(mdf.format(new Month(3, 2005).getStart()));
System.out.println(mdf.format(new Month(4, 2005).getStart()));
System.out.println(mdf.format(new Month(5, 2005).getStart()));
System.out.println(mdf.format(new Month(6, 2005).getStart()));
System.out.println(mdf.format(new Month(7, 2005).getStart()));
System.out.println(mdf.format(new Month(8, 2005).getStart()));
System.out.println(mdf.format(new Month(9, 2005).getStart()));
System.out.println(mdf.format(new Month(10, 2005).getStart()));
System.out.println(mdf.format(new Month(11, 2005).getStart()));
System.out.println(mdf.format(new Month(12, 2005).getStart()));
System.out.println();
mdf = new MonthDateFormat(Locale.FRANCE, 2);
System.out.println("FRANCE:");
System.out.println(mdf.format(new Month(1, 2005).getStart()));
System.out.println(mdf.format(new Month(2, 2005).getStart()));
System.out.println(mdf.format(new Month(3, 2005).getStart()));
System.out.println(mdf.format(new Month(4, 2005).getStart()));
System.out.println(mdf.format(new Month(5, 2005).getStart()));
System.out.println(mdf.format(new Month(6, 2005).getStart()));
System.out.println(mdf.format(new Month(7, 2005).getStart()));
System.out.println(mdf.format(new Month(8, 2005).getStart()));
System.out.println(mdf.format(new Month(9, 2005).getStart()));
System.out.println(mdf.format(new Month(10, 2005).getStart()));
System.out.println(mdf.format(new Month(11, 2005).getStart()));
System.out.println(mdf.format(new Month(12, 2005).getStart()));
System.out.println();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
sdf.setNumberFormat(null);
}
}
| 12,310 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
LogAxis.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/axis/LogAxis.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.]
*
* ------------
* LogAxis.java
* ------------
* (C) Copyright 2006-2013, by Object Refinery Limited and Contributors.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): Andrew Mickish (patch 1868745);
* Peter Kolb (patches 1934255 and 2603321);
*
* Changes
* -------
* 24-Aug-2006 : Version 1 (DG);
* 22-Mar-2007 : Use defaultAutoArrange attribute (DG);
* 02-Aug-2007 : Fixed zooming bug, added support for margins (DG);
* 14-Feb-2008 : Changed default minorTickCount to 9 - see bug report
* 1892419 (DG);
* 15-Feb-2008 : Applied a variation of patch 1868745 by Andrew Mickish to
* fix a labelling bug when the axis appears at the top or
* right of the chart (DG);
* 19-Mar-2008 : Applied patch 1902418 by Andrew Mickish to fix bug in tick
* labels for vertical axis (DG);
* 26-Mar-2008 : Changed createTickLabel() method from private to protected -
* see patch 1918209 by Andrew Mickish (DG);
* 25-Sep-2008 : Moved minor tick fields up to superclass, see patch 1934255
* by Peter Kolb (DG);
* 14-Jan-2009 : Fetch minor ticks from TickUnit, and corrected
* createLogTickUnits() (DG);
* 21-Jan-2009 : No need to call setMinorTickCount() in constructor (DG);
* 19-Mar-2009 : Added entity support - see patch 2603321 by Peter Kolb (DG);
* 30-Mar-2009 : Added pan(double) method (DG);
* 28-Oct-2011 : Fixed endless loop for 0 TickUnit, # 3429707 (MH);
* 17-Jun-2012 : Removed JCommon dependencies (DG);
*
*/
package org.jfree.chart.axis;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.font.FontRenderContext;
import java.awt.font.LineMetrics;
import java.awt.geom.Rectangle2D;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import org.jfree.chart.ui.RectangleEdge;
import org.jfree.chart.ui.RectangleInsets;
import org.jfree.chart.ui.TextAnchor;
import org.jfree.chart.event.AxisChangeEvent;
import org.jfree.chart.plot.Plot;
import org.jfree.chart.plot.PlotRenderingInfo;
import org.jfree.chart.plot.ValueAxisPlot;
import org.jfree.chart.util.LogFormat;
import org.jfree.chart.util.ParamChecks;
import org.jfree.data.Range;
/**
* A numerical axis that uses a logarithmic scale. The class is an
* alternative to the {@link LogarithmicAxis} class.
*
* @since 1.0.7
*/
public class LogAxis extends ValueAxis {
/** The logarithm base. */
private double base = 10.0;
/** The logarithm of the base value - cached for performance. */
private double baseLog = Math.log(10.0);
/** The smallest value permitted on the axis. */
private double smallestValue = 1E-100;
/** The current tick unit. */
private NumberTickUnit tickUnit;
/** The override number format. */
private NumberFormat numberFormatOverride;
/**
* Creates a new <code>LogAxis</code> with no label.
*/
public LogAxis() {
this(null);
}
/**
* Creates a new <code>LogAxis</code> with the given label.
*
* @param label the axis label (<code>null</code> permitted).
*/
public LogAxis(String label) {
super(label, createLogTickUnits(Locale.getDefault()));
setDefaultAutoRange(new Range(0.01, 1.0));
this.tickUnit = new NumberTickUnit(1.0, new DecimalFormat("0.#"), 9);
}
/**
* Returns the base for the logarithm calculation.
*
* @return The base for the logarithm calculation.
*
* @see #setBase(double)
*/
public double getBase() {
return this.base;
}
/**
* Sets the base for the logarithm calculation and sends an
* {@link AxisChangeEvent} to all registered listeners.
*
* @param base the base value (must be > 1.0).
*
* @see #getBase()
*/
public void setBase(double base) {
if (base <= 1.0) {
throw new IllegalArgumentException("Requires 'base' > 1.0.");
}
this.base = base;
this.baseLog = Math.log(base);
fireChangeEvent();
}
/**
* Returns the smallest value represented by the axis.
*
* @return The smallest value represented by the axis.
*
* @see #setSmallestValue(double)
*/
public double getSmallestValue() {
return this.smallestValue;
}
/**
* Sets the smallest value represented by the axis and sends an
* {@link AxisChangeEvent} to all registered listeners.
*
* @param value the value.
*
* @see #getSmallestValue()
*/
public void setSmallestValue(double value) {
if (value <= 0.0) {
throw new IllegalArgumentException("Requires 'value' > 0.0.");
}
this.smallestValue = value;
notifyListeners(new AxisChangeEvent(this));
}
/**
* Returns the current tick unit.
*
* @return The current tick unit.
*
* @see #setTickUnit(NumberTickUnit)
*/
public NumberTickUnit getTickUnit() {
return this.tickUnit;
}
/**
* Sets the tick unit for the axis and sends an {@link AxisChangeEvent} to
* all registered listeners. A side effect of calling this method is that
* the "auto-select" feature for tick units is switched off (you can
* restore it using the {@link ValueAxis#setAutoTickUnitSelection(boolean)}
* method).
*
* @param unit the new tick unit (<code>null</code> not permitted).
*
* @see #getTickUnit()
*/
public void setTickUnit(NumberTickUnit unit) {
// defer argument checking...
setTickUnit(unit, true, true);
}
/**
* Sets the tick unit for the axis and, if requested, sends an
* {@link AxisChangeEvent} to all registered listeners. In addition, an
* option is provided to turn off the "auto-select" feature for tick units
* (you can restore it using the
* {@link ValueAxis#setAutoTickUnitSelection(boolean)} method).
*
* @param unit the new tick unit (<code>null</code> not permitted).
* @param notify notify listeners?
* @param turnOffAutoSelect turn off the auto-tick selection?
*
* @see #getTickUnit()
*/
public void setTickUnit(NumberTickUnit unit, boolean notify,
boolean turnOffAutoSelect) {
ParamChecks.nullNotPermitted(unit, "unit");
this.tickUnit = unit;
if (turnOffAutoSelect) {
setAutoTickUnitSelection(false, false);
}
if (notify) {
fireChangeEvent();
}
}
/**
* Returns the number format override. If this is non-null, then it will
* be used to format the numbers on the axis.
*
* @return The number formatter (possibly <code>null</code>).
*
* @see #setNumberFormatOverride(NumberFormat)
*/
public NumberFormat getNumberFormatOverride() {
return this.numberFormatOverride;
}
/**
* Sets the number format override. If this is non-null, then it will be
* used to format the numbers on the axis.
*
* @param formatter the number formatter (<code>null</code> permitted).
*
* @see #getNumberFormatOverride()
*/
public void setNumberFormatOverride(NumberFormat formatter) {
this.numberFormatOverride = formatter;
notifyListeners(new AxisChangeEvent(this));
}
/**
* Calculates the log of the given value, using the current base.
*
* @param value the value.
*
* @return The log of the given value.
*
* @see #calculateValue(double)
* @see #getBase()
*/
public double calculateLog(double value) {
return Math.log(value) / this.baseLog;
}
/**
* Calculates the value from a given log.
*
* @param log the log value.
*
* @return The value with the given log.
*
* @see #calculateLog(double)
* @see #getBase()
*/
public double calculateValue(double log) {
return Math.pow(this.base, log);
}
/**
* Converts a Java2D coordinate to an axis value, assuming that the
* axis covers the specified <code>edge</code> of the <code>area</code>.
*
* @param java2DValue the Java2D coordinate.
* @param area the area.
* @param edge the edge that the axis belongs to.
*
* @return A value along the axis scale.
*/
@Override
public double java2DToValue(double java2DValue, Rectangle2D area,
RectangleEdge edge) {
Range range = getRange();
double axisMin = calculateLog(range.getLowerBound());
double axisMax = calculateLog(range.getUpperBound());
double min = 0.0;
double max = 0.0;
if (RectangleEdge.isTopOrBottom(edge)) {
min = area.getX();
max = area.getMaxX();
}
else if (RectangleEdge.isLeftOrRight(edge)) {
min = area.getMaxY();
max = area.getY();
}
double log = 0.0;
if (isInverted()) {
log = axisMax - (java2DValue - min) / (max - min)
* (axisMax - axisMin);
}
else {
log = axisMin + (java2DValue - min) / (max - min)
* (axisMax - axisMin);
}
return calculateValue(log);
}
/**
* Converts a value on the axis scale to a Java2D coordinate relative to
* the given <code>area</code>, based on the axis running along the
* specified <code>edge</code>.
*
* @param value the data value.
* @param area the area.
* @param edge the edge.
*
* @return The Java2D coordinate corresponding to <code>value</code>.
*/
@Override
public double valueToJava2D(double value, Rectangle2D area,
RectangleEdge edge) {
Range range = getRange();
double axisMin = calculateLog(range.getLowerBound());
double axisMax = calculateLog(range.getUpperBound());
value = calculateLog(value);
double min = 0.0;
double max = 0.0;
if (RectangleEdge.isTopOrBottom(edge)) {
min = area.getX();
max = area.getMaxX();
}
else if (RectangleEdge.isLeftOrRight(edge)) {
max = area.getMinY();
min = area.getMaxY();
}
if (isInverted()) {
return max
- ((value - axisMin) / (axisMax - axisMin)) * (max - min);
}
else {
return min
+ ((value - axisMin) / (axisMax - axisMin)) * (max - min);
}
}
/**
* Configures the axis. This method is typically called when an axis
* is assigned to a new plot.
*/
@Override
public void configure() {
if (isAutoRange()) {
autoAdjustRange();
}
}
/**
* Adjusts the axis range to match the data range that the axis is
* required to display.
*/
@Override
protected void autoAdjustRange() {
Plot plot = getPlot();
if (plot == null) {
return; // no plot, no data
}
if (plot instanceof ValueAxisPlot) {
ValueAxisPlot vap = (ValueAxisPlot) plot;
Range r = vap.getDataRange(this);
if (r == null) {
r = getDefaultAutoRange();
}
double upper = r.getUpperBound();
double lower = Math.max(r.getLowerBound(), this.smallestValue);
double range = upper - lower;
// if fixed auto range, then derive lower bound...
double fixedAutoRange = getFixedAutoRange();
if (fixedAutoRange > 0.0) {
lower = Math.max(upper - fixedAutoRange, this.smallestValue);
}
else {
// ensure the autorange is at least <minRange> in size...
double minRange = getAutoRangeMinimumSize();
if (range < minRange) {
double expand = (minRange - range) / 2;
upper = upper + expand;
lower = lower - expand;
}
// apply the margins - these should apply to the exponent range
double logUpper = calculateLog(upper);
double logLower = calculateLog(lower);
double logRange = logUpper - logLower;
logUpper = logUpper + getUpperMargin() * logRange;
logLower = logLower - getLowerMargin() * logRange;
upper = calculateValue(logUpper);
lower = calculateValue(logLower);
}
setRange(new Range(lower, upper), false, false);
}
}
/**
* Draws the axis on a Java 2D graphics device (such as the screen or a
* printer).
*
* @param g2 the graphics device (<code>null</code> not permitted).
* @param cursor the cursor location (determines where to draw the axis).
* @param plotArea the area within which the axes and plot should be drawn.
* @param dataArea the area within which the data should be drawn.
* @param edge the axis location (<code>null</code> not permitted).
* @param plotState collects information about the plot
* (<code>null</code> permitted).
*
* @return The axis state (never <code>null</code>).
*/
@Override
public AxisState draw(Graphics2D g2, double cursor, Rectangle2D plotArea,
Rectangle2D dataArea, RectangleEdge edge,
PlotRenderingInfo plotState) {
AxisState state;
// if the axis is not visible, don't draw it...
if (!isVisible()) {
state = new AxisState(cursor);
// even though the axis is not visible, we need ticks for the
// gridlines...
List<ValueTick> ticks = refreshTicks(g2, state, dataArea, edge);
state.setTicks(ticks);
return state;
}
state = drawTickMarksAndLabels(g2, cursor, plotArea, dataArea, edge);
state = drawLabel(getLabel(), g2, plotArea, dataArea, edge, state);
createAndAddEntity(cursor, state, dataArea, edge, plotState);
return state;
}
/**
* Calculates the positions of the tick labels for the axis, storing the
* results in the tick label list (ready for drawing).
*
* @param g2 the graphics device.
* @param state the axis state.
* @param dataArea the area in which the plot should be drawn.
* @param edge the location of the axis.
*
* @return A list of ticks.
*
*/
@Override
public List<ValueTick> refreshTicks(Graphics2D g2, AxisState state,
Rectangle2D dataArea, RectangleEdge edge) {
List<ValueTick> result = new java.util.ArrayList<ValueTick>();
if (RectangleEdge.isTopOrBottom(edge)) {
result = refreshTicksHorizontal(g2, dataArea, edge);
}
else if (RectangleEdge.isLeftOrRight(edge)) {
result = refreshTicksVertical(g2, dataArea, edge);
}
return result;
}
/**
* Returns a list of ticks for an axis at the top or bottom of the chart.
*
* @param g2 the graphics device.
* @param dataArea the data area.
* @param edge the edge.
*
* @return A list of ticks.
*/
protected List<ValueTick> refreshTicksHorizontal(Graphics2D g2, Rectangle2D dataArea,
RectangleEdge edge) {
Range range = getRange();
List<ValueTick> ticks = new ArrayList<ValueTick>();
Font tickLabelFont = getTickLabelFont();
g2.setFont(tickLabelFont);
TextAnchor textAnchor;
if (edge == RectangleEdge.TOP) {
textAnchor = TextAnchor.BOTTOM_CENTER;
}
else {
textAnchor = TextAnchor.TOP_CENTER;
}
if (isAutoTickUnitSelection()) {
selectAutoTickUnit(g2, dataArea, edge);
}
int minorTickCount = this.tickUnit.getMinorTickCount();
double start = Math.floor(calculateLog(getLowerBound()));
double end = Math.ceil(calculateLog(getUpperBound()));
double current = start;
boolean hasTicks = (this.tickUnit.getSize() > 0.0)
&& !Double.isInfinite(start);
while (hasTicks && current <= end) {
double v = calculateValue(current);
if (range.contains(v)) {
ticks.add(new NumberTick(TickType.MAJOR, v, createTickLabel(v),
textAnchor, TextAnchor.CENTER, 0.0));
}
// add minor ticks (for gridlines)
double next = Math.pow(this.base, current
+ this.tickUnit.getSize());
for (int i = 1; i < minorTickCount; i++) {
double minorV = v + i * ((next - v) / minorTickCount);
if (range.contains(minorV)) {
ticks.add(new NumberTick(TickType.MINOR, minorV, "",
textAnchor, TextAnchor.CENTER, 0.0));
}
}
current = current + this.tickUnit.getSize();
}
return ticks;
}
/**
* Returns a list of ticks for an axis at the left or right of the chart.
*
* @param g2 the graphics device.
* @param dataArea the data area.
* @param edge the edge.
*
* @return A list of ticks.
*/
protected List<ValueTick> refreshTicksVertical(Graphics2D g2, Rectangle2D dataArea,
RectangleEdge edge) {
Range range = getRange();
List<ValueTick> ticks = new ArrayList<ValueTick>();
Font tickLabelFont = getTickLabelFont();
g2.setFont(tickLabelFont);
TextAnchor textAnchor;
if (edge == RectangleEdge.RIGHT) {
textAnchor = TextAnchor.CENTER_LEFT;
}
else {
textAnchor = TextAnchor.CENTER_RIGHT;
}
if (isAutoTickUnitSelection()) {
selectAutoTickUnit(g2, dataArea, edge);
}
int minorTickCount = this.tickUnit.getMinorTickCount();
double start = Math.floor(calculateLog(getLowerBound()));
double end = Math.ceil(calculateLog(getUpperBound()));
double current = start;
boolean hasTicks = (this.tickUnit.getSize() > 0.0)
&& !Double.isInfinite(start);
while (hasTicks && current <= end) {
double v = calculateValue(current);
if (range.contains(v)) {
ticks.add(new NumberTick(TickType.MAJOR, v, createTickLabel(v),
textAnchor, TextAnchor.CENTER, 0.0));
}
// add minor ticks (for gridlines)
double next = Math.pow(this.base, current
+ this.tickUnit.getSize());
for (int i = 1; i < minorTickCount; i++) {
double minorV = v + i * ((next - v) / minorTickCount);
if (range.contains(minorV)) {
ticks.add(new NumberTick(TickType.MINOR, minorV, "",
textAnchor, TextAnchor.CENTER, 0.0));
}
}
current = current + this.tickUnit.getSize();
}
return ticks;
}
/**
* Selects an appropriate tick value for the axis. The strategy is to
* display as many ticks as possible (selected from an array of 'standard'
* tick units) without the labels overlapping.
*
* @param g2 the graphics device.
* @param dataArea the area defined by the axes.
* @param edge the axis location.
*
* @since 1.0.7
*/
protected void selectAutoTickUnit(Graphics2D g2, Rectangle2D dataArea,
RectangleEdge edge) {
if (RectangleEdge.isTopOrBottom(edge)) {
selectHorizontalAutoTickUnit(g2, dataArea, edge);
}
else if (RectangleEdge.isLeftOrRight(edge)) {
selectVerticalAutoTickUnit(g2, dataArea, edge);
}
}
/**
* Selects an appropriate tick value for the axis. The strategy is to
* display as many ticks as possible (selected from an array of 'standard'
* tick units) without the labels overlapping.
*
* @param g2 the graphics device.
* @param dataArea the area defined by the axes.
* @param edge the axis location.
*
* @since 1.0.7
*/
protected void selectHorizontalAutoTickUnit(Graphics2D g2,
Rectangle2D dataArea, RectangleEdge edge) {
double tickLabelWidth = estimateMaximumTickLabelWidth(g2,
getTickUnit());
// start with the current tick unit...
TickUnitSource tickUnits = getStandardTickUnits();
TickUnit unit1 = tickUnits.getCeilingTickUnit(getTickUnit());
double unit1Width = exponentLengthToJava2D(unit1.getSize(), dataArea,
edge);
// then extrapolate...
double guess = (tickLabelWidth / unit1Width) * unit1.getSize();
NumberTickUnit unit2 = (NumberTickUnit)
tickUnits.getCeilingTickUnit(guess);
double unit2Width = exponentLengthToJava2D(unit2.getSize(), dataArea,
edge);
tickLabelWidth = estimateMaximumTickLabelWidth(g2, unit2);
if (tickLabelWidth > unit2Width) {
unit2 = (NumberTickUnit) tickUnits.getLargerTickUnit(unit2);
}
setTickUnit(unit2, false, false);
}
/**
* Converts a length in data coordinates into the corresponding length in
* Java2D coordinates.
*
* @param length the length.
* @param area the plot area.
* @param edge the edge along which the axis lies.
*
* @return The length in Java2D coordinates.
*
* @since 1.0.7
*/
public double exponentLengthToJava2D(double length, Rectangle2D area,
RectangleEdge edge) {
double one = valueToJava2D(calculateValue(1.0), area, edge);
double l = valueToJava2D(calculateValue(length + 1.0), area, edge);
return Math.abs(l - one);
}
/**
* Selects an appropriate tick value for the axis. The strategy is to
* display as many ticks as possible (selected from an array of 'standard'
* tick units) without the labels overlapping.
*
* @param g2 the graphics device.
* @param dataArea the area in which the plot should be drawn.
* @param edge the axis location.
*
* @since 1.0.7
*/
protected void selectVerticalAutoTickUnit(Graphics2D g2,
Rectangle2D dataArea,
RectangleEdge edge) {
double tickLabelHeight = estimateMaximumTickLabelHeight(g2);
// start with the current tick unit...
TickUnitSource tickUnits = getStandardTickUnits();
TickUnit unit1 = tickUnits.getCeilingTickUnit(getTickUnit());
double unitHeight = exponentLengthToJava2D(unit1.getSize(), dataArea,
edge);
// then extrapolate...
double guess = (tickLabelHeight / unitHeight) * unit1.getSize();
NumberTickUnit unit2 = (NumberTickUnit)
tickUnits.getCeilingTickUnit(guess);
double unit2Height = exponentLengthToJava2D(unit2.getSize(), dataArea,
edge);
tickLabelHeight = estimateMaximumTickLabelHeight(g2);
if (tickLabelHeight > unit2Height) {
unit2 = (NumberTickUnit) tickUnits.getLargerTickUnit(unit2);
}
setTickUnit(unit2, false, false);
}
/**
* Estimates the maximum tick label height.
*
* @param g2 the graphics device.
*
* @return The maximum height.
*
* @since 1.0.7
*/
protected double estimateMaximumTickLabelHeight(Graphics2D g2) {
RectangleInsets tickLabelInsets = getTickLabelInsets();
double result = tickLabelInsets.getTop() + tickLabelInsets.getBottom();
Font tickLabelFont = getTickLabelFont();
FontRenderContext frc = g2.getFontRenderContext();
result += tickLabelFont.getLineMetrics("123", frc).getHeight();
return result;
}
/**
* Estimates the maximum width of the tick labels, assuming the specified
* tick unit is used.
* <P>
* Rather than computing the string bounds of every tick on the axis, we
* just look at two values: the lower bound and the upper bound for the
* axis. These two values will usually be representative.
*
* @param g2 the graphics device.
* @param unit the tick unit to use for calculation.
*
* @return The estimated maximum width of the tick labels.
*
* @since 1.0.7
*/
protected double estimateMaximumTickLabelWidth(Graphics2D g2,
TickUnit unit) {
RectangleInsets tickLabelInsets = getTickLabelInsets();
double result = tickLabelInsets.getLeft() + tickLabelInsets.getRight();
if (isVerticalTickLabels()) {
// all tick labels have the same width (equal to the height of the
// font)...
FontRenderContext frc = g2.getFontRenderContext();
LineMetrics lm = getTickLabelFont().getLineMetrics("0", frc);
result += lm.getHeight();
}
else {
// look at lower and upper bounds...
FontMetrics fm = g2.getFontMetrics(getTickLabelFont());
Range range = getRange();
double lower = range.getLowerBound();
double upper = range.getUpperBound();
String lowerStr, upperStr;
NumberFormat formatter = getNumberFormatOverride();
if (formatter != null) {
lowerStr = formatter.format(lower);
upperStr = formatter.format(upper);
}
else {
lowerStr = unit.valueToString(lower);
upperStr = unit.valueToString(upper);
}
double w1 = fm.stringWidth(lowerStr);
double w2 = fm.stringWidth(upperStr);
result += Math.max(w1, w2);
}
return result;
}
/**
* Zooms in on the current range.
*
* @param lowerPercent the new lower bound.
* @param upperPercent the new upper bound.
*/
@Override
public void zoomRange(double lowerPercent, double upperPercent) {
Range range = getRange();
double start = range.getLowerBound();
double end = range.getUpperBound();
double log1 = calculateLog(start);
double log2 = calculateLog(end);
double length = log2 - log1;
Range adjusted;
if (isInverted()) {
double logA = log1 + length * (1 - upperPercent);
double logB = log1 + length * (1 - lowerPercent);
adjusted = new Range(calculateValue(logA), calculateValue(logB));
}
else {
double logA = log1 + length * lowerPercent;
double logB = log1 + length * upperPercent;
adjusted = new Range(calculateValue(logA), calculateValue(logB));
}
setRange(adjusted);
}
/**
* Slides the axis range by the specified percentage.
*
* @param percent the percentage.
*
* @since 1.0.13
*/
@Override
public void pan(double percent) {
Range range = getRange();
double lower = range.getLowerBound();
double upper = range.getUpperBound();
double log1 = calculateLog(lower);
double log2 = calculateLog(upper);
double length = log2 - log1;
double adj = length * percent;
log1 = log1 + adj;
log2 = log2 + adj;
setRange(calculateValue(log1), calculateValue(log2));
}
/**
* Creates a tick label for the specified value. Note that this method
* was 'private' prior to version 1.0.10.
*
* @param value the value.
*
* @return The label.
*
* @since 1.0.10
*/
protected String createTickLabel(double value) {
if (this.numberFormatOverride != null) {
return this.numberFormatOverride.format(value);
}
else {
return this.tickUnit.valueToString(value);
}
}
/**
* Tests this axis 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 LogAxis)) {
return false;
}
LogAxis that = (LogAxis) obj;
if (this.base != that.base) {
return false;
}
if (this.smallestValue != that.smallestValue) {
return false;
}
return super.equals(obj);
}
/**
* Returns a hash code for this instance.
*
* @return A hash code.
*/
@Override
public int hashCode() {
int result = 193;
long temp = Double.doubleToLongBits(this.base);
result = 37 * result + (int) (temp ^ (temp >>> 32));
temp = Double.doubleToLongBits(this.smallestValue);
result = 37 * result + (int) (temp ^ (temp >>> 32));
if (this.numberFormatOverride != null) {
result = 37 * result + this.numberFormatOverride.hashCode();
}
result = 37 * result + this.tickUnit.hashCode();
return result;
}
/**
* Returns a collection of tick units for log (base 10) values.
* Uses a given Locale to create the DecimalFormats.
*
* @param locale the locale to use to represent Numbers.
*
* @return A collection of tick units for integer values.
*
* @since 1.0.7
*/
public static TickUnitSource createLogTickUnits(Locale locale) {
TickUnits units = new TickUnits();
NumberFormat numberFormat = new LogFormat();
units.add(new NumberTickUnit(0.05, numberFormat, 2));
units.add(new NumberTickUnit(0.1, numberFormat, 10));
units.add(new NumberTickUnit(0.2, numberFormat, 2));
units.add(new NumberTickUnit(0.5, numberFormat, 5));
units.add(new NumberTickUnit(1, numberFormat, 10));
units.add(new NumberTickUnit(2, numberFormat, 10));
units.add(new NumberTickUnit(3, numberFormat, 15));
units.add(new NumberTickUnit(4, numberFormat, 20));
units.add(new NumberTickUnit(5, numberFormat, 25));
units.add(new NumberTickUnit(6, numberFormat));
units.add(new NumberTickUnit(7, numberFormat));
units.add(new NumberTickUnit(8, numberFormat));
units.add(new NumberTickUnit(9, numberFormat));
units.add(new NumberTickUnit(10, numberFormat));
return units;
}
}
| 32,242 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
CyclicNumberAxis.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/axis/CyclicNumberAxis.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.]
*
* ---------------------
* CyclicNumberAxis.java
* ---------------------
* (C) Copyright 2003-2013, by Nicolas Brodu and Contributors.
*
* Original Author: Nicolas Brodu;
* Contributor(s): David Gilbert (for Object Refinery Limited);
*
* Changes
* -------
* 19-Nov-2003 : Initial import to JFreeChart from the JSynoptic project (NB);
* 16-Mar-2004 : Added plotState to draw() method (DG);
* 07-Apr-2004 : Modifed text bounds calculation (DG);
* 21-Apr-2005 : Replaced Insets with RectangleInsets, removed redundant
* argument in selectAutoTickUnit() (DG);
* 22-Apr-2005 : Renamed refreshHorizontalTicks() --> refreshTicksHorizontal
* (for consistency with other classes) and removed unused
* parameters (DG);
* 08-Jun-2005 : Fixed equals() method to handle GradientPaint (DG);
* 19-May-2009 : Fixed FindBugs warnings, patch by Michal Wozniak (DG);
* 17-Jun-2012 : Removed JCommon dependencies (DG);
*
*/
package org.jfree.chart.axis;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.Stroke;
import java.awt.geom.Line2D;
import java.awt.geom.Rectangle2D;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.text.NumberFormat;
import java.util.List;
import org.jfree.chart.ui.RectangleEdge;
import org.jfree.chart.ui.TextAnchor;
import org.jfree.chart.util.ObjectUtilities;
import org.jfree.chart.util.PaintUtilities;
import org.jfree.chart.plot.Plot;
import org.jfree.chart.plot.PlotRenderingInfo;
import org.jfree.chart.text.TextUtilities;
import org.jfree.chart.util.ParamChecks;
import org.jfree.chart.util.SerialUtilities;
import org.jfree.data.Range;
/**
This class extends NumberAxis and handles cycling.
Traditional representation of data in the range x0..x1
<pre>
|-------------------------|
x0 x1
</pre>
Here, the range bounds are at the axis extremities.
With cyclic axis, however, the time is split in
"cycles", or "time frames", or the same duration : the period.
A cycle axis cannot by definition handle a larger interval
than the period : <pre>x1 - x0 >= period</pre>. Thus, at most a full
period can be represented with such an axis.
The cycle bound is the number between x0 and x1 which marks
the beginning of new time frame:
<pre>
|---------------------|----------------------------|
x0 cb x1
<---previous cycle---><-------current cycle-------->
</pre>
It is actually a multiple of the period, plus optionally
a start offset: <pre>cb = n * period + offset</pre>
Thus, by definition, two consecutive cycle bounds
period apart, which is precisely why it is called a
period.
The visual representation of a cyclic axis is like that:
<pre>
|----------------------------|---------------------|
cb x1|x0 cb
<-------current cycle--------><---previous cycle--->
</pre>
The cycle bound is at the axis ends, then current
cycle is shown, then the last cycle. When using
dynamic data, the visual effect is the current cycle
erases the last cycle as x grows. Then, the next cycle
bound is reached, and the process starts over, erasing
the previous cycle.
A Cyclic item renderer is provided to do exactly this.
*/
public final class CyclicNumberAxis extends NumberAxis {
/** For serialization. */
static final long serialVersionUID = -7514160997164582554L;
/** The default axis line stroke. */
public static Stroke DEFAULT_ADVANCE_LINE_STROKE = new BasicStroke(1.0f);
/** The default axis line paint. */
public static final Paint DEFAULT_ADVANCE_LINE_PAINT = Color.GRAY;
/** The offset. */
protected double offset;
/** The period.*/
protected double period;
/** ??. */
protected boolean boundMappedToLastCycle;
/** A flag that controls whether or not the advance line is visible. */
protected boolean advanceLineVisible;
/** The advance line stroke. */
protected transient Stroke advanceLineStroke = DEFAULT_ADVANCE_LINE_STROKE;
/** The advance line paint. */
protected transient Paint advanceLinePaint;
private transient boolean internalMarkerWhenTicksOverlap;
private transient Tick internalMarkerCycleBoundTick;
/**
* Creates a CycleNumberAxis with the given period.
*
* @param period the period.
*/
public CyclicNumberAxis(double period) {
this(period, 0.0);
}
/**
* Creates a CycleNumberAxis with the given period and offset.
*
* @param period the period.
* @param offset the offset.
*/
public CyclicNumberAxis(double period, double offset) {
this(null, period, offset);
}
/**
* Creates a named CycleNumberAxis with the given period.
*
* @param label the label.
* @param period the period.
*/
public CyclicNumberAxis(String label, double period) {
this(label, 0, period);
}
/**
* Creates a named CycleNumberAxis with the given period and offset.
*
* @param label the label.
* @param period the period.
* @param offset the offset.
*/
public CyclicNumberAxis(String label, double period, double offset) {
super(label);
this.period = period;
this.offset = offset;
setFixedAutoRange(period);
this.advanceLineVisible = true;
this.advanceLinePaint = DEFAULT_ADVANCE_LINE_PAINT;
}
/**
* The advance line is the line drawn at the limit of the current cycle,
* when erasing the previous cycle.
*
* @return A boolean.
*/
public boolean isAdvanceLineVisible() {
return this.advanceLineVisible;
}
/**
* The advance line is the line drawn at the limit of the current cycle,
* when erasing the previous cycle.
*
* @param visible the flag.
*/
public void setAdvanceLineVisible(boolean visible) {
this.advanceLineVisible = visible;
}
/**
* The advance line is the line drawn at the limit of the current cycle,
* when erasing the previous cycle.
*
* @return The paint (never <code>null</code>).
*/
public Paint getAdvanceLinePaint() {
return this.advanceLinePaint;
}
/**
* The advance line is the line drawn at the limit of the current cycle,
* when erasing the previous cycle.
*
* @param paint the paint (<code>null</code> not permitted).
*/
public void setAdvanceLinePaint(Paint paint) {
ParamChecks.nullNotPermitted(paint, "paint");
this.advanceLinePaint = paint;
}
/**
* The advance line is the line drawn at the limit of the current cycle,
* when erasing the previous cycle.
*
* @return The stroke (never <code>null</code>).
*/
public Stroke getAdvanceLineStroke() {
return this.advanceLineStroke;
}
/**
* The advance line is the line drawn at the limit of the current cycle,
* when erasing the previous cycle.
*
* @param stroke the stroke (<code>null</code> not permitted).
*/
public void setAdvanceLineStroke(Stroke stroke) {
ParamChecks.nullNotPermitted(stroke, "stroke");
this.advanceLineStroke = stroke;
}
/**
* The cycle bound can be associated either with the current or with the
* last cycle. It's up to the user's choice to decide which, as this is
* just a convention. By default, the cycle bound is mapped to the current
* cycle.
* <br>
* Note that this has no effect on visual appearance, as the cycle bound is
* mapped successively for both axis ends. Use this function for correct
* results in translateValueToJava2D.
*
* @return <code>true</code> if the cycle bound is mapped to the last
* cycle, <code>false</code> if it is bound to the current cycle
* (default)
*/
public boolean isBoundMappedToLastCycle() {
return this.boundMappedToLastCycle;
}
/**
* The cycle bound can be associated either with the current or with the
* last cycle. It's up to the user's choice to decide which, as this is
* just a convention. By default, the cycle bound is mapped to the current
* cycle.
* <br>
* Note that this has no effect on visual appearance, as the cycle bound is
* mapped successively for both axis ends. Use this function for correct
* results in valueToJava2D.
*
* @param boundMappedToLastCycle Set it to true to map the cycle bound to
* the last cycle.
*/
public void setBoundMappedToLastCycle(boolean boundMappedToLastCycle) {
this.boundMappedToLastCycle = boundMappedToLastCycle;
}
/**
* Selects a tick unit when the axis is displayed horizontally.
*
* @param g2 the graphics device.
* @param drawArea the drawing area.
* @param dataArea the data area.
* @param edge the side of the rectangle on which the axis is displayed.
*/
protected void selectHorizontalAutoTickUnit(Graphics2D g2,
Rectangle2D drawArea, Rectangle2D dataArea, RectangleEdge edge) {
double tickLabelWidth
= estimateMaximumTickLabelWidth(g2, getTickUnit());
// Compute number of labels
double n = getRange().getLength()
* tickLabelWidth / dataArea.getWidth();
setTickUnit((NumberTickUnit) getStandardTickUnits()
.getCeilingTickUnit(n), false, false);
}
/**
* Selects a tick unit when the axis is displayed vertically.
*
* @param g2 the graphics device.
* @param drawArea the drawing area.
* @param dataArea the data area.
* @param edge the side of the rectangle on which the axis is displayed.
*/
protected void selectVerticalAutoTickUnit(Graphics2D g2,
Rectangle2D drawArea, Rectangle2D dataArea, RectangleEdge edge) {
double tickLabelWidth
= estimateMaximumTickLabelWidth(g2, getTickUnit());
// Compute number of labels
double n = getRange().getLength()
* tickLabelWidth / dataArea.getHeight();
setTickUnit((NumberTickUnit) getStandardTickUnits()
.getCeilingTickUnit(n), false, false);
}
/**
* A special Number tick that also hold information about the cycle bound
* mapping for this tick. This is especially useful for having a tick at
* each axis end with the cycle bound value. See also
* isBoundMappedToLastCycle()
*/
protected static class CycleBoundTick extends NumberTick {
/** Map to last cycle. */
public boolean mapToLastCycle;
/**
* Creates a new tick.
*
* @param mapToLastCycle map to last cycle?
* @param number the number.
* @param label the label.
* @param textAnchor the text anchor.
* @param rotationAnchor the rotation anchor.
* @param angle the rotation angle.
*/
public CycleBoundTick(boolean mapToLastCycle, Number number,
String label, TextAnchor textAnchor,
TextAnchor rotationAnchor, double angle) {
super(number, label, textAnchor, rotationAnchor, angle);
this.mapToLastCycle = mapToLastCycle;
}
}
/**
* Calculates the anchor point for a tick.
*
* @param tick the tick.
* @param cursor the cursor.
* @param dataArea the data area.
* @param edge the side on which the axis is displayed.
*
* @return The anchor point.
*/
@Override
protected float[] calculateAnchorPoint(ValueTick tick, double cursor,
Rectangle2D dataArea, RectangleEdge edge) {
if (tick instanceof CycleBoundTick) {
boolean mapsav = this.boundMappedToLastCycle;
this.boundMappedToLastCycle
= ((CycleBoundTick) tick).mapToLastCycle;
float[] ret = super.calculateAnchorPoint(
tick, cursor, dataArea, edge
);
this.boundMappedToLastCycle = mapsav;
return ret;
}
return super.calculateAnchorPoint(tick, cursor, dataArea, edge);
}
/**
* Builds a list of ticks for the axis. This method is called when the
* axis is at the top or bottom of the chart (so the axis is "horizontal").
*
* @param g2 the graphics device.
* @param dataArea the data area.
* @param edge the edge.
*
* @return A list of ticks.
*/
@Override
protected List<ValueTick> refreshTicksHorizontal(Graphics2D g2,
Rectangle2D dataArea, RectangleEdge edge) {
List<ValueTick> result = new java.util.ArrayList<ValueTick>();
Font tickLabelFont = getTickLabelFont();
g2.setFont(tickLabelFont);
if (isAutoTickUnitSelection()) {
selectAutoTickUnit(g2, dataArea, edge);
}
double unit = getTickUnit().getSize();
double cycleBound = getCycleBound();
double currentTickValue = Math.ceil(cycleBound / unit) * unit;
double upperValue = getRange().getUpperBound();
boolean cycled = false;
boolean boundMapping = this.boundMappedToLastCycle;
this.boundMappedToLastCycle = false;
CycleBoundTick lastTick = null;
float lastX = 0.0f;
if (upperValue == cycleBound) {
currentTickValue = calculateLowestVisibleTickValue();
cycled = true;
this.boundMappedToLastCycle = true;
}
while (currentTickValue <= upperValue) {
// Cycle when necessary
boolean cyclenow = false;
if ((currentTickValue + unit > upperValue) && !cycled) {
cyclenow = true;
}
double xx = valueToJava2D(currentTickValue, dataArea, edge);
String tickLabel;
NumberFormat formatter = getNumberFormatOverride();
if (formatter != null) {
tickLabel = formatter.format(currentTickValue);
}
else {
tickLabel = getTickUnit().valueToString(currentTickValue);
}
float x = (float) xx;
TextAnchor anchor;
TextAnchor rotationAnchor;
double angle = 0.0;
if (isVerticalTickLabels()) {
if (edge == RectangleEdge.TOP) {
angle = Math.PI / 2.0;
}
else {
angle = -Math.PI / 2.0;
}
anchor = TextAnchor.CENTER_RIGHT;
// If tick overlap when cycling, update last tick too
if ((lastTick != null) && (lastX == x)
&& (currentTickValue != cycleBound)) {
anchor = isInverted()
? TextAnchor.TOP_RIGHT : TextAnchor.BOTTOM_RIGHT;
result.remove(result.size() - 1);
result.add(new CycleBoundTick(
this.boundMappedToLastCycle, lastTick.getNumber(),
lastTick.getText(), anchor, anchor,
lastTick.getAngle())
);
this.internalMarkerWhenTicksOverlap = true;
anchor = isInverted()
? TextAnchor.BOTTOM_RIGHT : TextAnchor.TOP_RIGHT;
}
rotationAnchor = anchor;
}
else {
if (edge == RectangleEdge.TOP) {
anchor = TextAnchor.BOTTOM_CENTER;
if ((lastTick != null) && (lastX == x)
&& (currentTickValue != cycleBound)) {
anchor = isInverted()
? TextAnchor.BOTTOM_LEFT : TextAnchor.BOTTOM_RIGHT;
result.remove(result.size() - 1);
result.add(new CycleBoundTick(
this.boundMappedToLastCycle, lastTick.getNumber(),
lastTick.getText(), anchor, anchor,
lastTick.getAngle())
);
this.internalMarkerWhenTicksOverlap = true;
anchor = isInverted()
? TextAnchor.BOTTOM_RIGHT : TextAnchor.BOTTOM_LEFT;
}
rotationAnchor = anchor;
}
else {
anchor = TextAnchor.TOP_CENTER;
if ((lastTick != null) && (lastX == x)
&& (currentTickValue != cycleBound)) {
anchor = isInverted()
? TextAnchor.TOP_LEFT : TextAnchor.TOP_RIGHT;
result.remove(result.size() - 1);
result.add(new CycleBoundTick(
this.boundMappedToLastCycle, lastTick.getNumber(),
lastTick.getText(), anchor, anchor,
lastTick.getAngle())
);
this.internalMarkerWhenTicksOverlap = true;
anchor = isInverted()
? TextAnchor.TOP_RIGHT : TextAnchor.TOP_LEFT;
}
rotationAnchor = anchor;
}
}
CycleBoundTick tick = new CycleBoundTick(
this.boundMappedToLastCycle, currentTickValue, tickLabel,
anchor, rotationAnchor, angle);
if (currentTickValue == cycleBound) {
this.internalMarkerCycleBoundTick = tick;
}
result.add(tick);
lastTick = tick;
lastX = x;
currentTickValue += unit;
if (cyclenow) {
currentTickValue = calculateLowestVisibleTickValue();
upperValue = cycleBound;
cycled = true;
this.boundMappedToLastCycle = true;
}
}
this.boundMappedToLastCycle = boundMapping;
return result;
}
/**
* Builds a list of ticks for the axis. This method is called when the
* axis is at the left or right of the chart (so the axis is "vertical").
*
* @param g2 the graphics device.
* @param dataArea the data area.
* @param edge the edge.
*
* @return A list of ticks.
*/
protected List<ValueTick> refreshVerticalTicks(Graphics2D g2,
Rectangle2D dataArea, RectangleEdge edge) {
List<ValueTick> result = new java.util.ArrayList<ValueTick>();
result.clear();
Font tickLabelFont = getTickLabelFont();
g2.setFont(tickLabelFont);
if (isAutoTickUnitSelection()) {
selectAutoTickUnit(g2, dataArea, edge);
}
double unit = getTickUnit().getSize();
double cycleBound = getCycleBound();
double currentTickValue = Math.ceil(cycleBound / unit) * unit;
double upperValue = getRange().getUpperBound();
boolean cycled = false;
boolean boundMapping = this.boundMappedToLastCycle;
this.boundMappedToLastCycle = true;
NumberTick lastTick = null;
float lastY = 0.0f;
if (upperValue == cycleBound) {
currentTickValue = calculateLowestVisibleTickValue();
cycled = true;
this.boundMappedToLastCycle = true;
}
while (currentTickValue <= upperValue) {
// Cycle when necessary
boolean cyclenow = false;
if ((currentTickValue + unit > upperValue) && !cycled) {
cyclenow = true;
}
double yy = valueToJava2D(currentTickValue, dataArea, edge);
String tickLabel;
NumberFormat formatter = getNumberFormatOverride();
if (formatter != null) {
tickLabel = formatter.format(currentTickValue);
}
else {
tickLabel = getTickUnit().valueToString(currentTickValue);
}
float y = (float) yy;
TextAnchor anchor;
TextAnchor rotationAnchor;
double angle = 0.0;
if (isVerticalTickLabels()) {
if (edge == RectangleEdge.LEFT) {
anchor = TextAnchor.BOTTOM_CENTER;
if ((lastTick != null) && (lastY == y)
&& (currentTickValue != cycleBound)) {
anchor = isInverted()
? TextAnchor.BOTTOM_LEFT : TextAnchor.BOTTOM_RIGHT;
result.remove(result.size() - 1);
result.add(new CycleBoundTick(
this.boundMappedToLastCycle, lastTick.getNumber(),
lastTick.getText(), anchor, anchor,
lastTick.getAngle())
);
this.internalMarkerWhenTicksOverlap = true;
anchor = isInverted()
? TextAnchor.BOTTOM_RIGHT : TextAnchor.BOTTOM_LEFT;
}
rotationAnchor = anchor;
angle = -Math.PI / 2.0;
}
else {
anchor = TextAnchor.BOTTOM_CENTER;
if ((lastTick != null) && (lastY == y)
&& (currentTickValue != cycleBound)) {
anchor = isInverted()
? TextAnchor.BOTTOM_RIGHT : TextAnchor.BOTTOM_LEFT;
result.remove(result.size() - 1);
result.add(new CycleBoundTick(
this.boundMappedToLastCycle, lastTick.getNumber(),
lastTick.getText(), anchor, anchor,
lastTick.getAngle())
);
this.internalMarkerWhenTicksOverlap = true;
anchor = isInverted()
? TextAnchor.BOTTOM_LEFT : TextAnchor.BOTTOM_RIGHT;
}
rotationAnchor = anchor;
angle = Math.PI / 2.0;
}
}
else {
if (edge == RectangleEdge.LEFT) {
anchor = TextAnchor.CENTER_RIGHT;
if ((lastTick != null) && (lastY == y)
&& (currentTickValue != cycleBound)) {
anchor = isInverted()
? TextAnchor.BOTTOM_RIGHT : TextAnchor.TOP_RIGHT;
result.remove(result.size() - 1);
result.add(new CycleBoundTick(
this.boundMappedToLastCycle, lastTick.getNumber(),
lastTick.getText(), anchor, anchor,
lastTick.getAngle())
);
this.internalMarkerWhenTicksOverlap = true;
anchor = isInverted()
? TextAnchor.TOP_RIGHT : TextAnchor.BOTTOM_RIGHT;
}
rotationAnchor = anchor;
}
else {
anchor = TextAnchor.CENTER_LEFT;
if ((lastTick != null) && (lastY == y)
&& (currentTickValue != cycleBound)) {
anchor = isInverted()
? TextAnchor.BOTTOM_LEFT : TextAnchor.TOP_LEFT;
result.remove(result.size() - 1);
result.add(new CycleBoundTick(
this.boundMappedToLastCycle, lastTick.getNumber(),
lastTick.getText(), anchor, anchor,
lastTick.getAngle())
);
this.internalMarkerWhenTicksOverlap = true;
anchor = isInverted()
? TextAnchor.TOP_LEFT : TextAnchor.BOTTOM_LEFT;
}
rotationAnchor = anchor;
}
}
CycleBoundTick tick = new CycleBoundTick(
this.boundMappedToLastCycle, currentTickValue, tickLabel,
anchor, rotationAnchor, angle);
if (currentTickValue == cycleBound) {
this.internalMarkerCycleBoundTick = tick;
}
result.add(tick);
lastTick = tick;
lastY = y;
if (currentTickValue == cycleBound) {
this.internalMarkerCycleBoundTick = tick;
}
currentTickValue += unit;
if (cyclenow) {
currentTickValue = calculateLowestVisibleTickValue();
upperValue = cycleBound;
cycled = true;
this.boundMappedToLastCycle = false;
}
}
this.boundMappedToLastCycle = boundMapping;
return result;
}
/**
* Converts a coordinate from Java 2D space to data space.
*
* @param java2DValue the coordinate in Java2D space.
* @param dataArea the data area.
* @param edge the edge.
*
* @return The data value.
*/
@Override
public double java2DToValue(double java2DValue, Rectangle2D dataArea,
RectangleEdge edge) {
Range range = getRange();
double vmax = range.getUpperBound();
double vp = getCycleBound();
double jmin = 0.0;
double jmax = 0.0;
if (RectangleEdge.isTopOrBottom(edge)) {
jmin = dataArea.getMinX();
jmax = dataArea.getMaxX();
}
else if (RectangleEdge.isLeftOrRight(edge)) {
jmin = dataArea.getMaxY();
jmax = dataArea.getMinY();
}
if (isInverted()) {
double jbreak = jmax - (vmax - vp) * (jmax - jmin) / this.period;
if (java2DValue >= jbreak) {
return vp + (jmax - java2DValue) * this.period / (jmax - jmin);
}
else {
return vp - (java2DValue - jmin) * this.period / (jmax - jmin);
}
}
else {
double jbreak = (vmax - vp) * (jmax - jmin) / this.period + jmin;
if (java2DValue <= jbreak) {
return vp + (java2DValue - jmin) * this.period / (jmax - jmin);
}
else {
return vp - (jmax - java2DValue) * this.period / (jmax - jmin);
}
}
}
/**
* Translates a value from data space to Java 2D space.
*
* @param value the data value.
* @param dataArea the data area.
* @param edge the edge.
*
* @return The Java 2D value.
*/
@Override
public double valueToJava2D(double value, Rectangle2D dataArea,
RectangleEdge edge) {
Range range = getRange();
double vmin = range.getLowerBound();
double vmax = range.getUpperBound();
double vp = getCycleBound();
if ((value < vmin) || (value > vmax)) {
return Double.NaN;
}
double jmin = 0.0;
double jmax = 0.0;
if (RectangleEdge.isTopOrBottom(edge)) {
jmin = dataArea.getMinX();
jmax = dataArea.getMaxX();
}
else if (RectangleEdge.isLeftOrRight(edge)) {
jmax = dataArea.getMinY();
jmin = dataArea.getMaxY();
}
if (isInverted()) {
if (value == vp) {
return this.boundMappedToLastCycle ? jmin : jmax;
}
else if (value > vp) {
return jmax - (value - vp) * (jmax - jmin) / this.period;
}
else {
return jmin + (vp - value) * (jmax - jmin) / this.period;
}
}
else {
if (value == vp) {
return this.boundMappedToLastCycle ? jmax : jmin;
}
else if (value >= vp) {
return jmin + (value - vp) * (jmax - jmin) / this.period;
}
else {
return jmax - (vp - value) * (jmax - jmin) / this.period;
}
}
}
/**
* Centers the range about the given value.
*
* @param value the data value.
*/
@Override
public void centerRange(double value) {
setRange(value - this.period / 2.0, value + this.period / 2.0);
}
/**
* This function is nearly useless since the auto range is fixed for this
* class to the period. The period is extended if necessary to fit the
* minimum size.
*
* @param size the size.
* @param notify notify?
*
* @see org.jfree.chart.axis.ValueAxis#setAutoRangeMinimumSize(double,
* boolean)
*/
@Override
public void setAutoRangeMinimumSize(double size, boolean notify) {
if (size > this.period) {
this.period = size;
}
super.setAutoRangeMinimumSize(size, notify);
}
/**
* The auto range is fixed for this class to the period by default.
* This function will thus set a new period.
*
* @param length the length.
*
* @see org.jfree.chart.axis.ValueAxis#setFixedAutoRange(double)
*/
@Override
public void setFixedAutoRange(double length) {
this.period = length;
super.setFixedAutoRange(length);
}
/**
* Sets a new axis range. The period is extended to fit the range size, if
* necessary.
*
* @param range the range.
* @param turnOffAutoRange switch off the auto range.
* @param notify notify?
*
* @see org.jfree.chart.axis.ValueAxis#setRange(Range, boolean, boolean)
*/
@Override
public void setRange(Range range, boolean turnOffAutoRange,
boolean notify) {
double size = range.getUpperBound() - range.getLowerBound();
if (size > this.period) {
this.period = size;
}
super.setRange(range, turnOffAutoRange, notify);
}
/**
* The cycle bound is defined as the higest value x such that
* "offset + period * i = x", with i and integer and x <
* range.getUpperBound() This is the value which is at both ends of the
* axis : x...up|low...x
* The values from x to up are the valued in the current cycle.
* The values from low to x are the valued in the previous cycle.
*
* @return The cycle bound.
*/
public double getCycleBound() {
return Math.floor(
(getRange().getUpperBound() - this.offset) / this.period)
* this.period + this.offset;
}
/**
* The cycle bound is a multiple of the period, plus optionally a start
* offset.
* <P>
* <pre>cb = n * period + offset</pre><br>
*
* @return The current offset.
*
* @see #getCycleBound()
*/
public double getOffset() {
return this.offset;
}
/**
* The cycle bound is a multiple of the period, plus optionally a start
* offset.
* <P>
* <pre>cb = n * period + offset</pre><br>
*
* @param offset The offset to set.
*
* @see #getCycleBound()
*/
public void setOffset(double offset) {
this.offset = offset;
}
/**
* The cycle bound is a multiple of the period, plus optionally a start
* offset.
* <P>
* <pre>cb = n * period + offset</pre><br>
*
* @return The current period.
*
* @see #getCycleBound()
*/
public double getPeriod() {
return this.period;
}
/**
* The cycle bound is a multiple of the period, plus optionally a start
* offset.
* <P>
* <pre>cb = n * period + offset</pre><br>
*
* @param period The period to set.
*
* @see #getCycleBound()
*/
public void setPeriod(double period) {
this.period = period;
}
/**
* Draws the tick marks and labels.
*
* @param g2 the graphics device.
* @param cursor the cursor.
* @param plotArea the plot area.
* @param dataArea the area inside the axes.
* @param edge the side on which the axis is displayed.
*
* @return The axis state.
*/
@Override
protected AxisState drawTickMarksAndLabels(Graphics2D g2, double cursor,
Rectangle2D plotArea, Rectangle2D dataArea, RectangleEdge edge) {
this.internalMarkerWhenTicksOverlap = false;
AxisState ret = super.drawTickMarksAndLabels(g2, cursor, plotArea,
dataArea, edge);
// continue and separate the labels only if necessary
if (!this.internalMarkerWhenTicksOverlap) {
return ret;
}
double ol;
FontMetrics fm = g2.getFontMetrics(getTickLabelFont());
if (isVerticalTickLabels()) {
ol = fm.getMaxAdvance();
}
else {
ol = fm.getHeight();
}
double il = 0;
if (isTickMarksVisible()) {
float xx = (float) valueToJava2D(getRange().getUpperBound(),
dataArea, edge);
Line2D mark = null;
g2.setStroke(getTickMarkStroke());
g2.setPaint(getTickMarkPaint());
if (edge == RectangleEdge.LEFT) {
mark = new Line2D.Double(cursor - ol, xx, cursor + il, xx);
}
else if (edge == RectangleEdge.RIGHT) {
mark = new Line2D.Double(cursor + ol, xx, cursor - il, xx);
}
else if (edge == RectangleEdge.TOP) {
mark = new Line2D.Double(xx, cursor - ol, xx, cursor + il);
}
else if (edge == RectangleEdge.BOTTOM) {
mark = new Line2D.Double(xx, cursor + ol, xx, cursor - il);
}
g2.draw(mark);
}
return ret;
}
/**
* Draws the axis.
*
* @param g2 the graphics device (<code>null</code> not permitted).
* @param cursor the cursor position.
* @param plotArea the plot area (<code>null</code> not permitted).
* @param dataArea the data area (<code>null</code> not permitted).
* @param edge the edge (<code>null</code> not permitted).
* @param plotState collects information about the plot
* (<code>null</code> permitted).
*
* @return The axis state (never <code>null</code>).
*/
@Override
public AxisState draw(Graphics2D g2, double cursor, Rectangle2D plotArea,
Rectangle2D dataArea, RectangleEdge edge,
PlotRenderingInfo plotState) {
AxisState ret = super.draw(g2, cursor, plotArea, dataArea, edge,
plotState);
if (isAdvanceLineVisible()) {
double xx = valueToJava2D(getRange().getUpperBound(), dataArea,
edge);
Line2D mark = null;
g2.setStroke(getAdvanceLineStroke());
g2.setPaint(getAdvanceLinePaint());
if (edge == RectangleEdge.LEFT) {
mark = new Line2D.Double(cursor, xx,
cursor + dataArea.getWidth(), xx);
}
else if (edge == RectangleEdge.RIGHT) {
mark = new Line2D.Double(cursor - dataArea.getWidth(), xx,
cursor, xx);
}
else if (edge == RectangleEdge.TOP) {
mark = new Line2D.Double(xx, cursor + dataArea.getHeight(),
xx, cursor);
}
else if (edge == RectangleEdge.BOTTOM) {
mark = new Line2D.Double(xx, cursor, xx, cursor
- dataArea.getHeight());
}
g2.draw(mark);
}
return ret;
}
/**
* Reserve some space on each axis side because we draw a centered label at
* each extremity.
*
* @param g2 the graphics device.
* @param plot the plot.
* @param plotArea the plot area.
* @param edge the edge.
* @param space the space already reserved.
*
* @return The reserved space.
*/
@Override
public AxisSpace reserveSpace(Graphics2D g2, Plot plot,
Rectangle2D plotArea, RectangleEdge edge, AxisSpace space) {
this.internalMarkerCycleBoundTick = null;
AxisSpace ret = super.reserveSpace(g2, plot, plotArea, edge, space);
if (this.internalMarkerCycleBoundTick == null) {
return ret;
}
FontMetrics fm = g2.getFontMetrics(getTickLabelFont());
Rectangle2D r = TextUtilities.getTextBounds(
this.internalMarkerCycleBoundTick.getText(), g2, fm);
if (RectangleEdge.isTopOrBottom(edge)) {
if (isVerticalTickLabels()) {
space.add(r.getHeight() / 2, RectangleEdge.RIGHT);
}
else {
space.add(r.getWidth() / 2, RectangleEdge.RIGHT);
}
}
else if (RectangleEdge.isLeftOrRight(edge)) {
if (isVerticalTickLabels()) {
space.add(r.getWidth() / 2, RectangleEdge.TOP);
}
else {
space.add(r.getHeight() / 2, RectangleEdge.TOP);
}
}
return ret;
}
/**
* 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.advanceLinePaint, stream);
SerialUtilities.writeStroke(this.advanceLineStroke, 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.advanceLinePaint = SerialUtilities.readPaint(stream);
this.advanceLineStroke = SerialUtilities.readStroke(stream);
}
/**
* Tests the axis for equality with another object.
*
* @param obj the object to test against.
*
* @return A boolean.
*/
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof CyclicNumberAxis)) {
return false;
}
if (!super.equals(obj)) {
return false;
}
CyclicNumberAxis that = (CyclicNumberAxis) obj;
if (this.period != that.period) {
return false;
}
if (this.offset != that.offset) {
return false;
}
if (!PaintUtilities.equal(this.advanceLinePaint,
that.advanceLinePaint)) {
return false;
}
if (!ObjectUtilities.equal(this.advanceLineStroke,
that.advanceLineStroke)) {
return false;
}
if (this.advanceLineVisible != that.advanceLineVisible) {
return false;
}
if (this.boundMappedToLastCycle != that.boundMappedToLastCycle) {
return false;
}
return true;
}
}
| 41,084 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
CategoryLabelPosition.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/axis/CategoryLabelPosition.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.]
*
* --------------------------
* CategoryLabelPosition.java
* --------------------------
* (C) Copyright 2003-2012, by Object Refinery Limited and Contributors.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 31-Oct-2003 : Version 1 (DG);
* 17-Feb-2004 : Added new constructor (DG);
* 23-Mar-2004 : Added width calculation parameters (DG);
* 07-Jan-2005 : Fixed bug in equals() method (DG);
* 11-Jan-2005 : Removed deprecated constructor in preparation for the 1.0.0
* release (DG);
* 16-Jun-2012 : Removed JCommon dependencies (DG);
*
*/
package org.jfree.chart.axis;
import java.io.Serializable;
import org.jfree.chart.ui.RectangleAnchor;
import org.jfree.chart.ui.TextAnchor;
import org.jfree.chart.text.TextBlockAnchor;
/**
* The attributes that control the position of the labels for the categories on
* a {@link CategoryAxis}. Instances of this class are immutable and other
* JFreeChart classes rely upon this.
*/
public class CategoryLabelPosition implements Serializable {
/** For serialization. */
private static final long serialVersionUID = 5168681143844183864L;
/** The category anchor point. */
private RectangleAnchor categoryAnchor;
/** The text block anchor. */
private TextBlockAnchor labelAnchor;
/** The rotation anchor. */
private TextAnchor rotationAnchor;
/** The rotation angle (in radians). */
private double angle;
/** The width calculation type. */
private CategoryLabelWidthType widthType;
/**
* The maximum label width as a percentage of the category space or the
* range space.
*/
private float widthRatio;
/**
* Creates a new position record with default settings.
*/
public CategoryLabelPosition() {
this(RectangleAnchor.CENTER, TextBlockAnchor.BOTTOM_CENTER,
TextAnchor.CENTER, 0.0, CategoryLabelWidthType.CATEGORY, 0.95f);
}
/**
* Creates a new category label position record.
*
* @param categoryAnchor the category anchor (<code>null</code> not
* permitted).
* @param labelAnchor the label anchor (<code>null</code> not permitted).
*/
public CategoryLabelPosition(RectangleAnchor categoryAnchor,
TextBlockAnchor labelAnchor) {
// argument checking delegated...
this(categoryAnchor, labelAnchor, TextAnchor.CENTER, 0.0,
CategoryLabelWidthType.CATEGORY, 0.95f);
}
/**
* Creates a new category label position record.
*
* @param categoryAnchor the category anchor (<code>null</code> not
* permitted).
* @param labelAnchor the label anchor (<code>null</code> not permitted).
* @param widthType the width type (<code>null</code> not permitted).
* @param widthRatio the maximum label width as a percentage (of the
* category space or the range space).
*/
public CategoryLabelPosition(RectangleAnchor categoryAnchor,
TextBlockAnchor labelAnchor,
CategoryLabelWidthType widthType,
float widthRatio) {
// argument checking delegated...
this(categoryAnchor, labelAnchor, TextAnchor.CENTER, 0.0, widthType,
widthRatio);
}
/**
* Creates a new position record. The item label anchor is a point
* relative to the data item (dot, bar or other visual item) on a chart.
* The item label is aligned by aligning the text anchor with the item
* label anchor.
*
* @param categoryAnchor the category anchor (<code>null</code> not
* permitted).
* @param labelAnchor the label anchor (<code>null</code> not permitted).
* @param rotationAnchor the rotation anchor (<code>null</code> not
* permitted).
* @param angle the rotation angle (<code>null</code> not permitted).
* @param widthType the width type (<code>null</code> not permitted).
* @param widthRatio the maximum label width as a percentage (of the
* category space or the range space).
*/
public CategoryLabelPosition(RectangleAnchor categoryAnchor,
TextBlockAnchor labelAnchor,
TextAnchor rotationAnchor,
double angle,
CategoryLabelWidthType widthType,
float widthRatio) {
if (categoryAnchor == null) {
throw new IllegalArgumentException(
"Null 'categoryAnchor' argument.");
}
if (labelAnchor == null) {
throw new IllegalArgumentException(
"Null 'labelAnchor' argument.");
}
if (rotationAnchor == null) {
throw new IllegalArgumentException(
"Null 'rotationAnchor' argument.");
}
if (widthType == null) {
throw new IllegalArgumentException("Null 'widthType' argument.");
}
this.categoryAnchor = categoryAnchor;
this.labelAnchor = labelAnchor;
this.rotationAnchor = rotationAnchor;
this.angle = angle;
this.widthType = widthType;
this.widthRatio = widthRatio;
}
/**
* Returns the item label anchor.
*
* @return The item label anchor (never <code>null</code>).
*/
public RectangleAnchor getCategoryAnchor() {
return this.categoryAnchor;
}
/**
* Returns the text block anchor.
*
* @return The text block anchor (never <code>null</code>).
*/
public TextBlockAnchor getLabelAnchor() {
return this.labelAnchor;
}
/**
* Returns the rotation anchor point.
*
* @return The rotation anchor point (never <code>null</code>).
*/
public TextAnchor getRotationAnchor() {
return this.rotationAnchor;
}
/**
* Returns the angle of rotation for the label.
*
* @return The angle (in radians).
*/
public double getAngle() {
return this.angle;
}
/**
* Returns the width calculation type.
*
* @return The width calculation type (never <code>null</code>).
*/
public CategoryLabelWidthType getWidthType() {
return this.widthType;
}
/**
* Returns the ratio used to calculate the maximum category label width.
*
* @return The ratio.
*/
public float getWidthRatio() {
return this.widthRatio;
}
/**
* 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 CategoryLabelPosition)) {
return false;
}
CategoryLabelPosition that = (CategoryLabelPosition) obj;
if (!this.categoryAnchor.equals(that.categoryAnchor)) {
return false;
}
if (!this.labelAnchor.equals(that.labelAnchor)) {
return false;
}
if (!this.rotationAnchor.equals(that.rotationAnchor)) {
return false;
}
if (this.angle != that.angle) {
return false;
}
if (this.widthType != that.widthType) {
return false;
}
if (this.widthRatio != that.widthRatio) {
return false;
}
return true;
}
/**
* Returns a hash code for this object.
*
* @return A hash code.
*/
@Override
public int hashCode() {
int result = 19;
result = 37 * result + this.categoryAnchor.hashCode();
result = 37 * result + this.labelAnchor.hashCode();
result = 37 * result + this.rotationAnchor.hashCode();
return result;
}
}
| 9,354 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
Tick.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/axis/Tick.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.]
*
* ---------
* Tick.java
* ---------
* (C) Copyright 2000-2012, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): Nicolas Brodu;
*
* Changes
* -------
* 18-Sep-2001 : Added standard header and fixed DOS encoding problem (DG);
* 26-Sep-2002 : Fixed errors reported by Checkstyle (DG);
* 08-Nov-2002 : Moved to new package com.jrefinery.chart.axis (DG);
* 26-Mar-2003 : Implemented Serializable (DG);
* 12-Sep-2003 : Implemented Cloneable (NB);
* 07-Nov-2003 : Added subclasses for particular types of ticks (DG);
* 16-Jun-2012 : Removed JCommon dependencies (DG);
*
*/
package org.jfree.chart.axis;
import java.io.Serializable;
import org.jfree.chart.ui.TextAnchor;
import org.jfree.chart.util.ObjectUtilities;
/**
* The base class used to represent labelled ticks along an axis.
*/
public abstract class Tick implements Serializable, Cloneable {
/** For serialization. */
private static final long serialVersionUID = 6668230383875149773L;
/** A text version of the tick value. */
private String text;
/** The text anchor for the tick label. */
private TextAnchor textAnchor;
/** The rotation anchor for the tick label. */
private TextAnchor rotationAnchor;
/** The rotation angle. */
private double angle;
/**
* Creates a new tick.
*
* @param text the formatted version of the tick value.
* @param textAnchor the text anchor (<code>null</code> not permitted).
* @param rotationAnchor the rotation anchor (<code>null</code> not
* permitted).
* @param angle the angle.
*/
public Tick(String text, TextAnchor textAnchor, TextAnchor rotationAnchor,
double angle) {
if (textAnchor == null) {
throw new IllegalArgumentException("Null 'textAnchor' argument.");
}
if (rotationAnchor == null) {
throw new IllegalArgumentException(
"Null 'rotationAnchor' argument."
);
}
this.text = text;
this.textAnchor = textAnchor;
this.rotationAnchor = rotationAnchor;
this.angle = angle;
}
/**
* Returns the text version of the tick value.
*
* @return A string (possibly <code>null</code>;
*/
public String getText() {
return this.text;
}
/**
* Returns the text anchor.
*
* @return The text anchor (never <code>null</code>).
*/
public TextAnchor getTextAnchor() {
return this.textAnchor;
}
/**
* Returns the text anchor that defines the point around which the label is
* rotated.
*
* @return A text anchor (never <code>null</code>).
*/
public TextAnchor getRotationAnchor() {
return this.rotationAnchor;
}
/**
* Returns the angle.
*
* @return The angle.
*/
public double getAngle() {
return this.angle;
}
/**
* Tests this tick 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 Tick) {
Tick t = (Tick) obj;
if (!ObjectUtilities.equal(this.text, t.text)) {
return false;
}
if (!ObjectUtilities.equal(this.textAnchor, t.textAnchor)) {
return false;
}
if (!ObjectUtilities.equal(this.rotationAnchor, t.rotationAnchor)) {
return false;
}
if (!(this.angle == t.angle)) {
return false;
}
return true;
}
return false;
}
/**
* Returns a clone of the tick.
*
* @return A clone.
*
* @throws CloneNotSupportedException if there is a problem cloning.
*/
@Override
public Object clone() throws CloneNotSupportedException {
Tick clone = (Tick) super.clone();
return clone;
}
/**
* Returns a string representation of the tick.
*
* @return A string.
*/
@Override
public String toString() {
return this.text;
}
}
| 5,575 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
ModuloAxis.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/axis/ModuloAxis.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.]
*
* ---------------
* ModuloAxis.java
* ---------------
* (C) Copyright 2004-2012, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 13-Aug-2004 : Version 1 (DG);
* 13-Nov-2007 : Implemented equals() (DG);
* 17-Jun-2012 : Removed JCommon dependencies (DG);
*
*/
package org.jfree.chart.axis;
import java.awt.geom.Rectangle2D;
import org.jfree.chart.ui.RectangleEdge;
import org.jfree.chart.event.AxisChangeEvent;
import org.jfree.data.Range;
/**
* An axis that displays numerical values within a fixed range using a modulo
* calculation.
*/
public class ModuloAxis extends NumberAxis {
/**
* The fixed range for the axis - all data values will be mapped to this
* range using a modulo calculation.
*/
private Range fixedRange;
/**
* The display start value (this will sometimes be > displayEnd, in which
* case the axis wraps around at some point in the middle of the axis).
*/
private double displayStart;
/**
* The display end value.
*/
private double displayEnd;
/**
* Creates a new axis.
*
* @param label the axis label (<code>null</code> permitted).
* @param fixedRange the fixed range (<code>null</code> not permitted).
*/
public ModuloAxis(String label, Range fixedRange) {
super(label);
this.fixedRange = fixedRange;
this.displayStart = 270.0;
this.displayEnd = 90.0;
}
/**
* Returns the display start value.
*
* @return The display start value.
*/
public double getDisplayStart() {
return this.displayStart;
}
/**
* Returns the display end value.
*
* @return The display end value.
*/
public double getDisplayEnd() {
return this.displayEnd;
}
/**
* Sets the display range. The values will be mapped to the fixed range if
* necessary.
*
* @param start the start value.
* @param end the end value.
*/
public void setDisplayRange(double start, double end) {
this.displayStart = mapValueToFixedRange(start);
this.displayEnd = mapValueToFixedRange(end);
if (this.displayStart < this.displayEnd) {
setRange(this.displayStart, this.displayEnd);
}
else {
setRange(this.displayStart, this.fixedRange.getUpperBound()
+ (this.displayEnd - this.fixedRange.getLowerBound()));
}
notifyListeners(new AxisChangeEvent(this));
}
/**
* This method should calculate a range that will show all the data values.
* For now, it just sets the axis range to the fixedRange.
*/
@Override
protected void autoAdjustRange() {
setRange(this.fixedRange, false, false);
}
/**
* Translates a data value to a Java2D coordinate.
*
* @param value the value.
* @param area the area.
* @param edge the edge.
*
* @return A Java2D coordinate.
*/
@Override
public double valueToJava2D(double value, Rectangle2D area,
RectangleEdge edge) {
double result = 0.0;
double v = mapValueToFixedRange(value);
if (this.displayStart < this.displayEnd) { // regular number axis
result = trans(v, area, edge);
}
else { // displayStart > displayEnd, need to handle split
double cutoff = (this.displayStart + this.displayEnd) / 2.0;
double length1 = this.fixedRange.getUpperBound()
- this.displayStart;
double length2 = this.displayEnd - this.fixedRange.getLowerBound();
if (v > cutoff) {
result = transStart(v, area, edge, length1, length2);
}
else {
result = transEnd(v, area, edge, length1, length2);
}
}
return result;
}
/**
* A regular translation from a data value to a Java2D value.
*
* @param value the value.
* @param area the data area.
* @param edge the edge along which the axis lies.
*
* @return The Java2D coordinate.
*/
private double trans(double value, Rectangle2D area, RectangleEdge edge) {
double min = 0.0;
double max = 0.0;
if (RectangleEdge.isTopOrBottom(edge)) {
min = area.getX();
max = area.getX() + area.getWidth();
}
else if (RectangleEdge.isLeftOrRight(edge)) {
min = area.getMaxY();
max = area.getMaxY() - area.getHeight();
}
if (isInverted()) {
return max - ((value - this.displayStart)
/ (this.displayEnd - this.displayStart)) * (max - min);
}
else {
return min + ((value - this.displayStart)
/ (this.displayEnd - this.displayStart)) * (max - min);
}
}
/**
* Translates a data value to a Java2D value for the first section of the
* axis.
*
* @param value the value.
* @param area the data area.
* @param edge the edge along which the axis lies.
* @param length1 the length of the first section.
* @param length2 the length of the second section.
*
* @return The Java2D coordinate.
*/
private double transStart(double value, Rectangle2D area,
RectangleEdge edge,
double length1, double length2) {
double min = 0.0;
double max = 0.0;
if (RectangleEdge.isTopOrBottom(edge)) {
min = area.getX();
max = area.getX() + area.getWidth() * length1 / (length1 + length2);
}
else if (RectangleEdge.isLeftOrRight(edge)) {
min = area.getMaxY();
max = area.getMaxY() - area.getHeight() * length1
/ (length1 + length2);
}
if (isInverted()) {
return max - ((value - this.displayStart)
/ (this.fixedRange.getUpperBound() - this.displayStart))
* (max - min);
}
else {
return min + ((value - this.displayStart)
/ (this.fixedRange.getUpperBound() - this.displayStart))
* (max - min);
}
}
/**
* Translates a data value to a Java2D value for the second section of the
* axis.
*
* @param value the value.
* @param area the data area.
* @param edge the edge along which the axis lies.
* @param length1 the length of the first section.
* @param length2 the length of the second section.
*
* @return The Java2D coordinate.
*/
private double transEnd(double value, Rectangle2D area, RectangleEdge edge,
double length1, double length2) {
double min = 0.0;
double max = 0.0;
if (RectangleEdge.isTopOrBottom(edge)) {
max = area.getMaxX();
min = area.getMaxX() - area.getWidth() * length2
/ (length1 + length2);
}
else if (RectangleEdge.isLeftOrRight(edge)) {
max = area.getMinY();
min = area.getMinY() + area.getHeight() * length2
/ (length1 + length2);
}
if (isInverted()) {
return max - ((value - this.fixedRange.getLowerBound())
/ (this.displayEnd - this.fixedRange.getLowerBound()))
* (max - min);
}
else {
return min + ((value - this.fixedRange.getLowerBound())
/ (this.displayEnd - this.fixedRange.getLowerBound()))
* (max - min);
}
}
/**
* Maps a data value into the fixed range.
*
* @param value the value.
*
* @return The mapped value.
*/
private double mapValueToFixedRange(double value) {
double lower = this.fixedRange.getLowerBound();
double length = this.fixedRange.getLength();
if (value < lower) {
return lower + length + ((value - lower) % length);
}
else {
return lower + ((value - lower) % length);
}
}
/**
* Translates a Java2D coordinate into a data value.
*
* @param java2DValue the Java2D coordinate.
* @param area the area.
* @param edge the edge.
*
* @return The Java2D coordinate.
*/
@Override
public double java2DToValue(double java2DValue, Rectangle2D area,
RectangleEdge edge) {
double result = 0.0;
if (this.displayStart < this.displayEnd) { // regular number axis
result = super.java2DToValue(java2DValue, area, edge);
}
else { // displayStart > displayEnd, need to handle split
}
return result;
}
/**
* Returns the display length for the axis.
*
* @return The display length.
*/
private double getDisplayLength() {
if (this.displayStart < this.displayEnd) {
return (this.displayEnd - this.displayStart);
}
else {
return (this.fixedRange.getUpperBound() - this.displayStart)
+ (this.displayEnd - this.fixedRange.getLowerBound());
}
}
/**
* Returns the central value of the current display range.
*
* @return The central value.
*/
private double getDisplayCentralValue() {
return mapValueToFixedRange(
this.displayStart + (getDisplayLength() / 2)
);
}
/**
* Increases or decreases the axis range by the specified percentage about
* the central value and sends an {@link AxisChangeEvent} to all registered
* listeners.
* <P>
* To double the length of the axis range, use 200% (2.0).
* To halve the length of the axis range, use 50% (0.5).
*
* @param percent the resize factor.
*/
@Override
public void resizeRange(double percent) {
resizeRange(percent, getDisplayCentralValue());
}
/**
* Increases or decreases the axis range by the specified percentage about
* the specified anchor value and sends an {@link AxisChangeEvent} to all
* registered listeners.
* <P>
* To double the length of the axis range, use 200% (2.0).
* To halve the length of the axis range, use 50% (0.5).
*
* @param percent the resize factor.
* @param anchorValue the new central value after the resize.
*/
@Override
public void resizeRange(double percent, double anchorValue) {
if (percent > 0.0) {
double halfLength = getDisplayLength() * percent / 2;
setDisplayRange(anchorValue - halfLength, anchorValue + halfLength);
}
else {
setAutoRange(true);
}
}
/**
* Converts a length in data coordinates into the corresponding length in
* Java2D coordinates.
*
* @param length the length.
* @param area the plot area.
* @param edge the edge along which the axis lies.
*
* @return The length in Java2D coordinates.
*/
@Override
public double lengthToJava2D(double length, Rectangle2D area,
RectangleEdge edge) {
double axisLength = 0.0;
if (this.displayEnd > this.displayStart) {
axisLength = this.displayEnd - this.displayStart;
}
else {
axisLength = (this.fixedRange.getUpperBound() - this.displayStart)
+ (this.displayEnd - this.fixedRange.getLowerBound());
}
double areaLength = 0.0;
if (RectangleEdge.isLeftOrRight(edge)) {
areaLength = area.getHeight();
}
else {
areaLength = area.getWidth();
}
return (length / axisLength) * areaLength;
}
/**
* Tests this axis 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 ModuloAxis)) {
return false;
}
ModuloAxis that = (ModuloAxis) obj;
if (this.displayStart != that.displayStart) {
return false;
}
if (this.displayEnd != that.displayEnd) {
return false;
}
if (!this.fixedRange.equals(that.fixedRange)) {
return false;
}
return super.equals(obj);
}
}
| 13,955 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
MarkerAxisBand.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/axis/MarkerAxisBand.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.]
*
* -------------------
* MarkerAxisBand.java
* -------------------
* (C) Copyright 2000-2012, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 03-Sep-2002 : Updated Javadoc comments (DG);
* 01-Oct-2002 : Fixed errors reported by Checkstyle (DG);
* 08-Nov-2002 : Moved to new package com.jrefinery.chart.axis (DG);
* 26-Mar-2003 : Implemented Serializable (DG);
* 13-May-2003 : Renamed HorizontalMarkerAxisBand --> MarkerAxisBand (DG);
* 29-Oct-2003 : Added workaround for font alignment in PDF output (DG);
* 21-Jan-2004 : Update for renamed method in ValueAxis (DG);
* 07-Apr-2004 : Changed text bounds calculation (DG);
* 17-Jun-2012 : Removed JCommon dependencies (DG);
*
*/
package org.jfree.chart.axis;
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Composite;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.font.LineMetrics;
import java.awt.geom.Rectangle2D;
import java.io.Serializable;
import java.util.List;
import org.jfree.chart.ui.RectangleEdge;
import org.jfree.chart.util.ObjectUtilities;
import org.jfree.chart.plot.IntervalMarker;
import org.jfree.chart.text.TextUtilities;
/**
* A band that can be added to a number axis to display regions.
*/
public class MarkerAxisBand implements Serializable {
/** For serialization. */
private static final long serialVersionUID = -1729482413886398919L;
/** The axis that the band belongs to. */
private NumberAxis axis;
/** The top outer gap. */
private double topOuterGap;
/** The top inner gap. */
private double topInnerGap;
/** The bottom outer gap. */
private double bottomOuterGap;
/** The bottom inner gap. */
private double bottomInnerGap;
/** The font. */
private Font font;
/** Storage for the markers. */
private List<IntervalMarker> markers;
/**
* Constructs a new axis band.
*
* @param axis the owner.
* @param topOuterGap the top outer gap.
* @param topInnerGap the top inner gap.
* @param bottomOuterGap the bottom outer gap.
* @param bottomInnerGap the bottom inner gap.
* @param font the font.
*/
public MarkerAxisBand(NumberAxis axis,
double topOuterGap, double topInnerGap,
double bottomOuterGap, double bottomInnerGap,
Font font) {
this.axis = axis;
this.topOuterGap = topOuterGap;
this.topInnerGap = topInnerGap;
this.bottomOuterGap = bottomOuterGap;
this.bottomInnerGap = bottomInnerGap;
this.font = font;
this.markers = new java.util.ArrayList<IntervalMarker>();
}
/**
* Adds a marker to the band.
*
* @param marker the marker.
*/
public void addMarker(IntervalMarker marker) {
this.markers.add(marker);
}
/**
* Returns the height of the band.
*
* @param g2 the graphics device.
*
* @return The height of the band.
*/
public double getHeight(Graphics2D g2) {
double result = 0.0;
if (this.markers.size() > 0) {
LineMetrics metrics = this.font.getLineMetrics(
"123g", g2.getFontRenderContext()
);
result = this.topOuterGap + this.topInnerGap + metrics.getHeight()
+ this.bottomInnerGap + this.bottomOuterGap;
}
return result;
}
/**
* A utility method that draws a string inside a rectangle.
*
* @param g2 the graphics device.
* @param bounds the rectangle.
* @param font the font.
* @param text the text.
*/
private void drawStringInRect(Graphics2D g2, Rectangle2D bounds, Font font,
String text) {
g2.setFont(font);
FontMetrics fm = g2.getFontMetrics(font);
Rectangle2D r = TextUtilities.getTextBounds(text, g2, fm);
double x = bounds.getX();
if (r.getWidth() < bounds.getWidth()) {
x = x + (bounds.getWidth() - r.getWidth()) / 2;
}
LineMetrics metrics = font.getLineMetrics(
text, g2.getFontRenderContext()
);
g2.drawString(
text, (float) x, (float) (bounds.getMaxY()
- this.bottomInnerGap - metrics.getDescent())
);
}
/**
* Draws the band.
*
* @param g2 the graphics device.
* @param plotArea the plot area.
* @param dataArea the data area.
* @param x the x-coordinate.
* @param y the y-coordinate.
*/
public void draw(Graphics2D g2, Rectangle2D plotArea, Rectangle2D dataArea,
double x, double y) {
double h = getHeight(g2);
for (IntervalMarker marker : this.markers) {
double start = Math.max(
marker.getStartValue(), this.axis.getRange().getLowerBound()
);
double end = Math.min(
marker.getEndValue(), this.axis.getRange().getUpperBound()
);
double s = this.axis.valueToJava2D(
start, dataArea, RectangleEdge.BOTTOM
);
double e = this.axis.valueToJava2D(
end, dataArea, RectangleEdge.BOTTOM
);
Rectangle2D r = new Rectangle2D.Double(
s, y + this.topOuterGap, e - s,
h - this.topOuterGap - this.bottomOuterGap
);
Composite originalComposite = g2.getComposite();
g2.setComposite(AlphaComposite.getInstance(
AlphaComposite.SRC_OVER, marker.getAlpha())
);
g2.setPaint(marker.getPaint());
g2.fill(r);
g2.setPaint(marker.getOutlinePaint());
g2.draw(r);
g2.setComposite(originalComposite);
g2.setPaint(Color.BLACK);
drawStringInRect(g2, r, this.font, marker.getLabel());
}
}
/**
* Tests this axis for equality with another object. Note that the axis
* that the band belongs to is ignored in the test.
*
* @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 MarkerAxisBand)) {
return false;
}
MarkerAxisBand that = (MarkerAxisBand) obj;
if (this.topOuterGap != that.topOuterGap) {
return false;
}
if (this.topInnerGap != that.topInnerGap) {
return false;
}
if (this.bottomInnerGap != that.bottomInnerGap) {
return false;
}
if (this.bottomOuterGap != that.bottomOuterGap) {
return false;
}
if (!ObjectUtilities.equal(this.font, that.font)) {
return false;
}
if (!ObjectUtilities.equal(this.markers, that.markers)) {
return false;
}
return true;
}
/**
* Returns a hash code for the object.
*
* @return A hash code.
*/
@Override
public int hashCode() {
int result = 37;
result = 19 * result + this.font.hashCode();
result = 19 * result + this.markers.hashCode();
return result;
}
}
| 8,760 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
TickUnitSource.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/axis/TickUnitSource.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.]
*
* -------------------
* TickUnitSource.java
* -------------------
* (C) Copyright 2003-2008, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 23-Sep-2003 : Version 1 (DG);
*
*/
package org.jfree.chart.axis;
/**
* An interface used by the {@link DateAxis} and {@link NumberAxis} classes to
* obtain a suitable {@link TickUnit}.
*/
public interface TickUnitSource {
/**
* Returns a tick unit that is larger than the supplied unit.
*
* @param unit the unit.
*
* @return A tick unit that is larger than the supplied unit.
*/
public TickUnit getLargerTickUnit(TickUnit unit);
/**
* Returns the tick unit in the collection that is greater than or equal
* to (in size) the specified unit.
*
* @param unit the unit.
*
* @return A unit from the collection.
*/
public TickUnit getCeilingTickUnit(TickUnit unit);
/**
* Returns the tick unit in the collection that is greater than or equal
* to the specified size.
*
* @param size the size.
*
* @return A unit from the collection.
*/
public TickUnit getCeilingTickUnit(double size);
}
| 2,490 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
CategoryLabelWidthType.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/axis/CategoryLabelWidthType.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.]
*
* ---------------------------
* CategoryLabelWidthType.java
* ---------------------------
* (C) Copyright 2004-2008, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes:
* --------
* 24-Mar-2004 : Version 1 (DG);
*
*/
package org.jfree.chart.axis;
/**
* Represents the width types for a category label.
*/
public enum CategoryLabelWidthType {
/** Percentage of category. */
CATEGORY("CategoryLabelWidthType.CATEGORY"),
/** Percentage of range. */
RANGE("CategoryLabelWidthType.RANGE");
/** The name. */
private String name;
/**
* Private constructor.
*
* @param name the name (<code>null</code> not permitted).
*/
private CategoryLabelWidthType(String name) {
if (name == null) {
throw new IllegalArgumentException("Null 'name' argument.");
}
this.name = name;
}
/**
* Returns a string representing the object.
*
* @return The string (never </code>null</code>).
*/
@Override
public String toString() {
return this.name;
}
}
| 2,385 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
TextUtilities.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/text/TextUtilities.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.]
*
* ------------------
* TextUtilities.java
* ------------------
* (C) Copyright 2004-2014, by Object Refinery Limited and Contributors.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): Brian Fischer;
*
* Changes
* -------
* 07-Jan-2004 : Version 1 (DG);
* 24-Mar-2004 : Added 'paint' argument to createTextBlock() method (DG);
* 07-Apr-2004 : Added getTextBounds() method and useFontMetricsGetStringBounds
* flag (DG);
* 08-Apr-2004 : Changed word break iterator to line break iterator in the
* createTextBlock() method - see bug report 926074 (DG);
* 03-Sep-2004 : Updated createTextBlock() method to add ellipses when limit
* is reached (DG);
* 30-Sep-2004 : Modified bounds returned by drawAlignedString() method (DG);
* 10-Nov-2004 : Added new createTextBlock() method that works with
* newlines (DG);
* 19-Apr-2005 : Changed default value of useFontMetricsGetStringBounds (DG);
* 17-May-2005 : createTextBlock() now recognises '\n' (DG);
* 27-Jun-2005 : Added code to getTextBounds() method to work around Sun's bug
* parade item 6183356 (DG);
* 06-Jan-2006 : Reformatted (DG);
* 27-Apr-2009 : Fix text wrapping with new lines (DG);
* 27-Jul-2009 : Use AttributedString in drawRotatedString() (DG);
* 16-Jun-2012 : Moved from JCommon to JFreeChart (DG);
*
*/
package org.jfree.chart.text;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.Shape;
import java.awt.font.FontRenderContext;
import java.awt.font.LineMetrics;
import java.awt.font.TextLayout;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
import java.text.AttributedString;
import java.text.BreakIterator;
import org.jfree.chart.ui.TextAnchor;
import org.jfree.chart.util.ParamChecks;
/**
* Some utility methods for working with text.
*/
public class TextUtilities {
/**
* When this flag is set to <code>true</code>, strings will be drawn
* as attributed strings with the attributes taken from the current font.
* This allows for underlining, strike-out etc, but it means that
* TextLayout will be used to render the text:
*
* http://www.jfree.org/phpBB2/viewtopic.php?p=45459&highlight=#45459
*/
private static boolean drawStringsWithFontAttributes = false;
/**
* A flag that controls whether or not the rotated string workaround is
* used.
*/
private static boolean useDrawRotatedStringWorkaround = false;
/**
* A flag that controls whether the FontMetrics.getStringBounds() method
* is used or a workaround is applied.
*/
private static boolean useFontMetricsGetStringBounds = false;
/**
* Private constructor prevents object creation.
*/
private TextUtilities() {
}
/**
* Creates a {@link TextBlock} from a <code>String</code>. Line breaks
* are added where the <code>String</code> contains '\n' characters.
*
* @param text the text.
* @param font the font.
* @param paint the paint.
*
* @return A text block.
*/
public static TextBlock createTextBlock(String text, Font font,
Paint paint) {
if (text == null) {
throw new IllegalArgumentException("Null 'text' argument.");
}
TextBlock result = new TextBlock();
String input = text;
boolean moreInputToProcess = (text.length() > 0);
int start = 0;
while (moreInputToProcess) {
int index = input.indexOf("\n");
if (index > start) {
String line = input.substring(start, index);
if (index < input.length() - 1) {
result.addLine(line, font, paint);
input = input.substring(index + 1);
}
else {
moreInputToProcess = false;
}
}
else if (index == start) {
if (index < input.length() - 1) {
input = input.substring(index + 1);
}
else {
moreInputToProcess = false;
}
}
else {
result.addLine(input, font, paint);
moreInputToProcess = false;
}
}
return result;
}
/**
* Creates a new text block from the given string, breaking the
* text into lines so that the <code>maxWidth</code> value is
* respected.
*
* @param text the text.
* @param font the font.
* @param paint the paint.
* @param maxWidth the maximum width for each line.
* @param measurer the text measurer.
*
* @return A text block.
*/
public static TextBlock createTextBlock(String text, Font font, Paint paint,
float maxWidth, TextMeasurer measurer) {
return createTextBlock(text, font, paint, maxWidth, Integer.MAX_VALUE,
measurer);
}
/**
* Creates a new text block from the given string, breaking the
* text into lines so that the <code>maxWidth</code> value is
* respected.
*
* @param text the text.
* @param font the font.
* @param paint the paint.
* @param maxWidth the maximum width for each line.
* @param maxLines the maximum number of lines.
* @param measurer the text measurer.
*
* @return A text block.
*/
public static TextBlock createTextBlock(String text, Font font,
Paint paint, float maxWidth, int maxLines, TextMeasurer measurer) {
TextBlock result = new TextBlock();
BreakIterator iterator = BreakIterator.getLineInstance();
iterator.setText(text);
int current = 0;
int lines = 0;
int length = text.length();
while (current < length && lines < maxLines) {
int next = nextLineBreak(text, current, maxWidth, iterator,
measurer);
if (next == BreakIterator.DONE) {
result.addLine(text.substring(current), font, paint);
return result;
} else if (next == current) {
next++; // we must take one more character or we'll loop forever
}
result.addLine(text.substring(current, next), font, paint);
lines++;
current = next;
while (current < text.length()&& text.charAt(current) == '\n') {
current++;
}
}
if (current < length) {
TextLine lastLine = result.getLastLine();
TextFragment lastFragment = lastLine.getLastTextFragment();
String oldStr = lastFragment.getText();
String newStr = "...";
if (oldStr.length() > 3) {
newStr = oldStr.substring(0, oldStr.length() - 3) + "...";
}
lastLine.removeFragment(lastFragment);
TextFragment newFragment = new TextFragment(newStr,
lastFragment.getFont(), lastFragment.getPaint());
lastLine.addFragment(newFragment);
}
return result;
}
/**
* Returns the character index of the next line break. If the next
* character is wider than <code>width</code> this method will return
* <code>start</code> - the caller should check for this case.
*
* @param text the text (<code>null</code> not permitted).
* @param start the start index.
* @param width the target display width.
* @param iterator the word break iterator.
* @param measurer the text measurer.
*
* @return The index of the next line break.
*/
private static int nextLineBreak(String text, int start, float width,
BreakIterator iterator, TextMeasurer measurer) {
// this method is (loosely) based on code in JFreeReport's
// TextParagraph class
int current = start;
int end;
float x = 0.0f;
boolean firstWord = true;
int newline = text.indexOf('\n', start);
if (newline < 0) {
newline = Integer.MAX_VALUE;
}
while (((end = iterator.following(current)) != BreakIterator.DONE)) {
x += measurer.getStringWidth(text, current, end);
if (x > width) {
if (firstWord) {
while (measurer.getStringWidth(text, start, end) > width) {
end--;
if (end <= start) {
return end;
}
}
return end;
}
else {
end = iterator.previous();
return end;
}
}
else {
if (end > newline) {
return newline;
}
}
// we found at least one word that fits ...
firstWord = false;
current = end;
}
return BreakIterator.DONE;
}
/**
* Returns the bounds for the specified text.
*
* @param text the text (<code>null</code> permitted).
* @param g2 the graphics context (not <code>null</code>).
* @param fm the font metrics (not <code>null</code>).
*
* @return The text bounds (<code>null</code> if the <code>text</code>
* argument is <code>null</code>).
*/
public static Rectangle2D getTextBounds(String text, Graphics2D g2,
FontMetrics fm) {
Rectangle2D bounds;
if (TextUtilities.useFontMetricsGetStringBounds) { // default FALSE
bounds = fm.getStringBounds(text, g2);
// getStringBounds() can return incorrect height for some Unicode
// characters...see bug parade 6183356, let's replace it with
// something correct
LineMetrics lm = fm.getFont().getLineMetrics(text,
g2.getFontRenderContext());
bounds.setRect(bounds.getX(), bounds.getY(), bounds.getWidth(),
lm.getHeight());
}
else {
double width = fm.stringWidth(text);
double height = fm.getHeight();
bounds = new Rectangle2D.Double(0.0, -fm.getAscent(), width,
height);
}
return bounds;
}
/**
* Draws a string such that the specified anchor point is aligned to the
* given (x, y) location.
*
* @param text the text.
* @param g2 the graphics device.
* @param x the x coordinate (Java 2D).
* @param y the y coordinate (Java 2D).
* @param anchor the anchor location.
*
* @return The text bounds (adjusted for the text position).
*/
public static Rectangle2D drawAlignedString(String text, Graphics2D g2,
float x, float y, TextAnchor anchor) {
Rectangle2D textBounds = new Rectangle2D.Double();
float[] adjust = deriveTextBoundsAnchorOffsets(g2, text, anchor,
textBounds);
// adjust text bounds to match string position
textBounds.setRect(x + adjust[0], y + adjust[1] + adjust[2],
textBounds.getWidth(), textBounds.getHeight());
if (!drawStringsWithFontAttributes) {
g2.drawString(text, x + adjust[0], y + adjust[1]);
} else {
AttributedString as = new AttributedString(text,
g2.getFont().getAttributes());
g2.drawString(as.getIterator(), x + adjust[0], y + adjust[1]);
}
return textBounds;
}
/**
* A utility method that calculates the anchor offsets for a string.
* Normally, the (x, y) coordinate for drawing text is a point on the
* baseline at the left of the text string. If you add these offsets to
* (x, y) and draw the string, then the anchor point should coincide with
* the (x, y) point.
*
* @param g2 the graphics device (not <code>null</code>).
* @param text the text.
* @param anchor the anchor point.
* @param textBounds the text bounds (if not <code>null</code>, this
* object will be updated by this method to match the
* string bounds).
*
* @return The offsets.
*/
private static float[] deriveTextBoundsAnchorOffsets(Graphics2D g2,
String text, TextAnchor anchor, Rectangle2D textBounds) {
float[] result = new float[3];
FontRenderContext frc = g2.getFontRenderContext();
Font f = g2.getFont();
FontMetrics fm = g2.getFontMetrics(f);
Rectangle2D bounds = TextUtilities.getTextBounds(text, g2, fm);
LineMetrics metrics = f.getLineMetrics(text, frc);
float ascent = metrics.getAscent();
result[2] = -ascent;
float halfAscent = ascent / 2.0f;
float descent = metrics.getDescent();
float leading = metrics.getLeading();
float xAdj = 0.0f;
float yAdj = 0.0f;
if (anchor.isHorizontalCenter()) {
xAdj = (float) -bounds.getWidth() / 2.0f;
}
else if (anchor.isHorizontalRight()) {
xAdj = (float) -bounds.getWidth();
}
if (anchor.isTop()) {
yAdj = -descent - leading + (float) bounds.getHeight();
}
else if (anchor.isHalfAscent()) {
yAdj = halfAscent;
}
else if (anchor.isHalfHeight()) {
yAdj = -descent - leading + (float) (bounds.getHeight() / 2.0);
}
else if (anchor.isBaseline()) {
yAdj = 0.0f;
}
else if (anchor.isBottom()) {
yAdj = -descent - leading;
}
if (textBounds != null) {
textBounds.setRect(bounds);
}
result[0] = xAdj;
result[1] = yAdj;
return result;
}
/**
* A utility method for drawing rotated text.
* <P>
* A common rotation is -Math.PI/2 which draws text 'vertically' (with the
* top of the characters on the left).
*
* @param text the text.
* @param g2 the graphics device.
* @param angle the angle of the (clockwise) rotation (in radians).
* @param x the x-coordinate.
* @param y the y-coordinate.
*/
public static void drawRotatedString(String text, Graphics2D g2,
double angle, float x, float y) {
drawRotatedString(text, g2, x, y, angle, x, y);
}
/**
* A utility method for drawing rotated text.
* <P>
* A common rotation is -Math.PI/2 which draws text 'vertically' (with the
* top of the characters on the left).
*
* @param text the text.
* @param g2 the graphics device.
* @param textX the x-coordinate for the text (before rotation).
* @param textY the y-coordinate for the text (before rotation).
* @param angle the angle of the (clockwise) rotation (in radians).
* @param rotateX the point about which the text is rotated.
* @param rotateY the point about which the text is rotated.
*/
public static void drawRotatedString(String text, Graphics2D g2,
float textX, float textY, double angle, float rotateX,
float rotateY) {
ParamChecks.nullNotPermitted(text, "text");
if (angle == 0.0) {
drawAlignedString(text, g2, textY, textY, TextAnchor.BASELINE_LEFT);
return;
}
AffineTransform saved = g2.getTransform();
AffineTransform rotate = AffineTransform.getRotateInstance(angle,
rotateX, rotateY);
g2.transform(rotate);
if (useDrawRotatedStringWorkaround) {
// workaround for JDC bug ID 4312117 and others...
TextLayout tl = new TextLayout(text, g2.getFont(),
g2.getFontRenderContext());
tl.draw(g2, textX, textY);
}
else {
if (!drawStringsWithFontAttributes) {
g2.drawString(text, textX, textY);
} else {
AttributedString as = new AttributedString(text,
g2.getFont().getAttributes());
g2.drawString(as.getIterator(), textX, textY);
}
}
g2.setTransform(saved);
}
/**
* Draws a string that is aligned by one anchor point and rotated about
* another anchor point.
*
* @param text the text.
* @param g2 the graphics device.
* @param x the x-coordinate for positioning the text.
* @param y the y-coordinate for positioning the text.
* @param textAnchor the text anchor.
* @param angle the rotation angle.
* @param rotationX the x-coordinate for the rotation anchor point.
* @param rotationY the y-coordinate for the rotation anchor point.
*/
public static void drawRotatedString(String text, Graphics2D g2, float x,
float y, TextAnchor textAnchor, double angle,
float rotationX, float rotationY) {
ParamChecks.nullNotPermitted(text, "text");
if (angle == 0.0) {
drawAlignedString(text, g2, x, y, textAnchor);
return;
}
float[] textAdj = deriveTextBoundsAnchorOffsets(g2, text, textAnchor,
null);
drawRotatedString(text, g2, x + textAdj[0], y + textAdj[1], angle,
rotationX, rotationY);
}
/**
* Draws a string that is aligned by one anchor point and rotated about
* another anchor point.
*
* @param text the text.
* @param g2 the graphics device.
* @param x the x-coordinate for positioning the text.
* @param y the y-coordinate for positioning the text.
* @param textAnchor the text anchor.
* @param angle the rotation angle (in radians).
* @param rotationAnchor the rotation anchor.
*/
public static void drawRotatedString(String text, Graphics2D g2,
float x, float y, TextAnchor textAnchor,
double angle, TextAnchor rotationAnchor) {
if (text == null || text.equals("")) {
return;
}
if (angle == 0.0) {
drawAlignedString(text, g2, x, y, textAnchor);
return;
}
float[] textAdj = deriveTextBoundsAnchorOffsets(g2, text, textAnchor,
null);
float[] rotateAdj = deriveRotationAnchorOffsets(g2, text,
rotationAnchor);
drawRotatedString(text, g2, x + textAdj[0], y + textAdj[1],
angle, x + textAdj[0] + rotateAdj[0],
y + textAdj[1] + rotateAdj[1]);
}
/**
* Returns a shape that represents the bounds of the string after the
* specified rotation has been applied.
*
* @param text the text (<code>null</code> permitted).
* @param g2 the graphics device.
* @param x the x coordinate for the anchor point.
* @param y the y coordinate for the anchor point.
* @param textAnchor the text anchor.
* @param angle the angle.
* @param rotationAnchor the rotation anchor.
*
* @return The bounds (possibly <code>null</code>).
*/
public static Shape calculateRotatedStringBounds(String text, Graphics2D g2,
float x, float y, TextAnchor textAnchor, double angle,
TextAnchor rotationAnchor) {
if (text == null || text.equals("")) {
return null;
}
float[] textAdj = deriveTextBoundsAnchorOffsets(g2, text, textAnchor,
null);
float[] rotateAdj = deriveRotationAnchorOffsets(g2, text,
rotationAnchor);
Shape result = calculateRotatedStringBounds(text, g2,
x + textAdj[0], y + textAdj[1], angle,
x + textAdj[0] + rotateAdj[0], y + textAdj[1] + rotateAdj[1]);
return result;
}
/**
* A utility method that calculates the rotation anchor offsets for a
* string. These offsets are relative to the text starting coordinate
* (<code>BASELINE_LEFT</code>).
*
* @param g2 the graphics device.
* @param text the text.
* @param anchor the anchor point (<code>null</code> not permitted).
*
* @return The offsets.
*/
private static float[] deriveRotationAnchorOffsets(Graphics2D g2,
String text, TextAnchor anchor) {
float[] result = new float[2];
FontRenderContext frc = g2.getFontRenderContext();
LineMetrics metrics = g2.getFont().getLineMetrics(text, frc);
FontMetrics fm = g2.getFontMetrics();
Rectangle2D bounds = TextUtilities.getTextBounds(text, g2, fm);
float ascent = metrics.getAscent();
float halfAscent = ascent / 2.0f;
float descent = metrics.getDescent();
float leading = metrics.getLeading();
float xAdj = 0.0f;
float yAdj = 0.0f;
if (anchor.isHorizontalLeft()) {
xAdj = 0.0f;
}
else if (anchor.isHorizontalCenter()) {
xAdj = (float) bounds.getWidth() / 2.0f;
}
else if (anchor.isHorizontalRight()) {
xAdj = (float) bounds.getWidth();
}
if (anchor.isTop()) {
yAdj = descent + leading - (float) bounds.getHeight();
}
else if (anchor.isHalfHeight()) {
yAdj = descent + leading - (float) (bounds.getHeight() / 2.0);
}
else if (anchor.isHalfAscent()) {
yAdj = -halfAscent;
}
else if (anchor.isBaseline()) {
yAdj = 0.0f;
}
else if (anchor.isBottom()) {
yAdj = descent + leading;
}
result[0] = xAdj;
result[1] = yAdj;
return result;
}
/**
* Returns a shape that represents the bounds of the string after the
* specified rotation has been applied.
*
* @param text the text (<code>null</code> permitted).
* @param g2 the graphics device.
* @param textX the x coordinate for the text.
* @param textY the y coordinate for the text.
* @param angle the angle.
* @param rotateX the x coordinate for the rotation point.
* @param rotateY the y coordinate for the rotation point.
*
* @return The bounds (<code>null</code> if <code>text</code> is
* </code>null</code> or has zero length).
*/
public static Shape calculateRotatedStringBounds(String text, Graphics2D g2,
float textX, float textY, double angle, float rotateX,
float rotateY) {
if ((text == null) || (text.equals(""))) {
return null;
}
FontMetrics fm = g2.getFontMetrics();
Rectangle2D bounds = TextUtilities.getTextBounds(text, g2, fm);
AffineTransform translate = AffineTransform.getTranslateInstance(
textX, textY);
Shape translatedBounds = translate.createTransformedShape(bounds);
AffineTransform rotate = AffineTransform.getRotateInstance(angle,
rotateX, rotateY);
Shape result = rotate.createTransformedShape(translatedBounds);
return result;
}
/**
* Returns the flag that controls whether the FontMetrics.getStringBounds()
* method is used or not. If you are having trouble with label alignment
* or positioning, try changing the value of this flag.
*
* @return A boolean.
*/
public static boolean getUseFontMetricsGetStringBounds() {
return useFontMetricsGetStringBounds;
}
/**
* Sets the flag that controls whether the FontMetrics.getStringBounds()
* method is used or not. If you are having trouble with label alignment
* or positioning, try changing the value of this flag.
*
* @param use the flag.
*/
public static void setUseFontMetricsGetStringBounds(boolean use) {
useFontMetricsGetStringBounds = use;
}
/**
* Returns the flag that controls whether or not a workaround is used for
* drawing rotated strings.
*
* @return A boolean.
*/
public static boolean getUseDrawRotatedStringWorkaround() {
return useDrawRotatedStringWorkaround;
}
/**
* Sets the flag that controls whether or not a workaround is used for
* drawing rotated strings. The related bug is on Sun's bug parade
* (id 4312117) and the workaround involves using a <code>TextLayout</code>
* instance to draw the text instead of calling the
* <code>drawString()</code> method in the <code>Graphics2D</code> class.
*
* @param use the new flag value.
*/
public static void setUseDrawRotatedStringWorkaround(boolean use) {
TextUtilities.useDrawRotatedStringWorkaround = use;
}
/**
* Draws the attributed string at <code>(x, y)</code>, rotated by the
* specified angle about <code>(x, y)</code>.
*
* @param text the attributed string (<code>null</code> not permitted).
* @param g2 the graphics output target.
* @param angle the angle.
* @param x the x-coordinate.
* @param y the y-coordinate.
*/
public static void drawRotatedString(AttributedString text, Graphics2D g2,
double angle, float x, float y) {
drawRotatedString(text, g2, x, y, angle, x, y);
}
/**
* Draws the attributed string at <code>(textX, textY)</code>, rotated by
* the specified angle about <code>(rotateX, rotateY)</code>.
*
* @param text the attributed string (<code>null</code> not permitted).
* @param g2 the graphics output target (<code>null</code> not permitted).
* @param textX the x-coordinate for the text.
* @param textY the y-coordinate for the text.
* @param angle the rotation angle (in radians).
* @param rotateX the x-coordinate for the rotation point.
* @param rotateY the y-coordinate for the rotation point.
*/
public static void drawRotatedString(AttributedString text, Graphics2D g2,
float textX, float textY, double angle, float rotateX,
float rotateY) {
ParamChecks.nullNotPermitted(text, "text");
AffineTransform saved = g2.getTransform();
AffineTransform rotate = AffineTransform.getRotateInstance(angle,
rotateX, rotateY);
g2.transform(rotate);
TextLayout tl = new TextLayout(text.getIterator(),
g2.getFontRenderContext());
tl.draw(g2, textX, textY);
g2.setTransform(saved);
}
/**
* Draws an attributed string with the <code>textAnchor</code> point
* aligned to <code>(x, y)</code> and rotated by <code>angle</code> radians
* about the <code>rotationAnchor</code>.
*
* @param text the attributed string (<code>null</code> not permitted).
* @param g2 the graphics target (<code>null</code> not permitted).
* @param x the x-coordinate.
* @param y the y-coordinate.
* @param textAnchor the text anchor (<code>null</code> not permitted).
* @param angle the rotation angle (in radians).
* @param rotationAnchor the rotation anchor point (<code>null</code> not
* permitted).
*/
public static void drawRotatedString(AttributedString text, Graphics2D g2,
float x, float y, TextAnchor textAnchor,
double angle, TextAnchor rotationAnchor) {
ParamChecks.nullNotPermitted(text, "text");
float[] textAdj = deriveTextBoundsAnchorOffsets(g2, text, textAnchor,
null);
float[] rotateAdj = deriveRotationAnchorOffsets(g2, text,
rotationAnchor);
drawRotatedString(text, g2, x + textAdj[0], y + textAdj[1],
angle, x + textAdj[0] + rotateAdj[0],
y + textAdj[1] + rotateAdj[1]);
}
private static float[] deriveTextBoundsAnchorOffsets(Graphics2D g2,
AttributedString text, TextAnchor anchor, Rectangle2D textBounds) {
TextLayout layout = new TextLayout(text.getIterator(),
g2.getFontRenderContext());
Rectangle2D bounds = layout.getBounds();
float[] result = new float[3];
float ascent = layout.getAscent();
result[2] = -ascent;
float halfAscent = ascent / 2.0f;
float descent = layout.getDescent();
float leading = layout.getLeading();
float xAdj = 0.0f;
float yAdj = 0.0f;
if (anchor.isHorizontalCenter()) {
xAdj = (float) -bounds.getWidth() / 2.0f;
}
else if (anchor.isHorizontalRight()) {
xAdj = (float) -bounds.getWidth();
}
if (anchor.isTop()) {
yAdj = -descent - leading + (float) bounds.getHeight();
}
else if (anchor.isHalfAscent()) {
yAdj = halfAscent;
}
else if (anchor.isHalfHeight()) {
yAdj = -descent - leading + (float) (bounds.getHeight() / 2.0);
}
else if (anchor.isBaseline()) {
yAdj = 0.0f;
}
else if (anchor.isBottom()) {
yAdj = -descent - leading;
}
if (textBounds != null) {
textBounds.setRect(bounds);
}
result[0] = xAdj;
result[1] = yAdj;
return result;
}
/**
* A utility method that calculates the rotation anchor offsets for a
* string. These offsets are relative to the text starting coordinate
* (BASELINE_LEFT).
*
* @param g2 the graphics device.
* @param text the text.
* @param anchor the anchor point.
*
* @return The offsets.
*/
private static float[] deriveRotationAnchorOffsets(Graphics2D g2,
AttributedString text, TextAnchor anchor) {
float[] result = new float[2];
TextLayout layout = new TextLayout(text.getIterator(),
g2.getFontRenderContext());
Rectangle2D bounds = layout.getBounds();
float ascent = layout.getAscent();
float halfAscent = ascent / 2.0f;
float descent = layout.getDescent();
float leading = layout.getLeading();
float xAdj = 0.0f;
float yAdj = 0.0f;
if (anchor.isHorizontalLeft()) {
xAdj = 0.0f;
}
else if (anchor.isHorizontalCenter()) {
xAdj = (float) bounds.getWidth() / 2.0f;
}
else if (anchor.isHorizontalRight()) {
xAdj = (float) bounds.getWidth();
}
if (anchor.isTop()) {
yAdj = descent + leading - (float) bounds.getHeight();
}
else if (anchor.isHalfHeight()) {
yAdj = descent + leading - (float) (bounds.getHeight() / 2.0);
}
else if (anchor.isHalfAscent()) {
yAdj = -halfAscent;
}
else if (anchor.isBaseline()) {
yAdj = 0.0f;
}
else if (anchor.isBottom()) {
yAdj = descent + leading;
}
result[0] = xAdj;
result[1] = yAdj;
return result;
}
/**
* Returns the flag that controls whether or not strings are drawn using
* the current font attributes (such as underlining, strikethrough etc).
* The default value is <code>false</code>.
*
* @return A boolean.
*
* @since 1.0.21
*/
public static boolean getDrawStringsWithFontAttributes() {
return TextUtilities.drawStringsWithFontAttributes;
}
/**
* Sets the flag that controls whether or not strings are drawn using the
* current font attributes. This is a hack to allow underlining of titles
* without big changes to the API. See:
* http://www.jfree.org/phpBB2/viewtopic.php?p=45459&highlight=#45459
*
* @param b the new flag value.
*
* @since 1.0.21
*/
public static void setDrawStringsWithFontAttributes(boolean b) {
TextUtilities.drawStringsWithFontAttributes = b;
}
}
| 33,420 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
TextBlock.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/text/TextBlock.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.]
*
* --------------
* TextBlock.java
* --------------
* (C) Copyright 2003-2013, by Object Refinery Limited and Contributors.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 07-Nov-2003 : Version 1 (DG);
* 22-Dec-2003 : Added workaround for Java bug 4245442 (DG);
* 09-Jan-2004 : Added an extra draw() method for no rotation case (DG);
* 25-Feb-2004 : Added getLines() method (DG);
* 22-Mar-2004 : Added equals() method and implemented Serializable (DG);
* 24-Mar-2004 : Added 'paint' argument to addLine() method (DG);
* 01-Apr-2004 : Changed java.awt.geom.Dimension2D to org.jfree.ui.Size2D
* because of JDK bug 4976448 which persists on JDK 1.3.1 (DG);
* 04-Oct-2004 : Renamed ShapeUtils --> ShapeUtilities (DG);
* 15-Jun-2012 : Moved from JCommon to JFreeChart (DG);
*
*/
package org.jfree.chart.text;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.Shape;
import java.awt.geom.Rectangle2D;
import java.io.Serializable;
import java.util.Collections;
import java.util.List;
import org.jfree.chart.ui.HorizontalAlignment;
import org.jfree.chart.ui.Size2D;
import org.jfree.chart.ui.TextAnchor;
import org.jfree.chart.util.ParamChecks;
import org.jfree.chart.util.ShapeUtilities;
/**
* A list of {@link TextLine} objects that form a block of text.
*
* @see TextUtilities#createTextBlock(String, Font, Paint)
*/
public class TextBlock implements Serializable {
/** For serialization. */
private static final long serialVersionUID = -4333175719424385526L;
/** Storage for the lines of text. */
private List<TextLine> lines;
/** The alignment of the lines. */
private HorizontalAlignment lineAlignment;
/**
* Creates a new empty text block.
*/
public TextBlock() {
this.lines = new java.util.ArrayList<TextLine>();
this.lineAlignment = HorizontalAlignment.CENTER;
}
/**
* Returns the alignment of the lines of text within the block.
*
* @return The alignment (never <code>null</code>).
*/
public HorizontalAlignment getLineAlignment() {
return this.lineAlignment;
}
/**
* Sets the alignment of the lines of text within the block.
*
* @param alignment the alignment (<code>null</code> not permitted).
*/
public void setLineAlignment(HorizontalAlignment alignment) {
ParamChecks.nullNotPermitted(alignment, "alignment");
this.lineAlignment = alignment;
}
/**
* Adds a line of text that will be displayed using the specified font.
*
* @param text the text.
* @param font the font.
* @param paint the paint.
*/
public void addLine(String text, Font font, Paint paint) {
addLine(new TextLine(text, font, paint));
}
/**
* Adds a {@link TextLine} to the block.
*
* @param line the line.
*/
public void addLine(TextLine line) {
this.lines.add(line);
}
/**
* Returns the last line in the block.
*
* @return The last line in the block.
*/
public TextLine getLastLine() {
TextLine last = null;
int index = this.lines.size() - 1;
if (index >= 0) {
last = this.lines.get(index);
}
return last;
}
/**
* Returns an unmodifiable list containing the lines for the text block.
*
* @return A list of {@link TextLine} objects.
*/
public List<TextLine> getLines() {
return Collections.unmodifiableList(this.lines);
}
/**
* Returns the width and height of the text block.
*
* @param g2 the graphics device.
*
* @return The width and height.
*/
public Size2D calculateDimensions(Graphics2D g2) {
double width = 0.0;
double height = 0.0;
for (TextLine line : this.lines) {
Size2D dimension = line.calculateDimensions(g2);
width = Math.max(width, dimension.getWidth());
height = height + dimension.getHeight();
}
return new Size2D(width, height);
}
/**
* Returns the bounds of the text block.
*
* @param g2 the graphics device (<code>null</code> not permitted).
* @param anchorX the x-coordinate for the anchor point.
* @param anchorY the y-coordinate for the anchor point.
* @param anchor the text block anchor (<code>null</code> not permitted).
* @param rotateX the x-coordinate for the rotation point.
* @param rotateY the y-coordinate for the rotation point.
* @param angle the rotation angle.
*
* @return The bounds.
*/
public Shape calculateBounds(Graphics2D g2, float anchorX, float anchorY,
TextBlockAnchor anchor, float rotateX, float rotateY,
double angle) {
Size2D d = calculateDimensions(g2);
float[] offsets = calculateOffsets(anchor, d.getWidth(), d.getHeight());
Rectangle2D bounds = new Rectangle2D.Double(anchorX + offsets[0],
anchorY + offsets[1], d.getWidth(), d.getHeight());
Shape rotatedBounds = ShapeUtilities.rotateShape(bounds, angle,
rotateX, rotateY);
return rotatedBounds;
}
/**
* Draws the text block at a specific location.
*
* @param g2 the graphics device.
* @param x the x-coordinate for the anchor point.
* @param y the y-coordinate for the anchor point.
* @param anchor the anchor point.
*/
public void draw(Graphics2D g2, float x, float y, TextBlockAnchor anchor) {
draw(g2, x, y, anchor, 0.0f, 0.0f, 0.0);
}
/**
* Draws the text block, aligning it with the specified anchor point and
* rotating it about the specified rotation point.
*
* @param g2 the graphics device.
* @param anchorX the x-coordinate for the anchor point.
* @param anchorY the y-coordinate for the anchor point.
* @param anchor the point on the text block that is aligned to the
* anchor point.
* @param rotateX the x-coordinate for the rotation point.
* @param rotateY the x-coordinate for the rotation point.
* @param angle the rotation (in radians).
*/
public void draw(Graphics2D g2, float anchorX, float anchorY,
TextBlockAnchor anchor, float rotateX, float rotateY,
double angle) {
Size2D d = calculateDimensions(g2);
float[] offsets = calculateOffsets(anchor, d.getWidth(), d.getHeight());
float yCursor = 0.0f;
for (TextLine line : this.lines) {
Size2D dimension = line.calculateDimensions(g2);
float lineOffset = 0.0f;
if (this.lineAlignment == HorizontalAlignment.CENTER) {
lineOffset = (float) (d.getWidth() - dimension.getWidth())
/ 2.0f;
} else if (this.lineAlignment == HorizontalAlignment.RIGHT) {
lineOffset = (float) (d.getWidth() - dimension.getWidth());
}
line.draw(g2, anchorX + offsets[0] + lineOffset,
anchorY + offsets[1] + yCursor, TextAnchor.TOP_LEFT,
rotateX, rotateY, angle);
yCursor = yCursor + (float) dimension.getHeight();
}
}
/**
* Calculates the x and y offsets required to align the text block with the
* specified anchor point. This assumes that the top left of the text
* block is at (0.0, 0.0).
*
* @param anchor the anchor position.
* @param width the width of the text block.
* @param height the height of the text block.
*
* @return The offsets (float[0] = x offset, float[1] = y offset).
*/
private float[] calculateOffsets(TextBlockAnchor anchor,
double width, double height) {
float[] result = new float[2];
float xAdj = 0.0f;
float yAdj = 0.0f;
if (anchor == TextBlockAnchor.TOP_CENTER
|| anchor == TextBlockAnchor.CENTER
|| anchor == TextBlockAnchor.BOTTOM_CENTER) {
xAdj = (float) -width / 2.0f;
}
else if (anchor == TextBlockAnchor.TOP_RIGHT
|| anchor == TextBlockAnchor.CENTER_RIGHT
|| anchor == TextBlockAnchor.BOTTOM_RIGHT) {
xAdj = (float) -width;
}
if (anchor == TextBlockAnchor.TOP_LEFT
|| anchor == TextBlockAnchor.TOP_CENTER
|| anchor == TextBlockAnchor.TOP_RIGHT) {
yAdj = 0.0f;
}
else if (anchor == TextBlockAnchor.CENTER_LEFT
|| anchor == TextBlockAnchor.CENTER
|| anchor == TextBlockAnchor.CENTER_RIGHT) {
yAdj = (float) -height / 2.0f;
}
else if (anchor == TextBlockAnchor.BOTTOM_LEFT
|| anchor == TextBlockAnchor.BOTTOM_CENTER
|| anchor == TextBlockAnchor.BOTTOM_RIGHT) {
yAdj = (float) -height;
}
result[0] = xAdj;
result[1] = yAdj;
return result;
}
/**
* 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 TextBlock) {
TextBlock block = (TextBlock) obj;
return this.lines.equals(block.lines);
}
return false;
}
/**
* Returns a hash code for this object.
*
* @return A hash code.
*/
@Override
public int hashCode() {
return (this.lines != null ? this.lines.hashCode() : 0);
}
}
| 11,111 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
TextFragment.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/text/TextFragment.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.]
*
* -----------------
* TextFragment.java
* -----------------
* (C) Copyright 2003-2013, by Object Refinery Limited and Contributors.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* $Id: TextFragment.java,v 1.13 2007/03/16 10:25:58 mungady Exp $
*
* Changes
* -------
* 07-Nov-2003 : Version 1 (DG);
* 25-Nov-2003 : Fixed bug in the dimension calculation (DG);
* 22-Dec-2003 : Added workaround for Java bug 4245442 (DG);
* 29-Jan-2004 : Added paint attribute (DG);
* 22-Mar-2004 : Added equals() method and implemented Serializable (DG);
* 01-Apr-2004 : Changed java.awt.geom.Dimension2D to org.jfree.ui.Size2D
* because of JDK bug 4976448 which persists on JDK 1.3.1 (DG);
* 30-Sep-2004 : Moved drawRotatedString() from RefineryUtilities
* --> TextUtilities (DG);
* 16-Mar-2007 : Fixed serialization for GradientPaint (DG);
* 17-Jun-2012 : Moved from JCommon to JFreeChart (DG);
*
*/
package org.jfree.chart.text;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.font.LineMetrics;
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.ui.Size2D;
import org.jfree.chart.ui.TextAnchor;
import org.jfree.chart.util.ParamChecks;
import org.jfree.chart.util.SerialUtilities;
/**
* A text item, with an associated font, that fits on a single line (see
* {@link TextLine}). Instances of the class are immutable.
*/
public class TextFragment implements Serializable {
/** For serialization. */
private static final long serialVersionUID = 4465945952903143262L;
/** The default font. */
public static final Font DEFAULT_FONT = new Font("Serif", Font.PLAIN, 12);
/** The default text color. */
public static final Paint DEFAULT_PAINT = Color.BLACK;
/** The text. */
private String text;
/** The font. */
private Font font;
/** The text color. */
private transient Paint paint;
/**
* The baseline offset (can be used to simulate subscripts and
* superscripts).
*/
private float baselineOffset;
/**
* Creates a new text fragment.
*
* @param text the text (<code>null</code> not permitted).
*/
public TextFragment(String text) {
this(text, DEFAULT_FONT, DEFAULT_PAINT);
}
/**
* Creates a new text fragment.
*
* @param text the text (<code>null</code> not permitted).
* @param font the font (<code>null</code> not permitted).
*/
public TextFragment(String text, final Font font) {
this(text, font, DEFAULT_PAINT);
}
/**
* Creates a new text fragment.
*
* @param text the text (<code>null</code> not permitted).
* @param font the font (<code>null</code> not permitted).
* @param paint the text color (<code>null</code> not permitted).
*/
public TextFragment(String text, final Font font, final Paint paint) {
this(text, font, paint, 0.0f);
}
/**
* Creates a new text fragment.
*
* @param text the text (<code>null</code> not permitted).
* @param font the font (<code>null</code> not permitted).
* @param paint the text color (<code>null</code> not permitted).
* @param baselineOffset the baseline offset.
*/
public TextFragment(String text, Font font, Paint paint, float baselineOffset) {
ParamChecks.nullNotPermitted(text, "text");
ParamChecks.nullNotPermitted(font, "font");
ParamChecks.nullNotPermitted(paint, "paint");
this.text = text;
this.font = font;
this.paint = paint;
this.baselineOffset = baselineOffset;
}
/**
* Returns the text.
*
* @return The text (possibly <code>null</code>).
*/
public String getText() {
return this.text;
}
/**
* Returns the font.
*
* @return The font (never <code>null</code>).
*/
public Font getFont() {
return this.font;
}
/**
* Returns the text paint.
*
* @return The text paint (never <code>null</code>).
*/
public Paint getPaint() {
return this.paint;
}
/**
* Returns the baseline offset.
*
* @return The baseline offset.
*/
public float getBaselineOffset() {
return this.baselineOffset;
}
/**
* Draws the text fragment.
*
* @param g2 the graphics device.
* @param anchorX the x-coordinate of the anchor point.
* @param anchorY the y-coordinate of the anchor point.
* @param anchor the location of the text that is aligned to the anchor
* point.
* @param rotateX the x-coordinate of the rotation point.
* @param rotateY the y-coordinate of the rotation point.
* @param angle the angle.
*/
public void draw(Graphics2D g2, float anchorX, float anchorY,
TextAnchor anchor, float rotateX, float rotateY, double angle) {
g2.setFont(this.font);
g2.setPaint(this.paint);
TextUtilities.drawRotatedString(this.text, g2, anchorX, anchorY
+ this.baselineOffset, anchor, angle, rotateX, rotateY);
}
/**
* Calculates the dimensions of the text fragment.
*
* @param g2 the graphics device.
*
* @return The width and height of the text.
*/
public Size2D calculateDimensions(Graphics2D g2) {
FontMetrics fm = g2.getFontMetrics(this.font);
Rectangle2D bounds = TextUtilities.getTextBounds(this.text, g2, fm);
Size2D result = new Size2D(bounds.getWidth(), bounds.getHeight());
return result;
}
/**
* Calculates the vertical offset between the baseline and the specified
* text anchor.
*
* @param g2 the graphics device.
* @param anchor the anchor.
*
* @return the offset.
*/
public float calculateBaselineOffset(Graphics2D g2, TextAnchor anchor) {
float result = 0.0f;
FontMetrics fm = g2.getFontMetrics(this.font);
LineMetrics lm = fm.getLineMetrics("ABCxyz", g2);
if (anchor.isTop()) {
result = lm.getAscent();
}
else if (anchor.isHalfAscent()) {
result = lm.getAscent() / 2.0f;
}
else if (anchor.isHalfHeight()) {
result = lm.getAscent() / 2.0f - lm.getDescent() / 2.0f;
}
else if (anchor.isBottom()) {
result = -lm.getDescent() - lm.getLeading();
}
return result;
}
/**
* Tests this instance 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 == null) {
return false;
}
if (obj == this) {
return true;
}
if (obj instanceof TextFragment) {
TextFragment tf = (TextFragment) obj;
if (!this.text.equals(tf.text)) {
return false;
}
if (!this.font.equals(tf.font)) {
return false;
}
if (!this.paint.equals(tf.paint)) {
return false;
}
return true;
}
return false;
}
/**
* Returns a hash code for this object.
*
* @return A hash code.
*/
@Override
public int hashCode() {
int result;
result = (this.text != null ? this.text.hashCode() : 0);
result = 29 * result + (this.font != null ? this.font.hashCode() : 0);
result = 29 * result + (this.paint != null ? this.paint.hashCode() : 0);
return result;
}
/**
* Provides serialization support.
*
* @param stream the output stream.
*
* @throws IOException if there is an I/O error.
*/
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
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(final ObjectInputStream stream) throws IOException,
ClassNotFoundException {
stream.defaultReadObject();
this.paint = SerialUtilities.readPaint(stream);
}
}
| 9,956 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
G2TextMeasurer.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/text/G2TextMeasurer.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.]
*
* -------------------
* G2TextMeasurer.java
* -------------------
* (C) Copyright 2004-2013, by Object Refinery Limited and Contributors.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* $Id: G2TextMeasurer.java,v 1.4 2005/10/18 13:17:16 mungady Exp $
*
* Changes
* -------
* 07-Jan-2004 : Version 1 (DG);
*
*/
package org.jfree.chart.text;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;
/**
* A {@link TextMeasurer} based on a {@link Graphics2D}.
*/
public class G2TextMeasurer implements TextMeasurer {
/** The graphics device. */
private Graphics2D g2;
/**
* Creates a new text measurer.
*
* @param g2 the graphics device.
*/
public G2TextMeasurer(Graphics2D g2) {
this.g2 = g2;
}
/**
* Returns the string width.
*
* @param text the text.
* @param start the index of the first character to measure.
* @param end the index of the last character to measure.
*
* @return The string width.
*/
@Override
public float getStringWidth(String text, int start, int end) {
FontMetrics fm = this.g2.getFontMetrics();
Rectangle2D bounds = TextUtilities.getTextBounds(
text.substring(start, end), this.g2, fm);
float result = (float) bounds.getWidth();
return result;
}
}
| 2,654 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
TextLine.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/text/TextLine.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.]
*
* -------------
* TextLine.java
* -------------
* (C) Copyright 2003-2013, by Object Refinery Limited and Contributors.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* $Id: TextLine.java,v 1.13 2007/11/02 17:50:35 taqua Exp $
*
* Changes
* -------
* 07-Nov-2003 : Version 1 (DG);
* 22-Dec-2003 : Added workaround for Java bug 4245442 (DG);
* 29-Jan-2004 : Added new constructor (DG);
* 22-Mar-2004 : Added equals() method and implemented Serializable (DG);
* 01-Apr-2004 : Changed java.awt.geom.Dimension2D to org.jfree.ui.Size2D
* because of JDK bug 4976448 which persists on JDK 1.3.1 (DG);
* 03-Sep-2004 : Added a method to remove a fragment (DG);
* 08-Jul-2005 : Fixed bug in calculateBaselineOffset() (DG);
* 17-Jun-2012 : Moved from JCommon to JFreeChart (DG);
*
*/
package org.jfree.chart.text;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.io.Serializable;
import java.util.List;
import org.jfree.chart.ui.Size2D;
import org.jfree.chart.ui.TextAnchor;
import org.jfree.chart.util.ParamChecks;
/**
* A sequence of {@link TextFragment} objects that together form a line of
* text. A sequence of text lines is managed by the {@link TextBlock} class.
*/
public class TextLine implements Serializable {
/** For serialization. */
private static final long serialVersionUID = 7100085690160465444L;
/** Storage for the text fragments that make up the line. */
private List<TextFragment> fragments;
/**
* Creates a new empty line.
*/
public TextLine() {
this.fragments = new java.util.ArrayList<TextFragment>();
}
/**
* Creates a new text line using the default font.
*
* @param text the text (<code>null</code> not permitted).
*/
public TextLine(String text) {
this(text, TextFragment.DEFAULT_FONT);
}
/**
* Creates a new text line.
*
* @param text the text (<code>null</code> not permitted).
* @param font the text font (<code>null</code> not permitted).
*/
public TextLine(String text, Font font) {
this.fragments = new java.util.ArrayList<TextFragment>();
TextFragment fragment = new TextFragment(text, font);
this.fragments.add(fragment);
}
/**
* Creates a new text line.
*
* @param text the text (<code>null</code> not permitted).
* @param font the text font (<code>null</code> not permitted).
* @param paint the text color (<code>null</code> not permitted).
*/
public TextLine(String text, Font font, Paint paint) {
ParamChecks.nullNotPermitted(text, "text");
ParamChecks.nullNotPermitted(font, "font");
ParamChecks.nullNotPermitted(paint, "paint");
this.fragments = new java.util.ArrayList<TextFragment>();
TextFragment fragment = new TextFragment(text, font, paint);
this.fragments.add(fragment);
}
/**
* Adds a text fragment to the text line.
*
* @param fragment the text fragment (<code>null</code> not permitted).
*/
public void addFragment(TextFragment fragment) {
this.fragments.add(fragment);
}
/**
* Removes a fragment from the line.
*
* @param fragment the fragment to remove.
*/
public void removeFragment(TextFragment fragment) {
this.fragments.remove(fragment);
}
/**
* Draws the text line.
*
* @param g2 the graphics device.
* @param anchorX the x-coordinate for the anchor point.
* @param anchorY the y-coordinate for the anchor point.
* @param anchor the point on the text line that is aligned to the anchor
* point.
* @param rotateX the x-coordinate for the rotation point.
* @param rotateY the y-coordinate for the rotation point.
* @param angle the rotation angle (in radians).
*/
public void draw(Graphics2D g2, float anchorX, float anchorY,
TextAnchor anchor, float rotateX, float rotateY, double angle) {
Size2D dim = calculateDimensions(g2);
float xAdj = 0.0f;
if (anchor.isHorizontalCenter()) {
xAdj = (float) -dim.getWidth() / 2.0f;
}
else if (anchor.isHorizontalRight()) {
xAdj = (float) -dim.getWidth();
}
float x = anchorX + xAdj;
float yOffset = calculateBaselineOffset(g2, anchor);
for (TextFragment fragment : this.fragments) {
Size2D d = fragment.calculateDimensions(g2);
fragment.draw(g2, x, anchorY + yOffset, TextAnchor.BASELINE_LEFT,
rotateX, rotateY, angle);
x = x + (float) d.getWidth();
}
}
/**
* Calculates the width and height of the text line.
*
* @param g2 the graphics device.
*
* @return The width and height.
*/
public Size2D calculateDimensions(Graphics2D g2) {
double width = 0.0;
double height = 0.0;
for (TextFragment fragment : this.fragments) {
final Size2D dimension = fragment.calculateDimensions(g2);
width = width + dimension.getWidth();
height = Math.max(height, dimension.getHeight());
}
return new Size2D(width, height);
}
/**
* Returns the first text fragment in the line.
*
* @return The first text fragment in the line.
*/
public TextFragment getFirstTextFragment() {
TextFragment result = null;
if (this.fragments.size() > 0) {
result = this.fragments.get(0);
}
return result;
}
/**
* Returns the last text fragment in the line.
*
* @return The last text fragment in the line.
*/
public TextFragment getLastTextFragment() {
TextFragment result = null;
if (this.fragments.size() > 0) {
result = this.fragments.get(this.fragments.size()
- 1);
}
return result;
}
/**
* Calculate the offsets required to translate from the specified anchor
* position to the left baseline position.
*
* @param g2 the graphics device.
* @param anchor the anchor position.
*
* @return The offsets.
*/
private float calculateBaselineOffset(Graphics2D g2, TextAnchor anchor) {
float result = 0.0f;
for (TextFragment fragment : this.fragments) {
result = Math.max(result,
fragment.calculateBaselineOffset(g2, anchor));
}
return result;
}
/**
* 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 == null) {
return false;
}
if (obj == this) {
return true;
}
if (obj instanceof TextLine) {
TextLine line = (TextLine) obj;
return this.fragments.equals(line.fragments);
}
return false;
}
/**
* Returns a hash code for this object.
*
* @return A hash code.
*/
@Override
public int hashCode() {
return (this.fragments != null ? this.fragments.hashCode() : 0);
}
}
| 8,620 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
TextMeasurer.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/text/TextMeasurer.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.]
*
* -----------------
* TextMeasurer.java
* -----------------
* (C) Copyright 2004-2012, by Object Refinery Limited and Contributors.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* $Id: TextMeasurer.java,v 1.4 2005/10/18 13:17:16 mungady Exp $
*
* Changes
* -------
* 07-Jan-2004 : Version 1 (DG);
* 17-Jun-2012 : Moved from JCommon to JFreeChart (DG);
*
*/
package org.jfree.chart.text;
/**
* An object that can measure text.
*/
public interface TextMeasurer {
/**
* Calculates the width of a <code>String</code> in the current
* <code>Graphics</code> context.
*
* @param text the text.
* @param start the start position of the substring to be measured.
* @param end the position of the last character to be measured.
*
* @return The width of the string in Java2D units.
*/
public float getStringWidth(String text, int start, int end);
}
| 2,191 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
TextBox.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/text/TextBox.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.]
*
* ------------
* TextBox.java
* ------------
* (C) Copyright 2004-2013, by Object Refinery Limited and Contributors.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 09-Mar-2004 : Version 1 (DG);
* 22-Mar-2004 : Added equals() method and implemented Serializable (DG);
* 09-Nov-2004 : Renamed getAdjustedHeight() --> calculateExtendedHeight() in
* Spacer class (DG);
* 22-Feb-2005 : Replaced Spacer with RectangleInsets (DG);
* 14-Feb-2008 : Fixed alignment of text content with respect to insets (DG);
* 16-Jun-2012 : Moved from JCommon to JFreeChart (DG);
*
*/
package org.jfree.chart.text;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.Stroke;
import java.awt.geom.Rectangle2D;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import org.jfree.chart.ui.RectangleAnchor;
import org.jfree.chart.ui.RectangleInsets;
import org.jfree.chart.ui.Size2D;
import org.jfree.chart.util.ObjectUtilities;
import org.jfree.chart.util.SerialUtilities;
/**
* A box containing a text block.
*/
public class TextBox implements Serializable {
/** For serialization. */
private static final long serialVersionUID = 3360220213180203706L;
/** The outline paint. */
private transient Paint outlinePaint;
/** The outline stroke. */
private transient Stroke outlineStroke;
/** The interior space. */
private RectangleInsets interiorGap;
/** The background paint. */
private transient Paint backgroundPaint;
/** The shadow paint. */
private transient Paint shadowPaint;
/** The shadow x-offset. */
private double shadowXOffset = 2.0;
/** The shadow y-offset. */
private double shadowYOffset = 2.0;
/** The text block. */
private TextBlock textBlock;
/**
* Creates an empty text box.
*/
public TextBox() {
this((TextBlock) null);
}
/**
* Creates a text box.
*
* @param text the text.
*/
public TextBox(String text) {
this((TextBlock) null);
if (text != null) {
this.textBlock = new TextBlock();
this.textBlock.addLine(text, new Font("SansSerif", Font.PLAIN, 10),
Color.BLACK);
}
}
/**
* Creates a new text box.
*
* @param block the text block.
*/
public TextBox(TextBlock block) {
this.outlinePaint = Color.BLACK;
this.outlineStroke = new BasicStroke(1.0f);
this.interiorGap = new RectangleInsets(1.0, 3.0, 1.0, 3.0);
this.backgroundPaint = new Color(255, 255, 192);
this.shadowPaint = Color.GRAY;
this.shadowXOffset = 2.0;
this.shadowYOffset = 2.0;
this.textBlock = block;
}
/**
* Returns the outline paint.
*
* @return The outline paint.
*/
public Paint getOutlinePaint() {
return this.outlinePaint;
}
/**
* Sets the outline paint.
*
* @param paint the paint.
*/
public void setOutlinePaint(Paint paint) {
this.outlinePaint = paint;
}
/**
* Returns the outline stroke.
*
* @return The outline stroke.
*/
public Stroke getOutlineStroke() {
return this.outlineStroke;
}
/**
* Sets the outline stroke.
*
* @param stroke the stroke.
*/
public void setOutlineStroke(Stroke stroke) {
this.outlineStroke = stroke;
}
/**
* Returns the interior gap.
*
* @return The interior gap.
*/
public RectangleInsets getInteriorGap() {
return this.interiorGap;
}
/**
* Sets the interior gap.
*
* @param gap the gap.
*/
public void setInteriorGap(RectangleInsets gap) {
this.interiorGap = gap;
}
/**
* Returns the background paint.
*
* @return The background paint.
*/
public Paint getBackgroundPaint() {
return this.backgroundPaint;
}
/**
* Sets the background paint.
*
* @param paint the paint.
*/
public void setBackgroundPaint(Paint paint) {
this.backgroundPaint = paint;
}
/**
* Returns the shadow paint.
*
* @return The shadow paint.
*/
public Paint getShadowPaint() {
return this.shadowPaint;
}
/**
* Sets the shadow paint.
*
* @param paint the paint.
*/
public void setShadowPaint(Paint paint) {
this.shadowPaint = paint;
}
/**
* Returns the x-offset for the shadow effect.
*
* @return The offset.
*/
public double getShadowXOffset() {
return this.shadowXOffset;
}
/**
* Sets the x-offset for the shadow effect.
*
* @param offset the offset (in Java2D units).
*/
public void setShadowXOffset(double offset) {
this.shadowXOffset = offset;
}
/**
* Returns the y-offset for the shadow effect.
*
* @return The offset.
*/
public double getShadowYOffset() {
return this.shadowYOffset;
}
/**
* Sets the y-offset for the shadow effect.
*
* @param offset the offset (in Java2D units).
*/
public void setShadowYOffset(double offset) {
this.shadowYOffset = offset;
}
/**
* Returns the text block.
*
* @return The text block.
*/
public TextBlock getTextBlock() {
return this.textBlock;
}
/**
* Sets the text block.
*
* @param block the block.
*/
public void setTextBlock(TextBlock block) {
this.textBlock = block;
}
/**
* Draws the text box.
*
* @param g2 the graphics device.
* @param x the x-coordinate.
* @param y the y-coordinate.
* @param anchor the anchor point.
*/
public void draw(Graphics2D g2, float x, float y, RectangleAnchor anchor) {
Size2D d1 = this.textBlock.calculateDimensions(g2);
double w = this.interiorGap.extendWidth(d1.getWidth());
double h = this.interiorGap.extendHeight(d1.getHeight());
Size2D d2 = new Size2D(w, h);
Rectangle2D bounds = RectangleAnchor.createRectangle(d2, x, y, anchor);
double xx = bounds.getX();
double yy = bounds.getY();
if (this.shadowPaint != null) {
Rectangle2D shadow = new Rectangle2D.Double(xx + this.shadowXOffset,
yy + this.shadowYOffset, bounds.getWidth(),
bounds.getHeight());
g2.setPaint(this.shadowPaint);
g2.fill(shadow);
}
if (this.backgroundPaint != null) {
g2.setPaint(this.backgroundPaint);
g2.fill(bounds);
}
if (this.outlinePaint != null && this.outlineStroke != null) {
g2.setPaint(this.outlinePaint);
g2.setStroke(this.outlineStroke);
g2.draw(bounds);
}
this.textBlock.draw(g2,
(float) (xx + this.interiorGap.calculateLeftInset(w)),
(float) (yy + this.interiorGap.calculateTopInset(h)),
TextBlockAnchor.TOP_LEFT);
}
/**
* Returns the height of the text box.
*
* @param g2 the graphics device.
*
* @return The height (in Java2D units).
*/
public double getHeight(Graphics2D g2) {
Size2D d = this.textBlock.calculateDimensions(g2);
return this.interiorGap.extendHeight(d.getHeight());
}
/**
* 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 TextBox)) {
return false;
}
TextBox that = (TextBox) obj;
if (!ObjectUtilities.equal(this.outlinePaint, that.outlinePaint)) {
return false;
}
if (!ObjectUtilities.equal(this.outlineStroke, that.outlineStroke)) {
return false;
}
if (!ObjectUtilities.equal(this.interiorGap, that.interiorGap)) {
return false;
}
if (!ObjectUtilities.equal(this.backgroundPaint,
that.backgroundPaint)) {
return false;
}
if (!ObjectUtilities.equal(this.shadowPaint, that.shadowPaint)) {
return false;
}
if (this.shadowXOffset != that.shadowXOffset) {
return false;
}
if (this.shadowYOffset != that.shadowYOffset) {
return false;
}
if (!ObjectUtilities.equal(this.textBlock, that.textBlock)) {
return false;
}
return true;
}
/**
* Returns a hash code for this object.
*
* @return A hash code.
*/
@Override
public int hashCode() {
int result;
long temp;
result = (this.outlinePaint != null ? this.outlinePaint.hashCode() : 0);
result = 29 * result + (this.outlineStroke != null
? this.outlineStroke.hashCode() : 0);
result = 29 * result + (this.interiorGap != null
? this.interiorGap.hashCode() : 0);
result = 29 * result + (this.backgroundPaint != null
? this.backgroundPaint.hashCode() : 0);
result = 29 * result + (this.shadowPaint != null
? this.shadowPaint.hashCode() : 0);
temp = this.shadowXOffset != +0.0d
? Double.doubleToLongBits(this.shadowXOffset) : 0L;
result = 29 * result + (int) (temp ^ (temp >>> 32));
temp = this.shadowYOffset != +0.0d
? Double.doubleToLongBits(this.shadowYOffset) : 0L;
result = 29 * result + (int) (temp ^ (temp >>> 32));
result = 29 * result + (this.textBlock != null
? this.textBlock.hashCode() : 0);
return result;
}
/**
* Provides serialization support.
*
* @param stream the output stream.
*
* @throws IOException if there is an I/O error.
*/
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
SerialUtilities.writePaint(this.outlinePaint, stream);
SerialUtilities.writeStroke(this.outlineStroke, stream);
SerialUtilities.writePaint(this.backgroundPaint, stream);
SerialUtilities.writePaint(this.shadowPaint, stream);
}
/**
* Provides serialization support.
*
* @param stream the input stream.
*
* @throws IOException if there is an I/O error.
* @throws ClassNotFoundException if there is a classpath problem.
*/
private void readObject(ObjectInputStream stream) throws IOException,
ClassNotFoundException {
stream.defaultReadObject();
this.outlinePaint = SerialUtilities.readPaint(stream);
this.outlineStroke = SerialUtilities.readStroke(stream);
this.backgroundPaint = SerialUtilities.readPaint(stream);
this.shadowPaint = SerialUtilities.readPaint(stream);
}
}
| 12,597 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
TextBlockAnchor.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/text/TextBlockAnchor.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.]
*
* --------------------
* TextBlockAnchor.java
* --------------------
* (C) Copyright 2003-2012, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* $Id: TextBlockAnchor.java,v 1.4 2005/10/18 13:17:16 mungady Exp $
*
* Changes:
* --------
* 06-Nov-2003 : Version 1 (DG);
* 22-Mar-2004 : Added readResolve() method (DG);
* 17-Jun-2012 : Moved from JCommon to JFreeChart (DG);
*
*/
package org.jfree.chart.text;
/**
* Used to indicate the position of an anchor point for a text block.
*/
public enum TextBlockAnchor {
/** Top/left. */
TOP_LEFT("TextBlockAnchor.TOP_LEFT"),
/** Top/center. */
TOP_CENTER("TextBlockAnchor.TOP_CENTER"),
/** Top/right. */
TOP_RIGHT("TextBlockAnchor.TOP_RIGHT"),
/** Middle/left. */
CENTER_LEFT("TextBlockAnchor.CENTER_LEFT"),
/** Middle/center. */
CENTER("TextBlockAnchor.CENTER"),
/** Middle/right. */
CENTER_RIGHT("TextBlockAnchor.CENTER_RIGHT"),
/** Bottom/left. */
BOTTOM_LEFT("TextBlockAnchor.BOTTOM_LEFT"),
/** Bottom/center. */
BOTTOM_CENTER("TextBlockAnchor.BOTTOM_CENTER"),
/** Bottom/right. */
BOTTOM_RIGHT("TextBlockAnchor.BOTTOM_RIGHT");
/** The name. */
private String name;
/**
* Private constructor.
*
* @param name the name.
*/
private TextBlockAnchor(final String name) {
this.name = name;
}
/**
* Returns a string representing the object.
*
* @return The string.
*/
@Override
public String toString() {
return this.name;
}
}
| 2,862 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
HexNumberFormat.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/util/HexNumberFormat.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.]
*
* --------------------
* HexNumberFormat.java
* --------------------
* (C) Copyright 2007, 2008, by Richard West and Contributors.
*
* Original Author: Richard West, Advanced Micro Devices, Inc.;
* Contributor(s): David Gilbert (for Object Refinery Limited);
*
* Changes:
* --------
* 14-Jun-2007 : Version 1 (RW);
*
*/
package org.jfree.chart.util;
import java.text.FieldPosition;
import java.text.NumberFormat;
import java.text.ParsePosition;
/**
* A custom number formatter that formats numbers as hexadecimal strings.
* There are some limitations, so be careful using this class.
*
* @since 1.0.6
*/
public class HexNumberFormat extends NumberFormat {
/** Number of hexadecimal digits for a byte. */
public static final int BYTE = 2;
/** Number of hexadecimal digits for a word. */
public static final int WORD = 4;
/** Number of hexadecimal digits for a double word. */
public static final int DWORD = 8;
/** Number of hexadecimal digits for a quad word. */
public static final int QWORD = 16;
/** The number of digits (shorter strings will be left padded). */
private int m_numDigits = DWORD;
/**
* Creates a new instance with 8 digits.
*/
public HexNumberFormat() {
this(DWORD);
}
/**
* Creates a new instance with the specified number of digits.
* @param digits the digits.
*/
public HexNumberFormat(int digits) {
super();
this.m_numDigits = digits;
}
/**
* Returns the number of digits.
*
* @return The number of digits.
*/
public final int getNumberOfDigits() {
return this.m_numDigits;
}
/**
* Sets the number of digits.
*
* @param digits the number of digits.
*/
public void setNumberOfDigits(int digits) {
this.m_numDigits = digits;
}
/**
* Formats the specified number as a hexadecimal string. The decimal
* fraction is ignored.
*
* @param number the number to format.
* @param toAppendTo the buffer to append to (ignored here).
* @param pos the field position (ignored here).
*
* @return The string buffer.
*/
@Override
public StringBuffer format(double number, StringBuffer toAppendTo,
FieldPosition pos) {
return format((long) number, toAppendTo, pos);
}
/**
* Formats the specified number as a hexadecimal string. The decimal
* fraction is ignored.
*
* @param number the number to format.
* @param toAppendTo the buffer to append to (ignored here).
* @param pos the field position (ignored here).
*
* @return The string buffer.
*/
@Override
public StringBuffer format(long number, StringBuffer toAppendTo,
FieldPosition pos) {
String l_hex = Long.toHexString(number).toUpperCase();
int l_pad = this.m_numDigits - l_hex.length();
l_pad = (0 < l_pad) ? l_pad : 0;
StringBuffer l_extended = new StringBuffer("0x");
for (int i = 0; i < l_pad; i++) {
l_extended.append(0);
}
l_extended.append(l_hex);
return l_extended;
}
/**
* Parsing is not implemented, so this method always returns
* <code>null</code>.
*
* @param source ignored.
* @param parsePosition ignored.
*
* @return Always <code>null</code>.
*/
@Override
public Number parse (String source, ParsePosition parsePosition) {
return null; // don't bother with parsing
}
}
| 4,806 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
TableOrder.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/util/TableOrder.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.]
*
* ---------------
* TableOrder.java
* ---------------
* (C) Copyright 2004-2011, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes:
* --------
* 29-Jan-2004 : Version 1 (DG);
* 16-Jun-2012 : Moved from JCommon to JFreeChart (DG);
*
*/
package org.jfree.chart.util;
/**
* Used to indicate the processing order for a table (by row or by column).
*/
public enum TableOrder {
/** By row. */
BY_ROW("TableOrder.BY_ROW"),
/** By column. */
BY_COLUMN("TableOrder.BY_COLUMN");
/** The name. */
private String name;
/**
* Private constructor.
*
* @param name the name.
*/
private TableOrder(String name) {
this.name = name;
}
/**
* Returns a string representing the object.
*
* @return The string.
*/
@Override
public String toString() {
return this.name;
}
}
| 2,186 | 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/util/package-info.java | /**
* Utility classes used by JFreeChart. Some of these will be candidates for addition to JCommon, but we keep them here so that our dependency is only JCommon 1.0.0 or later.
*/
package org.jfree.chart.util;
| 213 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
PaintList.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/util/PaintList.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.]
*
* --------------
* PaintList.java
* --------------
* (C) Copyright 2003-2012, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 13-Aug-2003 : Version 1 (DG);
* 27-Jun-2005 : Fixed equals() method to handle GradientPaint (DG);
*
*/
package org.jfree.chart.util;
import java.awt.Paint;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
/**
* A table of {@link Paint} objects.
*/
public class PaintList extends AbstractObjectList<Paint> {
/**
* Creates a new list.
*/
public PaintList() {
super();
}
/**
* Returns a {@link Paint} object from the list.
*
* @param index the index (zero-based).
*
* @return The object.
*/
public Paint getPaint(final int index) {
return get(index);
}
/**
* Sets the {@link Paint} for an item in the list. The list is expanded if necessary.
*
* @param index the index (zero-based).
* @param paint the {@link Paint}.
*/
public void setPaint(final int index, final Paint paint) {
set(index, paint);
}
/**
* Tests the list for equality with another object (typically also a list).
*
* @param obj the other object (<code>null</code> permitted).
*
* @return A boolean.
*/
@Override
public boolean equals(final Object obj) {
if (obj == null) {
return false;
}
if (obj == this) {
return true;
}
if (obj instanceof PaintList) {
PaintList that = (PaintList) obj;
int listSize = size();
for (int i = 0; i < listSize; i++) {
if (!PaintUtilities.equal(getPaint(i), that.getPaint(i))) {
return false;
}
}
}
return true;
}
/**
* Returns a hash code value for the object.
*
* @return the hashcode
*/
@Override
public int hashCode() {
return super.hashCode();
}
/**
* Provides serialization support.
*
* @param stream the output stream.
*
* @throws IOException if there is an I/O error.
*/
private void writeObject(final ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
final int count = size();
stream.writeInt(count);
for (int i = 0; i < count; i++) {
final Paint paint = getPaint(i);
if (paint != null) {
stream.writeInt(i);
SerialUtilities.writePaint(paint, stream);
}
else {
stream.writeInt(-1);
}
}
}
/**
* 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(final ObjectInputStream stream) throws IOException, ClassNotFoundException {
stream.defaultReadObject();
final int count = stream.readInt();
for (int i = 0; i < count; i++) {
final int index = stream.readInt();
if (index != -1) {
setPaint(index, SerialUtilities.readPaint(stream));
}
}
}
}
| 4,669 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
PaintUtilities.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/util/PaintUtilities.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.]
*
* -------------------
* PaintUtilities.java
* -------------------
* (C) Copyright 2003-2012, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* $Id: PaintUtilities.java,v 1.10 2007/11/02 17:50:37 taqua Exp $
*
* Changes
* -------
* 13-Nov-2003 : Version 1 (DG);
* 04-Oct-2004 : Renamed PaintUtils --> PaintUtilities (DG);
* 23-Feb-2005 : Rewrote equal() method with less indenting required (DG);
* 16-Jun-2012 : Moved from JCommon to JFreeChart (DG);
*
*/
package org.jfree.chart.util;
import java.awt.Color;
import java.awt.GradientPaint;
import java.awt.Paint;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
/**
* Utility code that relates to <code>Paint</code> objects.
*/
public class PaintUtilities {
/**
* Private constructor prevents object creation.
*/
private PaintUtilities() {
}
/**
* Returns <code>true</code> if the two <code>Paint</code> objects are equal
* OR both <code>null</code>. This method handles
* <code>GradientPaint</code> as a special case.
*
* @param p1 paint 1 (<code>null</code> permitted).
* @param p2 paint 2 (<code>null</code> permitted).
*
* @return A boolean.
*/
public static boolean equal(final Paint p1, final Paint p2) {
// handle cases where either or both arguments are null
if (p1 == null) {
return (p2 == null);
}
if (p2 == null) {
return false;
}
boolean result = false;
// handle GradientPaint as a special case...
if (p1 instanceof GradientPaint && p2 instanceof GradientPaint) {
final GradientPaint gp1 = (GradientPaint) p1;
final GradientPaint gp2 = (GradientPaint) p2;
result = gp1.getColor1().equals(gp2.getColor1())
&& gp1.getColor2().equals(gp2.getColor2())
&& gp1.getPoint1().equals(gp2.getPoint1())
&& gp1.getPoint2().equals(gp2.getPoint2())
&& gp1.isCyclic() == gp2.isCyclic()
&& gp1.getTransparency() == gp1.getTransparency();
}
else {
result = p1.equals(p2);
}
return result;
}
/**
* Converts a color into a string. If the color is equal to one of the
* defined constant colors, that name is returned instead. Otherwise the
* color is returned as hex-string.
*
* @param c the color.
* @return the string for this color.
*/
public static String colorToString (final Color c)
{
try {
final Field[] fields = Color.class.getFields();
for (final Field f : fields) {
if (Modifier.isPublic(f.getModifiers())
&& Modifier.isFinal(f.getModifiers())
&& Modifier.isStatic(f.getModifiers())) {
final String name = f.getName();
final Object oColor = f.get(null);
if (oColor instanceof Color) {
if (c.equals(oColor)) {
return name;
}
}
}
}
}
catch (Exception e) {
//
}
// no defined constant color, so this must be a user defined color
final String color = Integer.toHexString(c.getRGB() & 0x00ffffff);
final StringBuffer retval = new StringBuffer(7);
retval.append("#");
final int fillUp = 6 - color.length();
for (int i = 0; i < fillUp; i++) {
retval.append("0");
}
retval.append(color);
return retval.toString();
}
/**
* Converts a given string into a color.
*
* @param value the string, either a name or a hex-string.
* @return the color.
*/
public static Color stringToColor (final String value)
{
if (value == null) {
return Color.BLACK;
}
try {
// get color by hex or octal value
return Color.decode(value);
}
catch (NumberFormatException nfe) {
// if we can't decode lets try to get it by name
try {
// try to get a color by name using reflection
final Field f = Color.class.getField(value);
return (Color) f.get(null);
}
catch (Exception ce) {
// if we can't get any color return black
return Color.BLACK;
}
}
}
}
| 5,784 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
SortOrder.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/util/SortOrder.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.]
*
* --------------
* SortOrder.java
* --------------
* (C) Copyright 2003-2012, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes:
* --------
* 05-Mar-2003 : Version 1 (DG);
* 13-Mar-2003 : Implemented Serializable (DG);
* 27-Aug-2003 : Moved from JFreeChart --> JCommon (DG);
* 29-Jul-2004 : Fixed error in readResolve() method (DG);
* 16-Jun-2012 : Moved from JCommon to JFreeChart (DG);
*
*/
package org.jfree.chart.util;
/**
* Defines tokens used to indicate sorting order (ascending or descending).
*
* @author David Gilbert
*/
public enum SortOrder {
/** Ascending order. */
ASCENDING("SortOrder.ASCENDING"),
/** Descending order. */
DESCENDING("SortOrder.DESCENDING");
/** The name. */
private String name;
/**
* Private constructor.
*
* @param name the name.
*/
private SortOrder(final String name) {
this.name = name;
}
/**
* Returns a string representing the object.
*
* @return The string.
*/
@Override
public String toString() {
return this.name;
}
}
| 2,402 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
PublicCloneable.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/util/PublicCloneable.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.]
*
* --------------------
* PublicCloneable.java
* --------------------
* (C) Copyright 2003-2012, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 18-Aug-2003 : Version 1 (DG);
* 16-Jun-2012 : Moved from JCommon to JFreeChart (DG);
*
*/
package org.jfree.chart.util;
/**
* An interface that exposes the clone() method.
*/
public interface PublicCloneable extends Cloneable {
/**
* Returns a clone of the object.
*
* @return A clone.
*
* @throws CloneNotSupportedException if cloning is not supported for some reason.
*/
public Object clone() throws CloneNotSupportedException;
}
| 1,959 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
ResourceBundleWrapper.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/util/ResourceBundleWrapper.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.]
*
* --------------------------
* ResourceBundleWrapper.java
* --------------------------
* (C)opyright 2008, 2009, by Jess Thrysoee and Contributors.
*
* Original Author: Jess Thrysoee;
* Contributor(s): David Gilbert (for Object Refinery Limited);
*
* Changes
* -------
* 18-Dec-2008 : Version 1 (JT);
*
*/
package org.jfree.chart.util;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.ResourceBundle;
/**
* Wrapper of ResourceBundle.getBundle() methods. This wrapper is introduced to
* avoid a dramatic performance penalty by superfluous resource (and classes
* loaded by Class.forName) lookups on web server in applets.
*
* <pre>
* public class AppletC extends javax.swing.JApplet {
* public void init() {
* ResourceBundleWrapper.removeCodeBase(getCodeBase(),
* (URLClassLoader) getClass().getClassLoader());
* ...
* </pre>
*
* @see <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4243379">
* Bug ID: 4243379</a>
* @see <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4668479">
* Bug ID: 4668479</a>
*
* @since 1.0.12
*/
public class ResourceBundleWrapper {
/**
* A special class loader with no code base lookup. This field may be
* <code>null</code> (the field is only initialised if removeCodeBase() is
* called from an applet).
*/
private static URLClassLoader noCodeBaseClassLoader;
/**
* Private constructor.
*/
private ResourceBundleWrapper() {
// all methods are static, no need to instantiate
}
/**
* Instantiate a {@link URLClassLoader} for resource lookups where the
* codeBase URL is removed. This method is typically called from an
* applet's init() method. If this method is never called, the
* <code>getBundle()</code> methods map to the standard
* {@link ResourceBundle} lookup methods.
*
* @param codeBase the codeBase URL.
* @param urlClassLoader the class loader.
*/
public static void removeCodeBase(URL codeBase,
URLClassLoader urlClassLoader) {
List<URL> urlsNoBase = new ArrayList<URL>();
URL[] urls = urlClassLoader.getURLs();
for (URL url : urls) {
if (!url.sameFile(codeBase)) {
urlsNoBase.add(url);
}
}
// substitute the filtered URL list
URL[] urlsNoBaseArray = urlsNoBase.toArray(new URL[urlsNoBase.size()]);
noCodeBaseClassLoader = URLClassLoader.newInstance(urlsNoBaseArray);
}
/**
* Finds and returns the specified resource bundle.
*
* @param baseName the base name.
*
* @return The resource bundle.
*/
public static ResourceBundle getBundle(String baseName) {
// the noCodeBaseClassLoader is configured by a call to the
// removeCodeBase() method, typically in the init() method of an
// applet...
if (noCodeBaseClassLoader != null) {
return ResourceBundle.getBundle(baseName, Locale.getDefault(),
noCodeBaseClassLoader);
}
else {
// standard ResourceBundle behaviour
return ResourceBundle.getBundle(baseName);
}
}
/**
* Finds and returns the specified resource bundle.
*
* @param baseName the base name.
* @param locale the locale.
*
* @return The resource bundle.
*/
public static ResourceBundle getBundle(String baseName, Locale locale) {
// the noCodeBaseClassLoader is configured by a call to the
// removeCodeBase() method, typically in the init() method of an
// applet...
if (noCodeBaseClassLoader != null) {
return ResourceBundle.getBundle(baseName, locale,
noCodeBaseClassLoader);
}
else {
// standard ResourceBundle behaviour
return ResourceBundle.getBundle(baseName, locale);
}
}
/**
* Maps directly to <code>ResourceBundle.getBundle(baseName, locale,
* loader)</code>.
*
* @param baseName the base name.
* @param locale the locale.
* @param loader the class loader.
*
* @return The resource bundle.
*/
public static ResourceBundle getBundle(String baseName, Locale locale,
ClassLoader loader) {
return ResourceBundle.getBundle(baseName, locale, loader);
}
}
| 5,773 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
ParamChecks.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/util/ParamChecks.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.]
*
* ----------------
* ParamChecks.java
* ----------------
* (C) Copyright 2011, 2013, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 16-Oct-2011 : Version 1 (DG);
* 01-Jan-2013 : Added requireInRange() method (DG);
*
*/
package org.jfree.chart.util;
/**
* A utility class for checking parameters.
*
* @since 1.0.14
*/
public class ParamChecks {
/**
* Throws an <code>IllegalArgumentException</code> if the supplied
* <code>param</code> is <code>null</code>.
*
* @param param the parameter to check (<code>null</code> permitted).
* @param name the name of the parameter (to use in the exception message
* if <code>param</code> is <code>null</code>).
*
* @throws IllegalArgumentException if <code>param</code> is
* <code>null</code>.
*
* @since 1.0.14
*/
public static void nullNotPermitted(Object param, String name) {
if (param == null) {
throw new IllegalArgumentException("Null '" + name + "' argument.");
}
}
/**
* Throws an <code>IllegalArgumentException</code> if the supplied
* <code>value</code> is not in the range <code>lowerBound</code> to
* <code>upperBound</code> inclusive.
*
* @param value the value to check.
* @param valueStr the name of the parameter (to use in the exception
* message).
* @param lowerBound the lower bound.
* @param upperBound the upper bound.
*
* @throws IllegalArgumentException if the supplied <code>value</code> is
* not in the range <code>lowerBound</code> to <code>upperBound</code>
* inclusive.
*
* @since 1.0.15
*/
public static void requireInRange(double value, String valueStr,
double lowerBound, double upperBound) {
if (value < lowerBound || value > upperBound || Double.isNaN(value)) {
throw new IllegalArgumentException("Requires '"
+ valueStr + "' in the range " + lowerBound + " to "
+ upperBound);
}
}
}
| 3,396 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
AbstractObjectList.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/util/AbstractObjectList.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.]
*
* -----------------------
* AbstractObjectList.java
* -----------------------
* (C)opyright 2003-2012, by Object Refinery Limited and Contributors.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): Bill Kelemen;
* Nicolas Brodu
*
* Changes
* -------
* 13-Aug-2003 : Version 1, based on ObjectList (DG);
* 24-Aug-2003 : Fixed size (BK);
* 15-Sep-2003 : Fix serialization for subclasses (ShapeList, PaintList) (NB);
* 15-Jun-2012 : Moved from JCommon to JFreeChart (DG);
*
*/
package org.jfree.chart.util;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Arrays;
/**
* A list of objects that can grow as required.
*/
public class AbstractObjectList<T> implements Cloneable, Serializable {
/** For serialization. */
private static final long serialVersionUID = 7789833772597351595L;
/** The default initial capacity of the list. */
public static final int DEFAULT_INITIAL_CAPACITY = 8;
/** Storage for the objects. */
private transient Object[] objects;
/** The current list size. */
private int size = 0;
/** The default increment. */
private int increment = DEFAULT_INITIAL_CAPACITY;
/**
* Creates a new list with the default initial capacity.
*/
protected AbstractObjectList() {
this(DEFAULT_INITIAL_CAPACITY);
}
/**
* Creates a new list.
*
* @param initialCapacity the initial capacity.
*/
protected AbstractObjectList(final int initialCapacity) {
this (initialCapacity, initialCapacity);
}
/**
* Creates a new list.
*
* @param initialCapacity the initial capacity.
* @param increment the increment.
*/
protected AbstractObjectList(final int initialCapacity,
final int increment) {
this.objects = new Object[initialCapacity];
this.increment = increment;
}
/**
* Returns the object at the specified index, if there is one, or
* <code>null</code>.
*
* @param index the object index.
*
* @return The object or <code>null</code>.
*/
protected T get(final int index) {
T result = null;
if (index >= 0 && index < this.size) {
result = (T)this.objects[index];
}
return result;
}
/**
* Sets an object reference (overwriting any existing object).
*
* @param index the object index.
* @param object the object (<code>null</code> permitted).
*/
protected void set(final int index, final T object) {
if (index < 0) {
throw new IllegalArgumentException("Requires index >= 0.");
}
if (index >= this.objects.length) {
final Object[] enlarged = new Object[index + this.increment];
System.arraycopy(this.objects, 0, enlarged, 0, this.objects.length);
this.objects = enlarged;
}
this.objects[index] = object;
this.size = Math.max(this.size, index + 1);
}
/**
* Clears the list.
*/
public void clear() {
Arrays.fill(this.objects, null);
this.size = 0;
}
/**
* Returns the size of the list.
*
* @return The size of the list.
*/
public int size() {
return this.size;
}
/**
* Returns the index of the specified object, or -1 if the object is not in
* the list.
*
* @param object the object.
*
* @return The index or -1.
*/
protected int indexOf(final T object) {
for (int index = 0; index < this.size; index++) {
if (this.objects[index] == object) {
return (index);
}
}
return -1;
}
/**
* Tests this list for equality with another object.
*
* @param obj the object to test.
*
* @return A boolean.
*/
@Override
public boolean equals(final Object obj) {
if (obj == null) {
return false;
}
if (obj == this) {
return true;
}
if (!(obj instanceof AbstractObjectList)) {
return false;
}
final AbstractObjectList<?> other = (AbstractObjectList<?>) obj;
final int listSize = size();
for (int i = 0; i < listSize; i++) {
if (!ObjectUtilities.equal(get(i), other.get(i))) {
return false;
}
}
return true;
}
/**
* Returns a hash code value for the object.
*
* @return the hashcode
*/
@Override
public int hashCode() {
return super.hashCode();
}
/**
* Clones the list of objects. The objects in the list are not cloned, so
* this is method makes a 'shallow' copy of the list.
*
* @return A clone.
*
* @throws CloneNotSupportedException if an item in the list does not
* support cloning.
*/
@Override
public Object clone() throws CloneNotSupportedException {
final AbstractObjectList<?> clone = (AbstractObjectList<?>) super.clone();
if (this.objects != null) {
clone.objects = new Object[this.objects.length];
System.arraycopy(
this.objects, 0, clone.objects, 0, this.objects.length
);
}
return clone;
}
/**
* Provides serialization support.
*
* @param stream the output stream.
*
* @throws IOException if there is an I/O error.
*/
private void writeObject(final ObjectOutputStream stream)
throws IOException {
stream.defaultWriteObject();
final int count = size();
stream.writeInt(count);
for (int i = 0; i < count; i++) {
final Object object = get(i);
if (object != null && object instanceof Serializable) {
stream.writeInt(i);
stream.writeObject(object);
}
else {
stream.writeInt(-1);
}
}
}
/**
* 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(final ObjectInputStream stream)
throws IOException, ClassNotFoundException {
stream.defaultReadObject();
this.objects = new Object[this.size];
final int count = stream.readInt();
for (int i = 0; i < count; i++) {
final int index = stream.readInt();
if (index != -1) {
set(index, (T)stream.readObject());
}
}
}
}
| 8,111 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
ShapeUtilities.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/util/ShapeUtilities.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.]
*
* -------------------
* ShapeUtilities.java
* -------------------
* (C)opyright 2003-2012, by Object Refinery Limited and Contributors.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 13-Aug-2003 : Version 1 (DG);
* 16-Mar-2004 : Moved rotateShape() from RefineryUtilities.java to here (DG);
* 13-May-2004 : Added new shape creation methods (DG);
* 30-Sep-2004 : Added createLineRegion() method (DG);
* Moved drawRotatedShape() method from RefineryUtilities class
* to this class (DG);
* 04-Oct-2004 : Renamed ShapeUtils --> ShapeUtilities (DG);
* 26-Oct-2004 : Added a method to test the equality of two Line2D
* instances (DG);
* 10-Nov-2004 : Added new translateShape() and equal(Ellipse2D, Ellipse2D)
* methods (DG);
* 11-Nov-2004 : Renamed translateShape() --> createTranslatedShape() (DG);
* 07-Jan-2005 : Minor Javadoc fix (DG);
* 11-Jan-2005 : Removed deprecated code in preparation for 1.0.0 release (DG);
* 21-Jan-2005 : Modified return type of RectangleAnchor.coordinates()
* method (DG);
* 22-Feb-2005 : Added equality tests for Arc2D and GeneralPath (DG);
* 16-Mar-2005 : Fixed bug where equal(Shape, Shape) fails for two Polygon
* instances (DG);
* 01-Jun-2008 : Fixed bug in equal(GeneralPath, GeneralPath) method (DG);
* 16-Jun-2012 : Moved from JCommon to JFreeChart (DG);
*
*/
package org.jfree.chart.util;
import java.awt.Graphics2D;
import java.awt.Polygon;
import java.awt.Shape;
import java.awt.geom.AffineTransform;
import java.awt.geom.Arc2D;
import java.awt.geom.Ellipse2D;
import java.awt.geom.GeneralPath;
import java.awt.geom.Line2D;
import java.awt.geom.PathIterator;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.util.Arrays;
import org.jfree.chart.ui.RectangleAnchor;
/**
* Utility methods for {@link Shape} objects.
*/
public class ShapeUtilities {
/**
* Prevents instantiation.
*/
private ShapeUtilities() {
}
/**
* Returns a clone of the specified shape, or <code>null</code>. At the
* current time, this method supports cloning for instances of
* <code>Line2D</code>, <code>RectangularShape</code>, <code>Area</code>
* and <code>GeneralPath</code>.
* <p>
* <code>RectangularShape</code> includes <code>Arc2D</code>,
* <code>Ellipse2D</code>, <code>Rectangle2D</code>,
* <code>RoundRectangle2D</code>.
*
* @param shape the shape to clone (<code>null</code> permitted,
* returns <code>null</code>).
*
* @return A clone or <code>null</code>.
*/
public static Shape clone(final Shape shape) {
if (shape instanceof Cloneable) {
try {
return ObjectUtilities.clone(shape);
}
catch (CloneNotSupportedException cnse) {
//this shouldn't be thrown if object is cloneable
}
}
return null;
}
/**
* Tests two shapes for equality. If both shapes are <code>null</code>,
* this method will return <code>true</code>.
* <p>
* In the current implementation, the following shapes are supported:
* <code>Ellipse2D</code>, <code>Line2D</code> and <code>Rectangle2D</code>
* (implicit).
*
* @param s1 the first shape (<code>null</code> permitted).
* @param s2 the second shape (<code>null</code> permitted).
*
* @return A boolean.
*/
public static boolean equal(final Shape s1, final Shape s2) {
if (s1 instanceof Line2D && s2 instanceof Line2D) {
return equal((Line2D) s1, (Line2D) s2);
}
else if (s1 instanceof Ellipse2D && s2 instanceof Ellipse2D) {
return equal((Ellipse2D) s1, (Ellipse2D) s2);
}
else if (s1 instanceof Arc2D && s2 instanceof Arc2D) {
return equal((Arc2D) s1, (Arc2D) s2);
}
else if (s1 instanceof Polygon && s2 instanceof Polygon) {
return equal((Polygon) s1, (Polygon) s2);
}
else if (s1 instanceof GeneralPath && s2 instanceof GeneralPath) {
return equal((GeneralPath) s1, (GeneralPath) s2);
}
else {
// this will handle Rectangle2D...
return ObjectUtilities.equal(s1, s2);
}
}
/**
* Compares two lines are returns <code>true</code> if they are equal or
* both <code>null</code>.
*
* @param l1 the first line (<code>null</code> permitted).
* @param l2 the second line (<code>null</code> permitted).
*
* @return A boolean.
*/
public static boolean equal(final Line2D l1, final Line2D l2) {
if (l1 == null) {
return (l2 == null);
}
if (l2 == null) {
return false;
}
if (!l1.getP1().equals(l2.getP1())) {
return false;
}
if (!l1.getP2().equals(l2.getP2())) {
return false;
}
return true;
}
/**
* Compares two ellipses and returns <code>true</code> if they are equal or
* both <code>null</code>.
*
* @param e1 the first ellipse (<code>null</code> permitted).
* @param e2 the second ellipse (<code>null</code> permitted).
*
* @return A boolean.
*/
public static boolean equal(final Ellipse2D e1, final Ellipse2D e2) {
if (e1 == null) {
return (e2 == null);
}
if (e2 == null) {
return false;
}
if (!e1.getFrame().equals(e2.getFrame())) {
return false;
}
return true;
}
/**
* Compares two arcs and returns <code>true</code> if they are equal or
* both <code>null</code>.
*
* @param a1 the first arc (<code>null</code> permitted).
* @param a2 the second arc (<code>null</code> permitted).
*
* @return A boolean.
*/
public static boolean equal(final Arc2D a1, final Arc2D a2) {
if (a1 == null) {
return (a2 == null);
}
if (a2 == null) {
return false;
}
if (!a1.getFrame().equals(a2.getFrame())) {
return false;
}
if (a1.getAngleStart() != a2.getAngleStart()) {
return false;
}
if (a1.getAngleExtent() != a2.getAngleExtent()) {
return false;
}
if (a1.getArcType() != a2.getArcType()) {
return false;
}
return true;
}
/**
* Tests two polygons for equality. If both are <code>null</code> this
* method returns <code>true</code>.
*
* @param p1 polygon 1 (<code>null</code> permitted).
* @param p2 polygon 2 (<code>null</code> permitted).
*
* @return A boolean.
*/
public static boolean equal(final Polygon p1, final Polygon p2) {
if (p1 == null) {
return (p2 == null);
}
if (p2 == null) {
return false;
}
if (p1.npoints != p2.npoints) {
return false;
}
if (!Arrays.equals(p1.xpoints, p2.xpoints)) {
return false;
}
if (!Arrays.equals(p1.ypoints, p2.ypoints)) {
return false;
}
return true;
}
/**
* Tests two polygons for equality. If both are <code>null</code> this
* method returns <code>true</code>.
*
* @param p1 path 1 (<code>null</code> permitted).
* @param p2 path 2 (<code>null</code> permitted).
*
* @return A boolean.
*/
public static boolean equal(final GeneralPath p1, final GeneralPath p2) {
if (p1 == null) {
return (p2 == null);
}
if (p2 == null) {
return false;
}
if (p1.getWindingRule() != p2.getWindingRule()) {
return false;
}
PathIterator iterator1 = p1.getPathIterator(null);
PathIterator iterator2 = p2.getPathIterator(null);
double[] d1 = new double[6];
double[] d2 = new double[6];
boolean done = iterator1.isDone() && iterator2.isDone();
while (!done) {
if (iterator1.isDone() != iterator2.isDone()) {
return false;
}
int seg1 = iterator1.currentSegment(d1);
int seg2 = iterator2.currentSegment(d2);
if (seg1 != seg2) {
return false;
}
if (!Arrays.equals(d1, d2)) {
return false;
}
iterator1.next();
iterator2.next();
done = iterator1.isDone() && iterator2.isDone();
}
return true;
}
/**
* Creates and returns a translated shape.
*
* @param shape the shape (<code>null</code> not permitted).
* @param transX the x translation (in Java2D space).
* @param transY the y translation (in Java2D space).
*
* @return The translated shape.
*/
public static Shape createTranslatedShape(final Shape shape,
final double transX,
final double transY) {
if (shape == null) {
throw new IllegalArgumentException("Null 'shape' argument.");
}
final AffineTransform transform = AffineTransform.getTranslateInstance(
transX, transY);
return transform.createTransformedShape(shape);
}
/**
* Translates a shape to a new location such that the anchor point
* (relative to the rectangular bounds of the shape) aligns with the
* specified (x, y) coordinate in Java2D space.
*
* @param shape the shape (<code>null</code> not permitted).
* @param anchor the anchor (<code>null</code> not permitted).
* @param locationX the x-coordinate (in Java2D space).
* @param locationY the y-coordinate (in Java2D space).
*
* @return A new and translated shape.
*/
public static Shape createTranslatedShape(final Shape shape,
final RectangleAnchor anchor,
final double locationX,
final double locationY) {
if (shape == null) {
throw new IllegalArgumentException("Null 'shape' argument.");
}
if (anchor == null) {
throw new IllegalArgumentException("Null 'anchor' argument.");
}
Point2D anchorPoint = RectangleAnchor.coordinates(
shape.getBounds2D(), anchor);
final AffineTransform transform = AffineTransform.getTranslateInstance(
locationX - anchorPoint.getX(), locationY - anchorPoint.getY());
return transform.createTransformedShape(shape);
}
/**
* Rotates a shape about the specified coordinates.
*
* @param base the shape (<code>null</code> permitted, returns
* <code>null</code>).
* @param angle the angle (in radians).
* @param x the x coordinate for the rotation point (in Java2D space).
* @param y the y coordinate for the rotation point (in Java2D space).
*
* @return the rotated shape.
*/
public static Shape rotateShape(final Shape base, final double angle,
final float x, final float y) {
if (base == null) {
return null;
}
final AffineTransform rotate = AffineTransform.getRotateInstance(
angle, x, y);
final Shape result = rotate.createTransformedShape(base);
return result;
}
/**
* Draws a shape with the specified rotation about <code>(x, y)</code>.
*
* @param g2 the graphics device (<code>null</code> not permitted).
* @param shape the shape (<code>null</code> not permitted).
* @param angle the angle (in radians).
* @param x the x coordinate for the rotation point.
* @param y the y coordinate for the rotation point.
*/
public static void drawRotatedShape(final Graphics2D g2, final Shape shape,
final double angle,
final float x, final float y) {
final AffineTransform saved = g2.getTransform();
final AffineTransform rotate = AffineTransform.getRotateInstance(
angle, x, y);
g2.transform(rotate);
g2.draw(shape);
g2.setTransform(saved);
}
/** A useful constant used internally. */
private static final float SQRT2 = (float) Math.pow(2.0, 0.5);
/**
* Creates a diagonal cross shape.
*
* @param l the length of each 'arm'.
* @param t the thickness.
*
* @return A diagonal cross shape.
*/
public static Shape createDiagonalCross(final float l, final float t) {
final GeneralPath p0 = new GeneralPath();
p0.moveTo(-l - t, -l + t);
p0.lineTo(-l + t, -l - t);
p0.lineTo(0.0f, -t * SQRT2);
p0.lineTo(l - t, -l - t);
p0.lineTo(l + t, -l + t);
p0.lineTo(t * SQRT2, 0.0f);
p0.lineTo(l + t, l - t);
p0.lineTo(l - t, l + t);
p0.lineTo(0.0f, t * SQRT2);
p0.lineTo(-l + t, l + t);
p0.lineTo(-l - t, l - t);
p0.lineTo(-t * SQRT2, 0.0f);
p0.closePath();
return p0;
}
/**
* Creates a diagonal cross shape.
*
* @param l the length of each 'arm'.
* @param t the thickness.
*
* @return A diagonal cross shape.
*/
public static Shape createRegularCross(final float l, final float t) {
final GeneralPath p0 = new GeneralPath();
p0.moveTo(-l, t);
p0.lineTo(-t, t);
p0.lineTo(-t, l);
p0.lineTo(t, l);
p0.lineTo(t, t);
p0.lineTo(l, t);
p0.lineTo(l, -t);
p0.lineTo(t, -t);
p0.lineTo(t, -l);
p0.lineTo(-t, -l);
p0.lineTo(-t, -t);
p0.lineTo(-l, -t);
p0.closePath();
return p0;
}
/**
* Creates a diamond shape.
*
* @param s the size factor (equal to half the height of the diamond).
*
* @return A diamond shape.
*/
public static Shape createDiamond(final float s) {
final GeneralPath p0 = new GeneralPath();
p0.moveTo(0.0f, -s);
p0.lineTo(s, 0.0f);
p0.lineTo(0.0f, s);
p0.lineTo(-s, 0.0f);
p0.closePath();
return p0;
}
/**
* Creates a triangle shape that points upwards.
*
* @param s the size factor (equal to half the height of the triangle).
*
* @return A triangle shape.
*/
public static Shape createUpTriangle(final float s) {
final GeneralPath p0 = new GeneralPath();
p0.moveTo(0.0f, -s);
p0.lineTo(s, s);
p0.lineTo(-s, s);
p0.closePath();
return p0;
}
/**
* Creates a triangle shape that points downwards.
*
* @param s the size factor (equal to half the height of the triangle).
*
* @return A triangle shape.
*/
public static Shape createDownTriangle(final float s) {
final GeneralPath p0 = new GeneralPath();
p0.moveTo(0.0f, s);
p0.lineTo(s, -s);
p0.lineTo(-s, -s);
p0.closePath();
return p0;
}
/**
* Creates a region surrounding a line segment by 'widening' the line
* segment. A typical use for this method is the creation of a
* 'clickable' region for a line that is displayed on-screen.
*
* @param line the line (<code>null</code> not permitted).
* @param width the width of the region.
*
* @return A region that surrounds the line.
*/
public static Shape createLineRegion(final Line2D line, final float width) {
final GeneralPath result = new GeneralPath();
final float x1 = (float) line.getX1();
final float x2 = (float) line.getX2();
final float y1 = (float) line.getY1();
final float y2 = (float) line.getY2();
if ((x2 - x1) != 0.0) {
final double theta = Math.atan((y2 - y1) / (x2 - x1));
final float dx = (float) Math.sin(theta) * width;
final float dy = (float) Math.cos(theta) * width;
result.moveTo(x1 - dx, y1 + dy);
result.lineTo(x1 + dx, y1 - dy);
result.lineTo(x2 + dx, y2 - dy);
result.lineTo(x2 - dx, y2 + dy);
result.closePath();
}
else {
// special case, vertical line
result.moveTo(x1 - width / 2.0f, y1);
result.lineTo(x1 + width / 2.0f, y1);
result.lineTo(x2 + width / 2.0f, y2);
result.lineTo(x2 - width / 2.0f, y2);
result.closePath();
}
return result;
}
/**
* Returns a point based on (x, y) but constrained to be within the bounds
* of a given rectangle.
*
* @param x the x-coordinate.
* @param y the y-coordinate.
* @param area the constraining rectangle (<code>null</code> not
* permitted).
*
* @return A point within the rectangle.
*
* @throws NullPointerException if <code>area</code> is <code>null</code>.
*/
public static Point2D getPointInRectangle(double x, double y,
final Rectangle2D area) {
x = Math.max(area.getMinX(), Math.min(x, area.getMaxX()));
y = Math.max(area.getMinY(), Math.min(y, area.getMaxY()));
return new Point2D.Double(x, y);
}
/**
* Checks, whether the given rectangle1 fully contains rectangle 2
* (even if rectangle 2 has a height or width of zero!).
*
* @param rect1 the first rectangle.
* @param rect2 the second rectangle.
*
* @return A boolean.
*/
public static boolean contains(final Rectangle2D rect1,
final Rectangle2D rect2) {
final double x0 = rect1.getX();
final double y0 = rect1.getY();
final double x = rect2.getX();
final double y = rect2.getY();
final double w = rect2.getWidth();
final double h = rect2.getHeight();
return ((x >= x0) && (y >= y0)
&& ((x + w) <= (x0 + rect1.getWidth()))
&& ((y + h) <= (y0 + rect1.getHeight())));
}
/**
* Checks, whether the given rectangle1 fully contains rectangle 2
* (even if rectangle 2 has a height or width of zero!).
*
* @param rect1 the first rectangle.
* @param rect2 the second rectangle.
*
* @return A boolean.
*/
public static boolean intersects (final Rectangle2D rect1,
final Rectangle2D rect2) {
final double x0 = rect1.getX();
final double y0 = rect1.getY();
final double x = rect2.getX();
final double width = rect2.getWidth();
final double y = rect2.getY();
final double height = rect2.getHeight();
return (x + width >= x0 && y + height >= y0 && x <= x0 + rect1.getWidth()
&& y <= y0 + rect1.getHeight());
}
}
| 20,558 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
RelativeDateFormat.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/util/RelativeDateFormat.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.]
*
* -----------------------
* RelativeDateFormat.java
* -----------------------
* (C) Copyright 2006-2008, by Object Refinery Limited and Contributors.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): Michael Siemer;
*
* Changes:
* --------
* 01-Nov-2006 : Version 1 (DG);
* 23-Nov-2006 : Added argument checks, updated equals(), added clone() and
* hashCode() (DG);
* 15-Feb-2008 : Applied patch 1873328 by Michael Siemer, with minor
* modifications (DG);
* 01-Sep-2008 : Added new fields for hour and minute formatting, based on
* patch 2033092 (DG);
*
*/
package org.jfree.chart.util;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.FieldPosition;
import java.text.NumberFormat;
import java.text.ParsePosition;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
/**
* A formatter that formats dates to show the elapsed time relative to some
* base date.
*
* @since 1.0.3
*/
public class RelativeDateFormat extends DateFormat {
/** The base milliseconds for the elapsed time calculation. */
private long baseMillis;
/**
* A flag that controls whether or not a zero day count is displayed.
*/
private boolean showZeroDays;
/**
* A flag that controls whether or not a zero hour count is displayed.
*
* @since 1.0.10
*/
private boolean showZeroHours;
/**
* A formatter for the day count (most likely not critical until the
* day count exceeds 999).
*/
private NumberFormat dayFormatter;
/**
* A prefix prepended to the start of the format if the relative date is
* positive.
*
* @since 1.0.10
*/
private String positivePrefix;
/**
* A string appended after the day count.
*/
private String daySuffix;
/**
* A formatter for the hours.
*
* @since 1.0.11
*/
private NumberFormat hourFormatter;
/**
* A string appended after the hours.
*/
private String hourSuffix;
/**
* A formatter for the minutes.
*
* @since 1.0.11
*/
private NumberFormat minuteFormatter;
/**
* A string appended after the minutes.
*/
private String minuteSuffix;
/**
* A formatter for the seconds (and milliseconds).
*/
private NumberFormat secondFormatter;
/**
* A string appended after the seconds.
*/
private String secondSuffix;
/**
* A constant for the number of milliseconds in one hour.
*/
private static long MILLISECONDS_IN_ONE_HOUR = 60 * 60 * 1000L;
/**
* A constant for the number of milliseconds in one day.
*/
private static long MILLISECONDS_IN_ONE_DAY = 24 * MILLISECONDS_IN_ONE_HOUR;
/**
* Creates a new instance with base milliseconds set to zero.
*/
public RelativeDateFormat() {
this(0L);
}
/**
* Creates a new instance.
*
* @param time the date/time (<code>null</code> not permitted).
*/
public RelativeDateFormat(Date time) {
this(time.getTime());
}
/**
* Creates a new instance.
*
* @param baseMillis the time zone (<code>null</code> not permitted).
*/
public RelativeDateFormat(long baseMillis) {
super();
this.baseMillis = baseMillis;
this.showZeroDays = false;
this.showZeroHours = true;
this.positivePrefix = "";
this.dayFormatter = NumberFormat.getNumberInstance();
this.daySuffix = "d";
this.hourFormatter = NumberFormat.getNumberInstance();
this.hourSuffix = "h";
this.minuteFormatter = NumberFormat.getNumberInstance();
this.minuteSuffix = "m";
this.secondFormatter = NumberFormat.getNumberInstance();
this.secondFormatter.setMaximumFractionDigits(3);
this.secondFormatter.setMinimumFractionDigits(3);
this.secondSuffix = "s";
// we don't use the calendar or numberFormat fields, but equals(Object)
// is failing without them being non-null
this.calendar = new GregorianCalendar();
this.numberFormat = new DecimalFormat("0");
}
/**
* Returns the base date/time used to calculate the elapsed time for
* display.
*
* @return The base date/time in milliseconds since 1-Jan-1970.
*
* @see #setBaseMillis(long)
*/
public long getBaseMillis() {
return this.baseMillis;
}
/**
* Sets the base date/time used to calculate the elapsed time for display.
* This should be specified in milliseconds using the same encoding as
* <code>java.util.Date</code>.
*
* @param baseMillis the base date/time in milliseconds.
*
* @see #getBaseMillis()
*/
public void setBaseMillis(long baseMillis) {
this.baseMillis = baseMillis;
}
/**
* Returns the flag that controls whether or not zero day counts are
* shown in the formatted output.
*
* @return The flag.
*
* @see #setShowZeroDays(boolean)
*/
public boolean getShowZeroDays() {
return this.showZeroDays;
}
/**
* Sets the flag that controls whether or not zero day counts are shown
* in the formatted output.
*
* @param show the flag.
*
* @see #getShowZeroDays()
*/
public void setShowZeroDays(boolean show) {
this.showZeroDays = show;
}
/**
* Returns the flag that controls whether or not zero hour counts are
* shown in the formatted output.
*
* @return The flag.
*
* @see #setShowZeroHours(boolean)
*
* @since 1.0.10
*/
public boolean getShowZeroHours() {
return this.showZeroHours;
}
/**
* Sets the flag that controls whether or not zero hour counts are shown
* in the formatted output.
*
* @param show the flag.
*
* @see #getShowZeroHours()
*
* @since 1.0.10
*/
public void setShowZeroHours(boolean show) {
this.showZeroHours = show;
}
/**
* Returns the string that is prepended to the format if the relative time
* is positive.
*
* @return The string (never <code>null</code>).
*
* @see #setPositivePrefix(String)
*
* @since 1.0.10
*/
public String getPositivePrefix() {
return this.positivePrefix;
}
/**
* Sets the string that is prepended to the format if the relative time is
* positive.
*
* @param prefix the prefix (<code>null</code> not permitted).
*
* @see #getPositivePrefix()
*
* @since 1.0.10
*/
public void setPositivePrefix(String prefix) {
if (prefix == null) {
throw new IllegalArgumentException("Null 'prefix' argument.");
}
this.positivePrefix = prefix;
}
/**
* Sets the formatter for the days.
*
* @param formatter the formatter (<code>null</code> not permitted).
*
* @since 1.0.11
*/
public void setDayFormatter(NumberFormat formatter) {
if (formatter == null) {
throw new IllegalArgumentException("Null 'formatter' argument.");
}
this.dayFormatter = formatter;
}
/**
* Returns the string that is appended to the day count.
*
* @return The string.
*
* @see #setDaySuffix(String)
*/
public String getDaySuffix() {
return this.daySuffix;
}
/**
* Sets the string that is appended to the day count.
*
* @param suffix the suffix (<code>null</code> not permitted).
*
* @see #getDaySuffix()
*/
public void setDaySuffix(String suffix) {
if (suffix == null) {
throw new IllegalArgumentException("Null 'suffix' argument.");
}
this.daySuffix = suffix;
}
/**
* Sets the formatter for the hours.
*
* @param formatter the formatter (<code>null</code> not permitted).
*
* @since 1.0.11
*/
public void setHourFormatter(NumberFormat formatter) {
if (formatter == null) {
throw new IllegalArgumentException("Null 'formatter' argument.");
}
this.hourFormatter = formatter;
}
/**
* Returns the string that is appended to the hour count.
*
* @return The string.
*
* @see #setHourSuffix(String)
*/
public String getHourSuffix() {
return this.hourSuffix;
}
/**
* Sets the string that is appended to the hour count.
*
* @param suffix the suffix (<code>null</code> not permitted).
*
* @see #getHourSuffix()
*/
public void setHourSuffix(String suffix) {
if (suffix == null) {
throw new IllegalArgumentException("Null 'suffix' argument.");
}
this.hourSuffix = suffix;
}
/**
* Sets the formatter for the minutes.
*
* @param formatter the formatter (<code>null</code> not permitted).
*
* @since 1.0.11
*/
public void setMinuteFormatter(NumberFormat formatter) {
if (formatter == null) {
throw new IllegalArgumentException("Null 'formatter' argument.");
}
this.minuteFormatter = formatter;
}
/**
* Returns the string that is appended to the minute count.
*
* @return The string.
*
* @see #setMinuteSuffix(String)
*/
public String getMinuteSuffix() {
return this.minuteSuffix;
}
/**
* Sets the string that is appended to the minute count.
*
* @param suffix the suffix (<code>null</code> not permitted).
*
* @see #getMinuteSuffix()
*/
public void setMinuteSuffix(String suffix) {
if (suffix == null) {
throw new IllegalArgumentException("Null 'suffix' argument.");
}
this.minuteSuffix = suffix;
}
/**
* Returns the string that is appended to the second count.
*
* @return The string.
*
* @see #setSecondSuffix(String)
*/
public String getSecondSuffix() {
return this.secondSuffix;
}
/**
* Sets the string that is appended to the second count.
*
* @param suffix the suffix (<code>null</code> not permitted).
*
* @see #getSecondSuffix()
*/
public void setSecondSuffix(String suffix) {
if (suffix == null) {
throw new IllegalArgumentException("Null 'suffix' argument.");
}
this.secondSuffix = suffix;
}
/**
* Sets the formatter for the seconds and milliseconds.
*
* @param formatter the formatter (<code>null</code> not permitted).
*/
public void setSecondFormatter(NumberFormat formatter) {
if (formatter == null) {
throw new IllegalArgumentException("Null 'formatter' argument.");
}
this.secondFormatter = formatter;
}
/**
* Formats the given date as the amount of elapsed time (relative to the
* base date specified in the constructor).
*
* @param date the date.
* @param toAppendTo the string buffer.
* @param fieldPosition the field position.
*
* @return The formatted date.
*/
@Override
public StringBuffer format(Date date, StringBuffer toAppendTo,
FieldPosition fieldPosition) {
long currentMillis = date.getTime();
long elapsed = currentMillis - this.baseMillis;
String signPrefix;
if (elapsed < 0) {
elapsed *= -1L;
signPrefix = "-";
}
else {
signPrefix = this.positivePrefix;
}
long days = elapsed / MILLISECONDS_IN_ONE_DAY;
elapsed = elapsed - (days * MILLISECONDS_IN_ONE_DAY);
long hours = elapsed / MILLISECONDS_IN_ONE_HOUR;
elapsed = elapsed - (hours * MILLISECONDS_IN_ONE_HOUR);
long minutes = elapsed / 60000L;
elapsed = elapsed - (minutes * 60000L);
double seconds = elapsed / 1000.0;
toAppendTo.append(signPrefix);
if (days != 0 || this.showZeroDays) {
toAppendTo.append(this.dayFormatter.format(days) + getDaySuffix());
}
if (hours != 0 || this.showZeroHours) {
toAppendTo.append(this.hourFormatter.format(hours)
+ getHourSuffix());
}
toAppendTo.append(this.minuteFormatter.format(minutes)
+ getMinuteSuffix());
toAppendTo.append(this.secondFormatter.format(seconds)
+ getSecondSuffix());
return toAppendTo;
}
/**
* Parses the given string (not implemented).
*
* @param source the date string.
* @param pos the parse position.
*
* @return <code>null</code>, as this method has not been implemented.
*/
@Override
public Date parse(String source, ParsePosition pos) {
return null;
}
/**
* Tests this formatter 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 RelativeDateFormat)) {
return false;
}
if (!super.equals(obj)) {
return false;
}
RelativeDateFormat that = (RelativeDateFormat) obj;
if (this.baseMillis != that.baseMillis) {
return false;
}
if (this.showZeroDays != that.showZeroDays) {
return false;
}
if (this.showZeroHours != that.showZeroHours) {
return false;
}
if (!this.positivePrefix.equals(that.positivePrefix)) {
return false;
}
if (!this.daySuffix.equals(that.daySuffix)) {
return false;
}
if (!this.hourSuffix.equals(that.hourSuffix)) {
return false;
}
if (!this.minuteSuffix.equals(that.minuteSuffix)) {
return false;
}
if (!this.secondSuffix.equals(that.secondSuffix)) {
return false;
}
if (!this.dayFormatter.equals(that.dayFormatter)) {
return false;
}
if (!this.hourFormatter.equals(that.hourFormatter)) {
return false;
}
if (!this.minuteFormatter.equals(that.minuteFormatter)) {
return false;
}
if (!this.secondFormatter.equals(that.secondFormatter)) {
return false;
}
return true;
}
/**
* Returns a hash code for this instance.
*
* @return A hash code.
*/
@Override
public int hashCode() {
int result = 193;
result = 37 * result
+ (int) (this.baseMillis ^ (this.baseMillis >>> 32));
result = 37 * result + this.positivePrefix.hashCode();
result = 37 * result + this.daySuffix.hashCode();
result = 37 * result + this.hourSuffix.hashCode();
result = 37 * result + this.minuteSuffix.hashCode();
result = 37 * result + this.secondSuffix.hashCode();
result = 37 * result + this.secondFormatter.hashCode();
return result;
}
/**
* Returns a clone of this instance.
*
* @return A clone.
*/
@Override
public Object clone() {
RelativeDateFormat clone = (RelativeDateFormat) super.clone();
clone.dayFormatter = (NumberFormat) this.dayFormatter.clone();
clone.secondFormatter = (NumberFormat) this.secondFormatter.clone();
return clone;
}
/**
* Some test code.
*
* @param args ignored.
*/
public static void main(String[] args) {
GregorianCalendar c0 = new GregorianCalendar(2006, 10, 1, 0, 0, 0);
GregorianCalendar c1 = new GregorianCalendar(2006, 10, 1, 11, 37, 43);
c1.set(Calendar.MILLISECOND, 123);
System.out.println("Default: ");
RelativeDateFormat rdf = new RelativeDateFormat(c0.getTimeInMillis());
System.out.println(rdf.format(c1.getTime()));
System.out.println();
System.out.println("Hide milliseconds: ");
rdf.setSecondFormatter(new DecimalFormat("0"));
System.out.println(rdf.format(c1.getTime()));
System.out.println();
System.out.println("Show zero day output: ");
rdf.setShowZeroDays(true);
System.out.println(rdf.format(c1.getTime()));
System.out.println();
System.out.println("Alternative suffixes: ");
rdf.setShowZeroDays(false);
rdf.setDaySuffix(":");
rdf.setHourSuffix(":");
rdf.setMinuteSuffix(":");
rdf.setSecondSuffix("");
System.out.println(rdf.format(c1.getTime()));
System.out.println();
}
}
| 18,210 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
ObjectList.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/util/ObjectList.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.]
*
* ---------------
* ObjectList.java
* ---------------
* (C)opyright 2003-2012, by Object Refinery Limited and Contributors.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 17-Jul-2003 : Version 1 (DG);
* 13-Aug-2003 : Refactored to extend AbstractObjectList (DG);
* 21-Oct-2004 : removed duplicate interface declarations and empty methods.
* 22-Oct-2004 : Restored removed methods - see note in code (DG);
* 16-Jun-2012 : Moved from JCommon to JFreeChart (DG);
*
*/
package org.jfree.chart.util;
/**
* A list of objects that can grow as required.
* <p>
* When cloning, the objects in the list are NOT cloned, only the references.
*/
public class ObjectList<T> extends AbstractObjectList<T> {
/**
* Default constructor.
*/
public ObjectList() {
}
/**
* Creates a new list.
*
* @param initialCapacity the initial capacity.
*/
public ObjectList(final int initialCapacity) {
super(initialCapacity);
}
// NOTE: the methods below look redundant, but their purpose is to provide public
// access to the the get(), set() and indexOf() methods defined in the
// AbstractObjectList class, for this class only. For other classes
// (e.g. PaintList, ShapeList etc) we don't want the Object versions of these
// methods to be visible in the public API.
/**
* Returns the object at the specified index, if there is one, or <code>null</code>.
*
* @param index the object index.
*
* @return The object or <code>null</code>.
*/
@Override
public T get(final int index) {
return super.get(index);
}
/**
* Sets an object reference (overwriting any existing object).
*
* @param index the object index.
* @param object the object (<code>null</code> permitted).
*/
@Override
public void set(final int index, final T object) {
super.set(index, object);
}
/**
* Returns the index of the specified object, or -1 if the object is not in the list.
*
* @param object the object.
*
* @return The index or -1.
*/
@Override
public int indexOf(final T object) {
return super.indexOf(object);
}
}
| 3,528 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
LogFormat.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/util/LogFormat.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.]
*
* --------------
* LogFormat.java
* --------------
* (C) Copyright 2007-2009, by Object Refinery Limited and Contributors.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 02-Aug-2007 : Version 1 (DG);
* 19-Feb-2008 : Implemented equals() and clone(), and added new powerLabel
* attribute as per Feature Request 1886036 (DG);
* 14-Jan-2009 : Added default constructor, and accessor methods for
* exponent formatter (DG);
*
*/
package org.jfree.chart.util;
import java.text.DecimalFormat;
import java.text.FieldPosition;
import java.text.NumberFormat;
import java.text.ParsePosition;
/**
* A number formatter for logarithmic values. This formatter does not support
* parsing.
*
* @since 1.0.7
*/
public class LogFormat extends NumberFormat {
/** The log base value. */
private double base;
/** The natural logarithm of the base value. */
private double baseLog;
/** The label for the log base (for example, "e"). */
private String baseLabel;
/**
* The label for the power symbol.
*
* @since 1.0.10
*/
private String powerLabel;
/** A flag that controls whether or not the base is shown. */
private boolean showBase;
/** The number formatter for the exponent. */
private NumberFormat formatter = new DecimalFormat("0.0#");
/**
* Creates a new instance using base 10.
*
* @since 1.0.13
*/
public LogFormat() {
this(10.0, "10", true);
}
/**
* Creates a new instance.
*
* @param base the base.
* @param baseLabel the base label (<code>null</code> not permitted).
* @param showBase a flag that controls whether or not the base value is
* shown.
*/
public LogFormat(double base, String baseLabel, boolean showBase) {
this(base, baseLabel, "^", showBase);
}
/**
* Creates a new instance.
*
* @param base the base.
* @param baseLabel the base label (<code>null</code> not permitted).
* @param powerLabel the power label (<code>null</code> not permitted).
* @param showBase a flag that controls whether or not the base value is
* shown.
*
* @since 1.0.10
*/
public LogFormat(double base, String baseLabel, String powerLabel,
boolean showBase) {
if (baseLabel == null) {
throw new IllegalArgumentException("Null 'baseLabel' argument.");
}
if (powerLabel == null) {
throw new IllegalArgumentException("Null 'powerLabel' argument.");
}
this.base = base;
this.baseLog = Math.log(this.base);
this.baseLabel = baseLabel;
this.showBase = showBase;
this.powerLabel = powerLabel;
}
/**
* Returns the number format used for the exponent.
*
* @return The number format (never <code>null</code>).
*
* @since 1.0.13.
*/
public NumberFormat getExponentFormat() {
return (NumberFormat) this.formatter.clone();
}
/**
* Sets the number format used for the exponent.
*
* @param format the formatter (<code>null</code> not permitted).
*
* @since 1.0.13
*/
public void setExponentFormat(NumberFormat format) {
if (format == null) {
throw new IllegalArgumentException("Null 'format' argument.");
}
this.formatter = format;
}
/**
* Calculates the log of a given value.
*
* @param value the value.
*
* @return The log of the value.
*/
private double calculateLog(double value) {
return Math.log(value) / this.baseLog;
}
/**
* Returns a formatted representation of the specified number.
*
* @param number the number.
* @param toAppendTo the string buffer to append to.
* @param pos the position.
*
* @return A string buffer containing the formatted value.
*/
@Override
public StringBuffer format(double number, StringBuffer toAppendTo,
FieldPosition pos) {
StringBuffer result = new StringBuffer();
if (this.showBase) {
result.append(this.baseLabel);
result.append(this.powerLabel);
}
result.append(this.formatter.format(calculateLog(number)));
return result;
}
/**
* Formats the specified number as a hexadecimal string. The decimal
* fraction is ignored.
*
* @param number the number to format.
* @param toAppendTo the buffer to append to (ignored here).
* @param pos the field position (ignored here).
*
* @return The string buffer.
*/
@Override
public StringBuffer format(long number, StringBuffer toAppendTo,
FieldPosition pos) {
StringBuffer result = new StringBuffer();
if (this.showBase) {
result.append(this.baseLabel);
result.append(this.powerLabel);
}
result.append(this.formatter.format(calculateLog(number)));
return result;
}
/**
* Parsing is not implemented, so this method always returns
* <code>null</code>.
*
* @param source ignored.
* @param parsePosition ignored.
*
* @return Always <code>null</code>.
*/
@Override
public Number parse (String source, ParsePosition parsePosition) {
return null; // don't bother with parsing
}
/**
* Tests this formatter 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 LogFormat)) {
return false;
}
LogFormat that = (LogFormat) obj;
if (this.base != that.base) {
return false;
}
if (!this.baseLabel.equals(that.baseLabel)) {
return false;
}
if (this.baseLog != that.baseLog) {
return false;
}
if (this.showBase != that.showBase) {
return false;
}
if (!this.formatter.equals(that.formatter)) {
return false;
}
return super.equals(obj);
}
/**
* Returns a clone of this instance.
*
* @return A clone.
*/
@Override
public Object clone() {
LogFormat clone = (LogFormat) super.clone();
clone.formatter = (NumberFormat) this.formatter.clone();
return clone;
}
}
| 7,923 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
ShadowGenerator.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/util/ShadowGenerator.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.]
*
* --------------------
* ShadowGenerator.java
* --------------------
* (C) Copyright 2009, 2011, by Object Refinery Limited and Contributors.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes:
* --------
* 10-Jul-2009 : Version 1 (DG);
*
*/
package org.jfree.chart.util;
import java.awt.image.BufferedImage;
/**
* An interface that defines the API for a shadow generator. Some plot
* classes use this to create drop shadows.
*
* @since 1.0.14
*/
public interface ShadowGenerator {
/**
* Creates and returns an image containing the drop shadow for the
* specified source image.
*
* @param source the source image.
*
* @return A new image containing the shadow.
*/
public BufferedImage createDropShadow(BufferedImage source);
/**
* Calculates the x-offset for drawing the shadow image relative to the
* source.
*
* @return The x-offset.
*/
public int calculateOffsetX();
/**
* Calculates the y-offset for drawing the shadow image relative to the
* source.
*
* @return The y-offset.
*/
public int calculateOffsetY();
}
| 2,428 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
XYCoordinateType.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/util/XYCoordinateType.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.]
*
* ---------------------
* XYCoordinateType.java
* ---------------------
* (C) Copyright 2007, 2008 by Object Refinery Limited and Contributors.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 02-Feb-2007 : Version 1 (DG);
* 03-Sep-2008 : Moved from experimental to main (DG);
*
*/
package org.jfree.chart.util;
/**
* Represents several possible interpretations for an (x, y) coordinate.
*
* @since 1.0.11
*/
public enum XYCoordinateType {
/** The (x, y) coordinates represent a point in the data space. */
DATA("XYCoordinateType.DATA"),
/**
* The (x, y) coordinates represent a relative position in the data space.
* In this case, the values should be in the range (0.0 to 1.0).
*/
RELATIVE("XYCoordinateType.RELATIVE"),
/**
* The (x, y) coordinates represent indices in a dataset.
* In this case, the values should be in the range (0.0 to 1.0).
*/
INDEX("XYCoordinateType.INDEX");
/** The name. */
private String name;
/**
* Private constructor.
*
* @param name the name.
*/
private XYCoordinateType(String name) {
this.name = name;
}
/**
* Returns a string representing the object.
*
* @return The string.
*/
@Override
public String toString() {
return this.name;
}
}
| 2,633 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
UnitType.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/util/UnitType.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.]
*
* -------------
* UnitType.java
* -------------
* (C) Copyright 2004-2012, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes:
* --------
* 11-Feb-2004 : Version 1 (DG);
*
*/
package org.jfree.chart.util;
/**
* Used to indicate absolute or relative units.
*/
public enum UnitType {
/** Absolute. */
ABSOLUTE("UnitType.ABSOLUTE"),
/** Relative. */
RELATIVE("UnitType.RELATIVE");
/** The name. */
private String name;
/**
* Private constructor.
*
* @param name the name.
*/
private UnitType(final String name) {
this.name = name;
}
/**
* Returns a string representing the object.
*
* @return The string.
*/
@Override
public String toString() {
return this.name;
}
}
| 2,098 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
LineUtilities.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/util/LineUtilities.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.]
*
* ------------------
* LineUtilities.java
* ------------------
* (C) Copyright 2008, 2014, by Object Refinery Limited and Contributors.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 05-Nov-2008 : Version 1 (DG);
* 28-Feb-2014 : Added extendLine() (DG);
*
*/
package org.jfree.chart.util;
import java.awt.geom.Line2D;
import java.awt.geom.Rectangle2D;
/**
* Some utility methods for {@link Line2D} objects.
*
* @since 1.0.12
*/
public class LineUtilities {
/**
* Clips the specified line to the given rectangle.
*
* @param line the line (<code>null</code> not permitted).
* @param rect the clipping rectangle (<code>null</code> not permitted).
*
* @return <code>true</code> if the clipped line is visible, and
* <code>false</code> otherwise.
*/
public static boolean clipLine(Line2D line, Rectangle2D rect) {
double x1 = line.getX1();
double y1 = line.getY1();
double x2 = line.getX2();
double y2 = line.getY2();
double minX = rect.getMinX();
double maxX = rect.getMaxX();
double minY = rect.getMinY();
double maxY = rect.getMaxY();
int f1 = rect.outcode(x1, y1);
int f2 = rect.outcode(x2, y2);
while ((f1 | f2) != 0) {
if ((f1 & f2) != 0) {
return false;
}
double dx = (x2 - x1);
double dy = (y2 - y1);
// update (x1, y1), (x2, y2) and f1 and f2 using intersections
// then recheck
if (f1 != 0) {
// first point is outside, so we update it against one of the
// four sides then continue
if ((f1 & Rectangle2D.OUT_LEFT) == Rectangle2D.OUT_LEFT
&& dx != 0.0) {
y1 = y1 + (minX - x1) * dy / dx;
x1 = minX;
}
else if ((f1 & Rectangle2D.OUT_RIGHT) == Rectangle2D.OUT_RIGHT
&& dx != 0.0) {
y1 = y1 + (maxX - x1) * dy / dx;
x1 = maxX;
}
else if ((f1 & Rectangle2D.OUT_BOTTOM) == Rectangle2D.OUT_BOTTOM
&& dy != 0.0) {
x1 = x1 + (maxY - y1) * dx / dy;
y1 = maxY;
}
else if ((f1 & Rectangle2D.OUT_TOP) == Rectangle2D.OUT_TOP
&& dy != 0.0) {
x1 = x1 + (minY - y1) * dx / dy;
y1 = minY;
}
f1 = rect.outcode(x1, y1);
}
else if (f2 != 0) {
// second point is outside, so we update it against one of the
// four sides then continue
if ((f2 & Rectangle2D.OUT_LEFT) == Rectangle2D.OUT_LEFT
&& dx != 0.0) {
y2 = y2 + (minX - x2) * dy / dx;
x2 = minX;
}
else if ((f2 & Rectangle2D.OUT_RIGHT) == Rectangle2D.OUT_RIGHT
&& dx != 0.0) {
y2 = y2 + (maxX - x2) * dy / dx;
x2 = maxX;
}
else if ((f2 & Rectangle2D.OUT_BOTTOM) == Rectangle2D.OUT_BOTTOM
&& dy != 0.0) {
x2 = x2 + (maxY - y2) * dx / dy;
y2 = maxY;
}
else if ((f2 & Rectangle2D.OUT_TOP) == Rectangle2D.OUT_TOP
&& dy != 0.0) {
x2 = x2 + (minY - y2) * dx / dy;
y2 = minY;
}
f2 = rect.outcode(x2, y2);
}
}
line.setLine(x1, y1, x2, y2);
return true; // the line is visible - if it wasn't, we'd have
// returned false from within the while loop above
}
/**
* Creates a new line by extending an existing line.
*
* @param line the line (<code>null</code> not permitted).
* @param startPercent the amount to extend the line at the start point
* end.
* @param endPercent the amount to extend the line at the end point end.
*
* @return A new line.
*
* @since 1.0.18
*/
public static Line2D extendLine(Line2D line, double startPercent,
double endPercent) {
ParamChecks.nullNotPermitted(line, "line");
double x1 = line.getX1();
double x2 = line.getX2();
double deltaX = x2 - x1;
double y1 = line.getY1();
double y2 = line.getY2();
double deltaY = y2 - y1;
x1 = x1 - (startPercent * deltaX);
y1 = y1 - (startPercent * deltaY);
x2 = x2 + (endPercent * deltaX);
y2 = y2 + (endPercent * deltaY);
return new Line2D.Double(x1, y1, x2, y2);
}
}
| 6,200 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
IDetailPanel.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/util/IDetailPanel.java | package org.jfree.chart.util;
public interface IDetailPanel {
void LoadDataToDetail(GanttParam ganttParam);
}
| 115 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
ObjectUtilities.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/util/ObjectUtilities.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.]
*
* ---------------------
* ObjectUtilitiess.java
* ---------------------
* (C) Copyright 2003-2013, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 25-Mar-2003 : Version 1 (DG);
* 15-Sep-2003 : Fixed bug in clone(List) method (DG);
* 25-Nov-2004 : Modified clone(Object) method to fail with objects that
* cannot be cloned, added new deepClone(Collection) method.
* Renamed ObjectUtils --> ObjectUtilities (DG);
* 11-Jan-2005 : Removed deprecated code in preparation for 1.0.0 release (DG);
* 18-Aug-2005 : Added casts to suppress compiler warnings, as suggested in
* patch 1260622 (DG);
* 16-Jun-2012 : Moved from JCommon to JFreeChart (DG);
*
*/
package org.jfree.chart.util;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Collection;
/**
* A collection of useful static utility methods for handling classes and object
* instantiation.
*/
public final class ObjectUtilities {
/**
* Default constructor - private.
*/
private ObjectUtilities() {
}
/**
* Returns <code>true</code> if the two objects are equal OR both
* <code>null</code>.
*
* @param o1 object 1 (<code>null</code> permitted).
* @param o2 object 2 (<code>null</code> permitted).
* @return <code>true</code> or <code>false</code>.
*/
public static boolean equal(final Object o1, final Object o2) {
if (o1 == o2) {
return true;
}
if (o1 != null) {
return o1.equals(o2);
}
else {
return false;
}
}
/**
* Returns a hash code for an object, or zero if the object is
* <code>null</code>.
*
* @param object the object (<code>null</code> permitted).
* @return The object's hash code (or zero if the object is
* <code>null</code>).
*/
public static int hashCode(final Object object) {
int result = 0;
if (object != null) {
result = object.hashCode();
}
return result;
}
/**
* Returns a clone of the specified object, if it can be cloned, otherwise
* throws a CloneNotSupportedException.
*
* @param object the object to clone (<code>null</code> not permitted).
* @return A clone of the specified object.
* @throws CloneNotSupportedException if the object cannot be cloned.
*/
public static <T> T clone(final T object)
throws CloneNotSupportedException {
if (object == null) {
throw new IllegalArgumentException("Null 'object' argument.");
}
if (object instanceof PublicCloneable) {
final PublicCloneable pc = (PublicCloneable) object;
return (T) pc.clone();
}
else {
try {
final Method method = object.getClass().getMethod("clone");
if (Modifier.isPublic(method.getModifiers())) {
return (T) method.invoke(object);
}
}
catch (NoSuchMethodException e) {
//Log.warn("Object without clone() method is impossible.");
}
catch (IllegalAccessException e) {
//Log.warn("Object.clone(): unable to call method.");
}
catch (InvocationTargetException e) {
//Log.warn("Object without clone() method is impossible.");
}
}
throw new CloneNotSupportedException("Failed to clone.");
}
/**
* Returns a new collection containing clones of all the items in the
* specified collection.
*
* @param collection the collection (<code>null</code> not permitted).
* @return A new collection containing clones of all the items in the
* specified collection.
* @throws CloneNotSupportedException if any of the items in the collection
* cannot be cloned.
*/
public static <T, C extends Collection<T>> C deepClone(final C collection)
throws CloneNotSupportedException {
if (collection == null) {
throw new IllegalArgumentException("Null 'collection' argument.");
}
// all JDK-Collections are cloneable ...
// and if the collection is not clonable, then we should throw
// a CloneNotSupportedException anyway ...
final C result = ObjectUtilities.clone(collection);
result.clear();
for (T item : collection) {
if (item == null) {
result.add(null);
} else {
result.add(clone(item));
}
}
return result;
}
}
| 6,089 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
BooleanList.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/util/BooleanList.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.]
*
* ----------------
* BooleanList.java
* ----------------
* (C) Copyright 2003-2012, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 11-Jun-2003 : Version 1 (DG);
* 23-Jul-2003 : Renamed BooleanTable --> BooleanList and now extends
* ObjectList (DG);
* 13-Aug-2003 : Now extends new class AbstractObjectList (DG);
* 21-Oct-2004 : Removed duplicate implementation of Cloneable and Serializable,
* AbstractObjectList already implements that.
* 14-Jun-2012 : Moved from JCommon to JFreeChart (DG);
*
*/
package org.jfree.chart.util;
/**
* A list of <code>Boolean</code> objects.
*/
public class BooleanList extends AbstractObjectList<Boolean> {
/** For serialization. */
private static final long serialVersionUID = -8543170333219422042L;
/**
* Creates a new list.
*/
public BooleanList() {
super();
}
/**
* Returns a {@link Boolean} from the list.
*
* @param index the index (zero-based).
*
* @return a {@link Boolean} from the list.
*/
public Boolean getBoolean(final int index) {
return get(index);
}
/**
* Sets the value for an item in the list. The list is expanded if
* necessary.
*
* @param index the index (zero-based).
* @param b the boolean.
*/
public void setBoolean(final int index, final Boolean b) {
set(index, b);
}
/**
* Tests the list for equality with another object (typically also a list).
*
* @param o the other object.
*
* @return A boolean.
*/
@Override
public boolean equals(final Object o) {
if (o instanceof BooleanList) {
return super.equals(o);
}
return false;
}
/**
* Returns a hash code value for the object.
*
* @return the hashcode
*/
@Override
public int hashCode() {
return super.hashCode();
}
}
| 3,277 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
StrokeList.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/util/StrokeList.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.]
*
* ---------------
* StrokeList.java
* ---------------
* (C) Copyright 2003-2012, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 19-Aug-2003 : Version 1 (DG);
* 17-Jun-2012 : Moved from JCommon to JFreeChart (DG);
*
*/
package org.jfree.chart.util;
import java.awt.Stroke;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
/**
* A table of {@link Stroke} objects.
*/
public class StrokeList extends AbstractObjectList<Stroke> {
/**
* Creates a new list.
*/
public StrokeList() {
super();
}
/**
* Returns a {@link Stroke} object from the list.
*
* @param index the index (zero-based).
*
* @return The object.
*/
public Stroke getStroke(final int index) {
return get(index);
}
/**
* Sets the {@link Stroke} for an item in the list. The list is expanded if necessary.
*
* @param index the index (zero-based).
* @param stroke the {@link Stroke}.
*/
public void setStroke(final int index, final Stroke stroke) {
set(index, stroke);
}
/**
* Returns an independent copy of the list.
*
* @return A clone.
*
* @throws CloneNotSupportedException if an item in the list cannot be cloned.
*/
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
/**
* Tests the list for equality with another object (typically also a list).
*
* @param o the other object.
*
* @return A boolean.
*/
@Override
public boolean equals(final Object o) {
if (o == null) {
return false;
}
if (o == this) {
return true;
}
if (o instanceof StrokeList) {
return super.equals(o);
}
return false;
}
/**
* Returns a hash code value for the object.
*
* @return the hashcode
*/
@Override
public int hashCode() {
return super.hashCode();
}
/**
* Provides serialization support.
*
* @param stream the output stream.
*
* @throws IOException if there is an I/O error.
*/
private void writeObject(final ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
final int count = size();
stream.writeInt(count);
for (int i = 0; i < count; i++) {
final Stroke stroke = getStroke(i);
if (stroke != null) {
stream.writeInt(i);
SerialUtilities.writeStroke(stroke, stream);
}
else {
stream.writeInt(-1);
}
}
}
/**
* 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(final ObjectInputStream stream) throws IOException, ClassNotFoundException {
stream.defaultReadObject();
final int count = stream.readInt();
for (int i = 0; i < count; i++) {
final int index = stream.readInt();
if (index != -1) {
setStroke(index, SerialUtilities.readStroke(stream));
}
}
}
}
| 4,714 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
ShapeList.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/util/ShapeList.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.]
*
* --------------
* ShapeList.java
* --------------
* (C) Copyright 2003-2012, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 13-Aug-2003 : Version 1 (DG);
* 17-Jun-2008 : Fixed bug in equals() (DG);
* 16-Jun-2012 : Moved from JCommon to JFreeChart (DG);
*
*/
package org.jfree.chart.util;
import java.awt.Shape;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
/**
* A table of {@link Shape} objects.
*/
public class ShapeList extends AbstractObjectList<Shape> {
/**
* Creates a new list.
*/
public ShapeList() {
super();
}
/**
* Returns a {@link Shape} object from the list.
*
* @param index the index (zero-based).
*
* @return The object.
*/
public Shape getShape(final int index) {
return get(index);
}
/**
* Sets the {@link Shape} for an item in the list. The list is expanded
* if necessary.
*
* @param index the index (zero-based).
* @param shape the {@link Shape}.
*/
public void setShape(final int index, final Shape shape) {
set(index, shape);
}
/**
* Returns an independent copy of the list.
*
* @return A clone.
*
* @throws CloneNotSupportedException if an item in the list does not
* support cloning.
*/
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
/**
* Tests the list for equality with another object (typically also a list).
*
* @param obj the other object (<code>null</code> permitted).
*
* @return A boolean.
*/
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof ShapeList)) {
return false;
}
ShapeList that = (ShapeList) obj;
int listSize = size();
for (int i = 0; i < listSize; i++) {
if (!ShapeUtilities.equal(get(i), that.get(i))) {
return false;
}
}
return true;
}
/**
* Returns a hash code value for the object.
*
* @return the hashcode
*/
@Override
public int hashCode() {
return super.hashCode();
}
/**
* Provides serialization support.
*
* @param stream the output stream.
*
* @throws IOException if there is an I/O error.
*/
private void writeObject(final ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
final int count = size();
stream.writeInt(count);
for (int i = 0; i < count; i++) {
final Shape shape = getShape(i);
if (shape != null) {
stream.writeInt(i);
SerialUtilities.writeShape(shape, stream);
}
else {
stream.writeInt(-1);
}
}
}
/**
* 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(final ObjectInputStream stream) throws IOException, ClassNotFoundException {
stream.defaultReadObject();
final int count = stream.readInt();
for (int i = 0; i < count; i++) {
final int index = stream.readInt();
if (index != -1) {
setShape(index, SerialUtilities.readShape(stream));
}
}
}
}
| 4,953 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
HMSNumberFormat.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/util/HMSNumberFormat.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.]
*
* --------------------
* HMSNumberFormat.java
* --------------------
* (C) Copyright 2013, by Object Refinery Limited and Contributors.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes:
* --------
* 28-Sep-2013 : Version 1 (RW);
*
*/
package org.jfree.chart.util;
import java.text.DecimalFormat;
import java.text.FieldPosition;
import java.text.NumberFormat;
import java.text.ParsePosition;
/**
* A custom number formatter that formats numbers (in seconds) as HH:MM:SS.
* Created in response to:
*
* http://stackoverflow.com/questions/19028908/jfreechart-need-to-customize-y-axis-just-for-printing
*
* @since 1.0.17
*/
public class HMSNumberFormat extends NumberFormat {
private NumberFormat formatter = new DecimalFormat("00");
/**
* Creates a new instance.
*/
public HMSNumberFormat() {
// nothing to do
}
/**
* Formats the specified number as a string of the form HH:MM:SS. The
* decimal fraction is ignored.
*
* @param number the number to format.
* @param toAppendTo the buffer to append to (ignored here).
* @param pos the field position (ignored here).
*
* @return The string buffer.
*/
@Override
public StringBuffer format(double number, StringBuffer toAppendTo,
FieldPosition pos) {
return format((long) number, toAppendTo, pos);
}
/**
* Formats the specified number as a string of the form HH:MM:SS.
*
* @param number the number to format.
* @param toAppendTo the buffer to append to (ignored here).
* @param pos the field position (ignored here).
*
* @return The string buffer.
*/
@Override
public StringBuffer format(long number, StringBuffer toAppendTo,
FieldPosition pos) {
StringBuffer sb = new StringBuffer();
long hours = number / 3600;
sb.append(this.formatter.format(hours)).append(":");
long remaining = number - (hours * 3600);
long minutes = remaining / 60;
sb.append(this.formatter.format(minutes)).append(":");
long seconds = remaining - (minutes * 60);
sb.append(this.formatter.format(seconds));
return sb;
}
/**
* Parsing is not implemented, so this method always returns
* <code>null</code>.
*
* @param source ignored.
* @param parsePosition ignored.
*
* @return Always <code>null</code>.
*/
@Override
public Number parse (String source, ParsePosition parsePosition) {
return null; // don't bother with parsing
}
}
| 3,883 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
GanttParam.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/util/GanttParam.java | package org.jfree.chart.util;
import java.util.List;
public class GanttParam {
private final double beginTime;
private final double endTime;
private String sqlId, sessionId, serial, currentFileR, fileName, tsName, waitClass;
private boolean isSqlSessionDetial;
private List<Long> dbaFilesIdList;
public double getBeginTime() {
return beginTime;
}
public double getEndTime() {
return endTime;
}
public String getSqlId() {
return sqlId;
}
public String getSessionId() {
return sessionId;
}
public String getSerial() {
return serial;
}
public String getCurrentFileR() { return currentFileR; }
public String getFileName() { return fileName; }
public String getTsName() { return tsName; }
public String getWaitClass() { return waitClass; }
public boolean isSqlSessionDetial() { return isSqlSessionDetial; }
public List<Long> getDbaFilesIdList() { return dbaFilesIdList; }
public static class Builder {
private final double beginTime;
private final double endTime;
private String sqlId = "";
private String sessionId = "";
private String serial = "";
private String currentFileR = "";
private String fileName = "";
private String tsName = "";
private String waitClass = "";
private boolean isSqlSessionDetial = false;
private List<Long> dbaFilesIdList = null;
public Builder(double beginTime, double endTime) {
this.beginTime = beginTime;
this.endTime = endTime;
}
public Builder sqlId(String val) { sqlId = val; return this; }
public Builder sessionId(String val) { sessionId = val; return this; }
public Builder serial(String val) { serial = val; return this; }
public Builder currentFileR(String val) { currentFileR = val; return this; }
public Builder fileName(String val) { fileName = val; return this; }
public Builder tsName(String val) { tsName = val; return this; }
public Builder waitClass(String val) { waitClass = val; return this; }
public Builder isSqlSessionDetial(boolean val) { isSqlSessionDetial = val; return this; }
public Builder dbaFilesIdList(List<Long> val) { dbaFilesIdList = val; return this; }
public GanttParam build() {
return new GanttParam(this);
}
}
private GanttParam(Builder builder){
beginTime = builder.beginTime;
endTime = builder.endTime;
sqlId = builder.sqlId;
sessionId = builder.sessionId;
serial = builder.serial;
currentFileR = builder.currentFileR;
fileName = builder.fileName;
tsName = builder.tsName;
waitClass = builder.waitClass;
isSqlSessionDetial = builder.isSqlSessionDetial;
dbaFilesIdList = builder.dbaFilesIdList;
}
}
| 2,947 | Java | .java | akardapolov/ASH-Viewer | 156 | 72 | 35 | 2011-05-25T05:22:11Z | 2023-12-04T11:03:40Z |
AttributedStringUtilities.java | /FileExtraction/Java_unseen/akardapolov_ASH-Viewer/jfreechart-fse/src/main/java/org/jfree/chart/util/AttributedStringUtilities.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.]
*
* ------------------------------
* AttributedStringUtilities.java
* ------------------------------
* (C)opyright 2005-2013, by Object Refinery Limited and Contributors.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* $Id: AttributedStringUtilities.java,v 1.2 2005/10/18 13:24:19 mungady Exp $
*
* Changes
* -------
* 29-Jul-2005 : Version 1(DG);
* 16-Jun-2012 : Moved from JCommon to JFreeChart (DG);
* 01-Aug-2013 : Added toString() method (DG);
*
*/
package org.jfree.chart.util;
import java.text.AttributedCharacterIterator;
import java.text.AttributedString;
import java.text.CharacterIterator;
import java.util.Map;
/**
* Some utility methods for working with <code>AttributedString</code> objects.
*/
public class AttributedStringUtilities {
/**
* Private constructor prevents object creation.
*/
private AttributedStringUtilities() {
}
/**
* Returns a string containing the underlying character data for the
* supplied iterator.
*
* @param aci the iterator (<code>null</code> not permitted).
*
* @return A string.
*/
public static String toString(AttributedCharacterIterator aci) {
StringBuilder builder = new StringBuilder();
int count = aci.getEndIndex() - aci.getBeginIndex();
char c = aci.first();
for (int i = 0; i < count; i++) {
builder.append(c);
c = aci.next();
}
return builder.toString();
}
/**
* Tests two attributed strings for equality.
*
* @param s1 string 1 (<code>null</code> permitted).
* @param s2 string 2 (<code>null</code> permitted).
*
* @return <code>true</code> if <code>s1</code> and <code>s2</code> are
* equal or both <code>null</code>, and <code>false</code>
* otherwise.
*/
public static boolean equal(AttributedString s1, AttributedString s2) {
if (s1 == null) {
return (s2 == null);
}
if (s2 == null) {
return false;
}
AttributedCharacterIterator it1 = s1.getIterator();
AttributedCharacterIterator it2 = s2.getIterator();
char c1 = it1.first();
char c2 = it2.first();
int start = 0;
while (c1 != CharacterIterator.DONE) {
int limit1 = it1.getRunLimit();
int limit2 = it2.getRunLimit();
if (limit1 != limit2) {
return false;
}
// if maps aren't equivalent, return false
Map<AttributedCharacterIterator.Attribute, Object> m1 = it1.getAttributes();
Map<AttributedCharacterIterator.Attribute, Object> m2 = it2.getAttributes();
if (!m1.equals(m2)) {
return false;
}
// now check characters in the run are the same
for (int i = start; i < limit1; i++) {
if (c1 != c2) {
return false;
}
c1 = it1.next();
c2 = it2.next();
}
start = limit1;
}
return c2 == CharacterIterator.DONE;
}
}
| 4,435 | 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.