001/* ===========================================================
002 * JFreeChart : a free chart library for the Java(tm) platform
003 * ===========================================================
004 *
005 * (C) Copyright 2000-2020, by Object Refinery Limited and Contributors.
006 *
007 * Project Info:  http://www.jfree.org/jfreechart/index.html
008 *
009 * This library is free software; you can redistribute it and/or modify it
010 * under the terms of the GNU Lesser General Public License as published by
011 * the Free Software Foundation; either version 2.1 of the License, or
012 * (at your option) any later version.
013 *
014 * This library is distributed in the hope that it will be useful, but
015 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
016 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
017 * License for more details.
018 *
019 * You should have received a copy of the GNU Lesser General Public
020 * License along with this library; if not, write to the Free Software
021 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301,
022 * USA.
023 *
024 * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. 
025 * Other names may be trademarks of their respective owners.]
026 *
027 * ---------------
028 * SymbolAxis.java
029 * ---------------
030 * (C) Copyright 2002-2017, by Anthony Boulestreau and Contributors.
031 *
032 * Original Author:  Anthony Boulestreau;
033 * Contributor(s):   David Gilbert (for Object Refinery Limited);
034 *
035 *
036 * Changes
037 * -------
038 * 29-Mar-2002 : First version (AB);
039 * 19-Apr-2002 : Updated formatting and import statements (DG);
040 * 21-Jun-2002 : Make change to use the class TickUnit - remove valueToString()
041 *               method and add SymbolicTickUnit (AB);
042 * 25-Jun-2002 : Removed redundant code (DG);
043 * 25-Jul-2002 : Changed order of parameters in ValueAxis constructor (DG);
044 * 05-Sep-2002 : Updated constructor to reflect changes in the Axis class (DG);
045 * 08-Nov-2002 : Moved to new package com.jrefinery.chart.axis (DG);
046 * 14-Feb-2003 : Added back missing constructor code (DG);
047 * 26-Mar-2003 : Implemented Serializable (DG);
048 * 14-May-2003 : Renamed HorizontalSymbolicAxis --> SymbolicAxis and merged in
049 *               VerticalSymbolicAxis (DG);
050 * 12-Aug-2003 : Fixed bug where refreshTicks() method has different signature
051 *               to super class (DG);
052 * 29-Oct-2003 : Added workaround for font alignment in PDF output (DG);
053 * 02-Nov-2003 : Added code to avoid overlapping labels (MR);
054 * 07-Nov-2003 : Modified to use new tick classes (DG);
055 * 18-Nov-2003 : Fixed bug where symbols are not being displayed on the
056 *               axis (DG);
057 * 24-Nov-2003 : Added fix for gridlines on zooming (bug id 834643) (DG);
058 * 21-Jan-2004 : Update for renamed method in ValueAxis (DG);
059 * 11-Mar-2004 : Modified the way the background grid color is being drawn, see
060 *               this thread:
061 *               http://www.jfree.org/phpBB2/viewtopic.php?p=22973 (DG);
062 * 16-Mar-2004 : Added plotState to draw() method (DG);
063 * 07-Apr-2004 : Modified string bounds calculation (DG);
064 * 28-Mar-2005 : Renamed autoRangeIncludesZero() --> getAutoRangeIncludesZero()
065 *               and autoRangeStickyZero() --> getAutoRangeStickyZero() (DG);
066 * 05-Jul-2005 : Fixed signature on refreshTicks() method - see bug report
067 *               1232264 (DG);
068 * 06-Jul-2005 : Renamed SymbolicAxis --> SymbolAxis, added equals() method,
069 *               renamed getSymbolicValue() --> getSymbols(), renamed
070 *               symbolicGridPaint --> gridBandPaint, fixed serialization of
071 *               gridBandPaint, renamed symbolicGridLinesVisible -->
072 *               gridBandsVisible, eliminated symbolicGridLineList (DG);
073 * ------------- JFREECHART 1.0.x ---------------------------------------------
074 * 02-Feb-2007 : Removed author tags all over JFreeChart sources (DG);
075 * 28-Feb-2007 : Fixed bug 1669302 (tick label overlap) (DG);
076 * 25-Jul-2007 : Added new field for alternate grid band paint (DG);
077 * 15-Aug-2008 : Use alternate grid band paint when drawing (DG);
078 * 02-Jul-2013 : Use ParamChecks (DG);
079 * 19-Mar-2014 : Fix gridbands (bug #1056) (DG);
080 * 08-Sep-2014 : Update Javadocs for grid bands (DG):
081 *
082 */
083
084package org.jfree.chart.axis;
085
086import java.awt.BasicStroke;
087import java.awt.Color;
088import java.awt.Font;
089import java.awt.Graphics2D;
090import java.awt.Paint;
091import java.awt.Shape;
092import java.awt.Stroke;
093import java.awt.geom.Rectangle2D;
094import java.io.IOException;
095import java.io.ObjectInputStream;
096import java.io.ObjectOutputStream;
097import java.io.Serializable;
098import java.text.NumberFormat;
099import java.util.Arrays;
100import java.util.Iterator;
101import java.util.List;
102
103import org.jfree.chart.plot.Plot;
104import org.jfree.chart.plot.PlotRenderingInfo;
105import org.jfree.chart.plot.ValueAxisPlot;
106import org.jfree.chart.text.TextUtils;
107import org.jfree.chart.ui.RectangleEdge;
108import org.jfree.chart.ui.TextAnchor;
109import org.jfree.chart.util.PaintUtils;
110import org.jfree.chart.util.Args;
111import org.jfree.chart.util.SerialUtils;
112import org.jfree.data.Range;
113
114/**
115 * A standard linear value axis that replaces integer values with symbols.
116 */
117public class SymbolAxis extends NumberAxis implements Serializable {
118
119    /** For serialization. */
120    private static final long serialVersionUID = 7216330468770619716L;
121
122    /** The default grid band paint. */
123    public static final Paint DEFAULT_GRID_BAND_PAINT
124            = new Color(232, 234, 232, 128);
125
126    /**
127     * The default paint for alternate grid bands.
128     *
129     * @since 1.0.7
130     */
131    public static final Paint DEFAULT_GRID_BAND_ALTERNATE_PAINT
132            = new Color(0, 0, 0, 0);  // transparent
133
134    /** The list of symbols to display instead of the numeric values. */
135    private List symbols;
136
137    /** Flag that indicates whether or not grid bands are visible. */
138    private boolean gridBandsVisible;
139
140    /** The paint used to color the grid bands (if the bands are visible). */
141    private transient Paint gridBandPaint;
142
143    /**
144     * The paint used to fill the alternate grid bands.
145     *
146     * @since 1.0.7
147     */
148    private transient Paint gridBandAlternatePaint;
149
150    /**
151     * Constructs a symbol axis, using default attribute values where
152     * necessary.
153     *
154     * @param label  the axis label ({@code null} permitted).
155     * @param sv  the list of symbols to display instead of the numeric
156     *            values.
157     */
158    public SymbolAxis(String label, String[] sv) {
159        super(label);
160        this.symbols = Arrays.asList(sv);
161        this.gridBandsVisible = true;
162        this.gridBandPaint = DEFAULT_GRID_BAND_PAINT;
163        this.gridBandAlternatePaint = DEFAULT_GRID_BAND_ALTERNATE_PAINT;
164        setAutoTickUnitSelection(false, false);
165        setAutoRangeStickyZero(false);
166    }
167
168    /**
169     * Returns an array of the symbols for the axis.
170     *
171     * @return The symbols.
172     */
173    public String[] getSymbols() {
174        String[] result = new String[this.symbols.size()];
175        result = (String[]) this.symbols.toArray(result);
176        return result;
177    }
178
179    /**
180     * Returns the flag that controls whether or not grid bands are drawn for 
181     * the axis.  The default value is {@code true}. 
182     *
183     * @return A boolean.
184     *
185     * @see #setGridBandsVisible(boolean)
186     */
187    public boolean isGridBandsVisible() {
188        return this.gridBandsVisible;
189    }
190
191    /**
192     * Sets the flag that controls whether or not grid bands are drawn for this
193     * axis and notifies registered listeners that the axis has been modified.
194     * Each band is the area between two adjacent gridlines 
195     * running perpendicular to the axis.  When the bands are drawn they are 
196     * filled with the colors {@link #getGridBandPaint()} and 
197     * {@link #getGridBandAlternatePaint()} in an alternating sequence.
198     *
199     * @param flag  the new setting.
200     *
201     * @see #isGridBandsVisible()
202     */
203    public void setGridBandsVisible(boolean flag) {
204        this.gridBandsVisible = flag;
205        fireChangeEvent();
206    }
207
208    /**
209     * Returns the paint used to color grid bands (two colors are used
210     * alternately, the other is returned by 
211     * {@link #getGridBandAlternatePaint()}).  The default value is
212     * {@link #DEFAULT_GRID_BAND_PAINT}.
213     *
214     * @return The paint (never {@code null}).
215     *
216     * @see #setGridBandPaint(Paint)
217     * @see #isGridBandsVisible()
218     */
219    public Paint getGridBandPaint() {
220        return this.gridBandPaint;
221    }
222
223    /**
224     * Sets the grid band paint and notifies registered listeners that the
225     * axis has been changed.  See the {@link #setGridBandsVisible(boolean)}
226     * method for more information about grid bands.
227     *
228     * @param paint  the paint ({@code null} not permitted).
229     *
230     * @see #getGridBandPaint()
231     */
232    public void setGridBandPaint(Paint paint) {
233        Args.nullNotPermitted(paint, "paint");
234        this.gridBandPaint = paint;
235        fireChangeEvent();
236    }
237
238    /**
239     * Returns the second paint used to color grid bands (two colors are used
240     * alternately, the other is returned by {@link #getGridBandPaint()}).  
241     * The default value is {@link #DEFAULT_GRID_BAND_ALTERNATE_PAINT} 
242     * (transparent).
243     *
244     * @return The paint (never {@code null}).
245     *
246     * @see #setGridBandAlternatePaint(Paint)
247     *
248     * @since 1.0.7
249     */
250    public Paint getGridBandAlternatePaint() {
251        return this.gridBandAlternatePaint;
252    }
253
254    /**
255     * Sets the grid band paint and notifies registered listeners that the
256     * axis has been changed.  See the {@link #setGridBandsVisible(boolean)}
257     * method for more information about grid bands.
258     *
259     * @param paint  the paint ({@code null} not permitted).
260     *
261     * @see #getGridBandAlternatePaint()
262     * @see #setGridBandPaint(Paint)
263     *
264     * @since 1.0.7
265     */
266    public void setGridBandAlternatePaint(Paint paint) {
267        Args.nullNotPermitted(paint, "paint");
268        this.gridBandAlternatePaint = paint;
269        fireChangeEvent();
270    }
271
272    /**
273     * This operation is not supported by this axis.
274     *
275     * @param g2  the graphics device.
276     * @param dataArea  the area in which the plot and axes should be drawn.
277     * @param edge  the edge along which the axis is drawn.
278     */
279    @Override
280    protected void selectAutoTickUnit(Graphics2D g2, Rectangle2D dataArea,
281            RectangleEdge edge) {
282        throw new UnsupportedOperationException();
283    }
284
285    /**
286     * Draws the axis on a Java 2D graphics device (such as the screen or a
287     * printer).
288     *
289     * @param g2  the graphics device ({@code null} not permitted).
290     * @param cursor  the cursor location.
291     * @param plotArea  the area within which the plot and axes should be drawn
292     *                  ({@code null} not permitted).
293     * @param dataArea  the area within which the data should be drawn
294     *                  ({@code null} not permitted).
295     * @param edge  the axis location ({@code null} not permitted).
296     * @param plotState  collects information about the plot
297     *                   ({@code null} permitted).
298     *
299     * @return The axis state (never {@code null}).
300     */
301    @Override
302    public AxisState draw(Graphics2D g2, double cursor, Rectangle2D plotArea,
303            Rectangle2D dataArea, RectangleEdge edge, 
304            PlotRenderingInfo plotState) {
305
306        AxisState info = new AxisState(cursor);
307        if (isVisible()) {
308            info = super.draw(g2, cursor, plotArea, dataArea, edge, plotState);
309        }
310        if (this.gridBandsVisible) {
311            drawGridBands(g2, plotArea, dataArea, edge, info.getTicks());
312        }
313        return info;
314
315    }
316
317    /**
318     * Draws the grid bands (alternate bands are colored using
319     * {@link #getGridBandPaint()} and {@link #getGridBandAlternatePaint()}.
320     *
321     * @param g2  the graphics target ({@code null} not permitted).
322     * @param plotArea  the area within which the plot is drawn 
323     *     ({@code null} not permitted).
324     * @param dataArea  the data area to which the axes are aligned 
325     *     ({@code null} not permitted).
326     * @param edge  the edge to which the axis is aligned ({@code null} not
327     *     permitted).
328     * @param ticks  the ticks ({@code null} not permitted).
329     */
330    protected void drawGridBands(Graphics2D g2, Rectangle2D plotArea,
331            Rectangle2D dataArea, RectangleEdge edge, List ticks) {
332        Shape savedClip = g2.getClip();
333        g2.clip(dataArea);
334        if (RectangleEdge.isTopOrBottom(edge)) {
335            drawGridBandsHorizontal(g2, plotArea, dataArea, true, ticks);
336        } else if (RectangleEdge.isLeftOrRight(edge)) {
337            drawGridBandsVertical(g2, plotArea, dataArea, true, ticks);
338        }
339        g2.setClip(savedClip);
340    }
341
342    /**
343     * Draws the grid bands for the axis when it is at the top or bottom of
344     * the plot.
345     *
346     * @param g2  the graphics target ({@code null} not permitted).
347     * @param plotArea  the area within which the plot is drawn (not used here).
348     * @param dataArea  the area for the data (to which the axes are aligned,
349     *         {@code null} not permitted).
350     * @param firstGridBandIsDark  True: the first grid band takes the
351     *                             color of {@code gridBandPaint}.
352     *                             False: the second grid band takes the
353     *                             color of {@code gridBandPaint}.
354     * @param ticks  a list of ticks ({@code null} not permitted).
355     */
356    protected void drawGridBandsHorizontal(Graphics2D g2,
357            Rectangle2D plotArea, Rectangle2D dataArea, 
358            boolean firstGridBandIsDark, List ticks) {
359
360        boolean currentGridBandIsDark = firstGridBandIsDark;
361        double yy = dataArea.getY();
362        double xx1, xx2;
363
364        //gets the outline stroke width of the plot
365        double outlineStrokeWidth = 1.0;
366        Stroke outlineStroke = getPlot().getOutlineStroke();
367        if (outlineStroke != null && outlineStroke instanceof BasicStroke) {
368            outlineStrokeWidth = ((BasicStroke) outlineStroke).getLineWidth();
369        }
370
371        Iterator iterator = ticks.iterator();
372        ValueTick tick;
373        Rectangle2D band;
374        while (iterator.hasNext()) {
375            tick = (ValueTick) iterator.next();
376            xx1 = valueToJava2D(tick.getValue() - 0.5d, dataArea,
377                    RectangleEdge.BOTTOM);
378            xx2 = valueToJava2D(tick.getValue() + 0.5d, dataArea,
379                    RectangleEdge.BOTTOM);
380            if (currentGridBandIsDark) {
381                g2.setPaint(this.gridBandPaint);
382            } else {
383                g2.setPaint(this.gridBandAlternatePaint);
384            }
385            band = new Rectangle2D.Double(Math.min(xx1, xx2), 
386                    yy + outlineStrokeWidth, Math.abs(xx2 - xx1), 
387                    dataArea.getMaxY() - yy - outlineStrokeWidth);
388            g2.fill(band);
389            currentGridBandIsDark = !currentGridBandIsDark;
390        }
391    }
392
393    /**
394     * Draws the grid bands for an axis that is aligned to the left or
395     * right of the data area (that is, a vertical axis).
396     *
397     * @param g2  the graphics target ({@code null} not permitted).
398     * @param plotArea  the area within which the plot is drawn (not used here).
399     * @param dataArea  the area for the data (to which the axes are aligned,
400     *         {@code null} not permitted).
401     * @param firstGridBandIsDark  True: the first grid band takes the
402     *                             color of {@code gridBandPaint}.
403     *                             False: the second grid band takes the
404     *                             color of {@code gridBandPaint}.
405     * @param ticks  a list of ticks ({@code null} not permitted).
406     */
407    protected void drawGridBandsVertical(Graphics2D g2, Rectangle2D plotArea,
408            Rectangle2D dataArea, boolean firstGridBandIsDark, 
409            List ticks) {
410
411        boolean currentGridBandIsDark = firstGridBandIsDark;
412        double xx = dataArea.getX();
413        double yy1, yy2;
414
415        //gets the outline stroke width of the plot
416        double outlineStrokeWidth = 1.0;
417        Stroke outlineStroke = getPlot().getOutlineStroke();
418        if (outlineStroke != null && outlineStroke instanceof BasicStroke) {
419            outlineStrokeWidth = ((BasicStroke) outlineStroke).getLineWidth();
420        }
421
422        Iterator iterator = ticks.iterator();
423        ValueTick tick;
424        Rectangle2D band;
425        while (iterator.hasNext()) {
426            tick = (ValueTick) iterator.next();
427            yy1 = valueToJava2D(tick.getValue() + 0.5d, dataArea,
428                    RectangleEdge.LEFT);
429            yy2 = valueToJava2D(tick.getValue() - 0.5d, dataArea,
430                    RectangleEdge.LEFT);
431            if (currentGridBandIsDark) {
432                g2.setPaint(this.gridBandPaint);
433            } else {
434                g2.setPaint(this.gridBandAlternatePaint);
435            }
436            band = new Rectangle2D.Double(xx + outlineStrokeWidth, 
437                    Math.min(yy1, yy2), dataArea.getMaxX() - xx 
438                    - outlineStrokeWidth, Math.abs(yy2 - yy1));
439            g2.fill(band);
440            currentGridBandIsDark = !currentGridBandIsDark;
441        }
442    }
443
444    /**
445     * Rescales the axis to ensure that all data is visible.
446     */
447    @Override
448    protected void autoAdjustRange() {
449        Plot plot = getPlot();
450        if (plot == null) {
451            return;  // no plot, no data
452        }
453
454        if (plot instanceof ValueAxisPlot) {
455
456            // ensure that all the symbols are displayed
457            double upper = this.symbols.size() - 1;
458            double lower = 0;
459            double range = upper - lower;
460
461            // ensure the autorange is at least <minRange> in size...
462            double minRange = getAutoRangeMinimumSize();
463            if (range < minRange) {
464                upper = (upper + lower + minRange) / 2;
465                lower = (upper + lower - minRange) / 2;
466            }
467
468            // this ensure that the grid bands will be displayed correctly.
469            double upperMargin = 0.5;
470            double lowerMargin = 0.5;
471
472            if (getAutoRangeIncludesZero()) {
473                if (getAutoRangeStickyZero()) {
474                    if (upper <= 0.0) {
475                        upper = 0.0;
476                    } else {
477                        upper = upper + upperMargin;
478                    }
479                    if (lower >= 0.0) {
480                        lower = 0.0;
481                    } else {
482                        lower = lower - lowerMargin;
483                    }
484                } else {
485                    upper = Math.max(0.0, upper + upperMargin);
486                    lower = Math.min(0.0, lower - lowerMargin);
487                }
488            } else {
489                if (getAutoRangeStickyZero()) {
490                    if (upper <= 0.0) {
491                        upper = Math.min(0.0, upper + upperMargin);
492                    } else {
493                        upper = upper + upperMargin * range;
494                    }
495                    if (lower >= 0.0) {
496                        lower = Math.max(0.0, lower - lowerMargin);
497                    } else {
498                        lower = lower - lowerMargin;
499                    }
500                } else {
501                    upper = upper + upperMargin;
502                    lower = lower - lowerMargin;
503                }
504            }
505            setRange(new Range(lower, upper), false, false);
506        }
507    }
508
509    /**
510     * Calculates the positions of the tick labels for the axis, storing the
511     * results in the tick label list (ready for drawing).
512     *
513     * @param g2  the graphics device.
514     * @param state  the axis state.
515     * @param dataArea  the area in which the data should be drawn.
516     * @param edge  the location of the axis.
517     *
518     * @return A list of ticks.
519     */
520    @Override
521    public List refreshTicks(Graphics2D g2, AxisState state,
522            Rectangle2D dataArea, RectangleEdge edge) {
523        List ticks = null;
524        if (RectangleEdge.isTopOrBottom(edge)) {
525            ticks = refreshTicksHorizontal(g2, dataArea, edge);
526        } else if (RectangleEdge.isLeftOrRight(edge)) {
527            ticks = refreshTicksVertical(g2, dataArea, edge);
528        }
529        return ticks;
530    }
531
532    /**
533     * Calculates the positions of the tick labels for the axis, storing the
534     * results in the tick label list (ready for drawing).
535     *
536     * @param g2  the graphics device.
537     * @param dataArea  the area in which the data should be drawn.
538     * @param edge  the location of the axis.
539     *
540     * @return The ticks.
541     */
542    @Override
543    protected List refreshTicksHorizontal(Graphics2D g2, Rectangle2D dataArea,
544            RectangleEdge edge) {
545
546        List ticks = new java.util.ArrayList();
547
548        Font tickLabelFont = getTickLabelFont();
549        g2.setFont(tickLabelFont);
550
551        double size = getTickUnit().getSize();
552        int count = calculateVisibleTickCount();
553        double lowestTickValue = calculateLowestVisibleTickValue();
554
555        double previousDrawnTickLabelPos = 0.0;
556        double previousDrawnTickLabelLength = 0.0;
557
558        if (count <= ValueAxis.MAXIMUM_TICK_COUNT) {
559            for (int i = 0; i < count; i++) {
560                double currentTickValue = lowestTickValue + (i * size);
561                double xx = valueToJava2D(currentTickValue, dataArea, edge);
562                String tickLabel;
563                NumberFormat formatter = getNumberFormatOverride();
564                if (formatter != null) {
565                    tickLabel = formatter.format(currentTickValue);
566                }
567                else {
568                    tickLabel = valueToString(currentTickValue);
569                }
570
571                // avoid to draw overlapping tick labels
572                Rectangle2D bounds = TextUtils.getTextBounds(tickLabel, g2,
573                        g2.getFontMetrics());
574                double tickLabelLength = isVerticalTickLabels()
575                        ? bounds.getHeight() : bounds.getWidth();
576                boolean tickLabelsOverlapping = false;
577                if (i > 0) {
578                    double avgTickLabelLength = (previousDrawnTickLabelLength
579                            + tickLabelLength) / 2.0;
580                    if (Math.abs(xx - previousDrawnTickLabelPos)
581                            < avgTickLabelLength) {
582                        tickLabelsOverlapping = true;
583                    }
584                }
585                if (tickLabelsOverlapping) {
586                    tickLabel = ""; // don't draw this tick label
587                }
588                else {
589                    // remember these values for next comparison
590                    previousDrawnTickLabelPos = xx;
591                    previousDrawnTickLabelLength = tickLabelLength;
592                }
593
594                TextAnchor anchor;
595                TextAnchor rotationAnchor;
596                double angle = 0.0;
597                if (isVerticalTickLabels()) {
598                    anchor = TextAnchor.CENTER_RIGHT;
599                    rotationAnchor = TextAnchor.CENTER_RIGHT;
600                    if (edge == RectangleEdge.TOP) {
601                        angle = Math.PI / 2.0;
602                    }
603                    else {
604                        angle = -Math.PI / 2.0;
605                    }
606                }
607                else {
608                    if (edge == RectangleEdge.TOP) {
609                        anchor = TextAnchor.BOTTOM_CENTER;
610                        rotationAnchor = TextAnchor.BOTTOM_CENTER;
611                    }
612                    else {
613                        anchor = TextAnchor.TOP_CENTER;
614                        rotationAnchor = TextAnchor.TOP_CENTER;
615                    }
616                }
617                Tick tick = new NumberTick(currentTickValue,
618                        tickLabel, anchor, rotationAnchor, angle);
619                ticks.add(tick);
620            }
621        }
622        return ticks;
623
624    }
625
626    /**
627     * Calculates the positions of the tick labels for the axis, storing the
628     * results in the tick label list (ready for drawing).
629     *
630     * @param g2  the graphics device.
631     * @param dataArea  the area in which the plot should be drawn.
632     * @param edge  the location of the axis.
633     *
634     * @return The ticks.
635     */
636    @Override
637    protected List refreshTicksVertical(Graphics2D g2, Rectangle2D dataArea,
638            RectangleEdge edge) {
639
640        List ticks = new java.util.ArrayList();
641
642        Font tickLabelFont = getTickLabelFont();
643        g2.setFont(tickLabelFont);
644
645        double size = getTickUnit().getSize();
646        int count = calculateVisibleTickCount();
647        double lowestTickValue = calculateLowestVisibleTickValue();
648
649        double previousDrawnTickLabelPos = 0.0;
650        double previousDrawnTickLabelLength = 0.0;
651
652        if (count <= ValueAxis.MAXIMUM_TICK_COUNT) {
653            for (int i = 0; i < count; i++) {
654                double currentTickValue = lowestTickValue + (i * size);
655                double yy = valueToJava2D(currentTickValue, dataArea, edge);
656                String tickLabel;
657                NumberFormat formatter = getNumberFormatOverride();
658                if (formatter != null) {
659                    tickLabel = formatter.format(currentTickValue);
660                }
661                else {
662                    tickLabel = valueToString(currentTickValue);
663                }
664
665                // avoid to draw overlapping tick labels
666                Rectangle2D bounds = TextUtils.getTextBounds(tickLabel, g2,
667                        g2.getFontMetrics());
668                double tickLabelLength = isVerticalTickLabels()
669                    ? bounds.getWidth() : bounds.getHeight();
670                boolean tickLabelsOverlapping = false;
671                if (i > 0) {
672                    double avgTickLabelLength = (previousDrawnTickLabelLength
673                            + tickLabelLength) / 2.0;
674                    if (Math.abs(yy - previousDrawnTickLabelPos)
675                            < avgTickLabelLength) {
676                        tickLabelsOverlapping = true;
677                    }
678                }
679                if (tickLabelsOverlapping) {
680                    tickLabel = ""; // don't draw this tick label
681                }
682                else {
683                    // remember these values for next comparison
684                    previousDrawnTickLabelPos = yy;
685                    previousDrawnTickLabelLength = tickLabelLength;
686                }
687
688                TextAnchor anchor;
689                TextAnchor rotationAnchor;
690                double angle = 0.0;
691                if (isVerticalTickLabels()) {
692                    anchor = TextAnchor.BOTTOM_CENTER;
693                    rotationAnchor = TextAnchor.BOTTOM_CENTER;
694                    if (edge == RectangleEdge.LEFT) {
695                        angle = -Math.PI / 2.0;
696                    }
697                    else {
698                        angle = Math.PI / 2.0;
699                    }
700                }
701                else {
702                    if (edge == RectangleEdge.LEFT) {
703                        anchor = TextAnchor.CENTER_RIGHT;
704                        rotationAnchor = TextAnchor.CENTER_RIGHT;
705                    }
706                    else {
707                        anchor = TextAnchor.CENTER_LEFT;
708                        rotationAnchor = TextAnchor.CENTER_LEFT;
709                    }
710                }
711                Tick tick = new NumberTick(currentTickValue, tickLabel, anchor, 
712                        rotationAnchor, angle);
713                ticks.add(tick);
714            }
715        }
716        return ticks;
717
718    }
719
720    /**
721     * Converts a value to a string, using the list of symbols.
722     *
723     * @param value  value to convert.
724     *
725     * @return The symbol.
726     */
727    public String valueToString(double value) {
728        String strToReturn;
729        try {
730            strToReturn = (String) this.symbols.get((int) value);
731        }
732        catch (IndexOutOfBoundsException  ex) {
733            strToReturn = "";
734        }
735        return strToReturn;
736    }
737
738    /**
739     * Tests this axis for equality with an arbitrary object.
740     *
741     * @param obj  the object ({@code null} permitted).
742     *
743     * @return A boolean.
744     */
745    @Override
746    public boolean equals(Object obj) {
747        if (obj == this) {
748            return true;
749        }
750        if (!(obj instanceof SymbolAxis)) {
751            return false;
752        }
753        SymbolAxis that = (SymbolAxis) obj;
754        if (!this.symbols.equals(that.symbols)) {
755            return false;
756        }
757        if (this.gridBandsVisible != that.gridBandsVisible) {
758            return false;
759        }
760        if (!PaintUtils.equal(this.gridBandPaint, that.gridBandPaint)) {
761            return false;
762        }
763        if (!PaintUtils.equal(this.gridBandAlternatePaint,
764                that.gridBandAlternatePaint)) {
765            return false;
766        }
767        return super.equals(obj);
768    }
769
770    /**
771     * Provides serialization support.
772     *
773     * @param stream  the output stream.
774     *
775     * @throws IOException  if there is an I/O error.
776     */
777    private void writeObject(ObjectOutputStream stream) throws IOException {
778        stream.defaultWriteObject();
779        SerialUtils.writePaint(this.gridBandPaint, stream);
780        SerialUtils.writePaint(this.gridBandAlternatePaint, stream);
781    }
782
783    /**
784     * Provides serialization support.
785     *
786     * @param stream  the input stream.
787     *
788     * @throws IOException  if there is an I/O error.
789     * @throws ClassNotFoundException  if there is a classpath problem.
790     */
791    private void readObject(ObjectInputStream stream)
792        throws IOException, ClassNotFoundException {
793        stream.defaultReadObject();
794        this.gridBandPaint = SerialUtils.readPaint(stream);
795        this.gridBandAlternatePaint = SerialUtils.readPaint(stream);
796    }
797
798}