KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > openi > chart > ChartCustomizer


1 /*********************************************************************************
2  * The contents of this file are subject to the OpenI Public License Version 1.0
3  * ("License"); You may not use this file except in compliance with the
4  * License. You may obtain a copy of the License at
5  * http://www.openi.org/docs/LICENSE.txt
6  *
7  * Software distributed under the License is distributed on an "AS IS" basis,
8  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
9  * the specific language governing rights and limitations under the License.
10  *
11  * The Original Code is: OpenI Open Source
12  *
13  * The Initial Developer of the Original Code is Loyalty Matrix, Inc.
14  * Portions created by Loyalty Matrix, Inc. are
15  * Copyright (C) 2005 Loyalty Matrix, Inc.; All Rights Reserved.
16  *
17  * Contributor(s): ______________________________________.
18  *
19  ********************************************************************************/

20 package org.openi.chart;
21
22 import com.tonbeller.jpivot.olap.model.Member;
23 import com.tonbeller.jpivot.olap.model.OlapException;
24 import com.tonbeller.jpivot.olap.model.Position;
25 import com.tonbeller.jpivot.olap.model.Result;
26 import org.apache.log4j.Logger;
27 import org.jfree.chart.JFreeChart;
28 import org.jfree.chart.StandardLegend;
29 import org.jfree.chart.axis.CategoryLabelPosition;
30 import org.jfree.chart.axis.CategoryLabelPositions;
31 import org.jfree.chart.axis.NumberAxis;
32 import org.jfree.chart.plot.CategoryPlot;
33 import org.jfree.chart.plot.DatasetRenderingOrder;
34 import org.jfree.chart.plot.PiePlot;
35 import org.jfree.chart.plot.PiePlot3D;
36 import org.jfree.chart.plot.Plot;
37 import org.jfree.chart.plot.XYPlot;
38 import org.jfree.chart.renderer.category.CategoryItemRenderer;
39 import org.jfree.chart.renderer.category.LineAndShapeRenderer;
40 import org.jfree.chart.title.TextTitle;
41 import org.jfree.data.KeyedValues;
42 import org.jfree.data.category.CategoryDataset;
43 import org.jfree.data.general.DataUtilities;
44 import org.jfree.data.general.DatasetUtilities;
45 import org.jfree.data.general.PieDataset;
46 import org.jfree.text.TextBlockAnchor;
47 import org.jfree.ui.HorizontalAlignment;
48 import org.jfree.ui.RectangleAnchor;
49 import org.jfree.ui.RectangleEdge;
50 import org.jfree.ui.TextAnchor;
51 import org.openi.analysis.Analysis;
52 import java.awt.Color JavaDoc;
53 import java.awt.Font JavaDoc;
54 import java.awt.Paint JavaDoc;
55 import java.text.NumberFormat JavaDoc;
56 import java.util.Iterator JavaDoc;
57 import java.util.LinkedList JavaDoc;
58 import java.util.List JavaDoc;
59
60
61 /**
62  * customizes chart properties based on model (enhanced chart component)
63  */

64 public class ChartCustomizer {
65     private static Logger logger = Logger.getLogger(ChartCustomizer.class);
66     
67         
68     public void customizeChart(JFreeChart chart, Paint JavaDoc bgPaint, Font JavaDoc axisFont,
69             Font JavaDoc axisTickFont, Font JavaDoc legendFont, int legendPosition,
70             double tickLabelRotate, float foregoundAlpha){
71             chart.setBackgroundPaint(bgPaint);
72         // chart.setBackgroundPaint(new Color(255, 255, 255));
73
logger.debug("setting background paint: " + bgPaint);
74
75         Plot plot = chart.getPlot();
76         logger.debug("plot type: " + plot.getClass().getName());
77         plot.setForegroundAlpha(1.0f);
78         
79         if (plot instanceof CategoryPlot) {
80             CategoryPlot catPlot = (CategoryPlot) plot;
81             catPlot.getDomainAxis().setLabelFont(axisFont);
82             catPlot.getRangeAxis().setLabelFont(axisFont);
83             catPlot.getDomainAxis().setTickLabelFont(axisTickFont);
84             catPlot.getRangeAxis().setTickLabelFont(axisTickFont);
85             catPlot.getDomainAxis().setMaxCategoryLabelWidthRatio(100);
86             
87             double angle = (-2.0 * Math.PI) / 360.0 * tickLabelRotate;
88             CategoryLabelPositions oldp = catPlot.getDomainAxis()
89                                                  .getCategoryLabelPositions();
90             CategoryLabelPositions newp = new CategoryLabelPositions(oldp
91                     .getLabelPosition(RectangleEdge.TOP),
92                     new CategoryLabelPosition(RectangleAnchor.TOP,
93                         TextBlockAnchor.TOP_RIGHT,
94                         TextAnchor.TOP_RIGHT, angle),
95                     oldp.getLabelPosition(RectangleEdge.LEFT),
96                     oldp.getLabelPosition(RectangleEdge.RIGHT));
97             catPlot.getDomainAxis().setCategoryLabelPositions(newp);
98     
99             // XXX: setting series colors
100
logger.info("setting up series colors");
101             setupSeriesPaint(this.getDefaultColorPalette(),
102                     chart.getCategoryPlot().getRenderer());
103                     
104         } else if (plot instanceof PiePlot3D) {
105             PiePlot3D piePlot = (PiePlot3D) plot;
106     
107             //piePlot.setSectionLabelFont(axisFont);
108
piePlot.setLabelFont(axisFont);
109     
110             //piePlot.setSeriesLabelFont(axisTickFont);
111
//piePlot.setSectionLabelType(piePlot.NO_LABELS);
112
piePlot.setDirection(org.jfree.util.Rotation.CLOCKWISE);
113             //casting int type to float type
114
piePlot.setNoDataMessage("No data to display");
115         } else if (plot instanceof PiePlot) {
116             PiePlot piePlot = (PiePlot) plot;
117             //piePlot.setSectionLabelFont(axisFont);
118
//piePlot.setSeriesLabelFont(axisTickFont);
119
piePlot.setLabelFont(axisFont);
120     
121             //piePlot.setSectionLabelType(piePlot.NO_LABELS);
122
} else if(plot instanceof XYPlot){
123                 XYPlot xyPlot = (XYPlot)plot;
124                 xyPlot.getDomainAxis().setLabelFont(axisFont);
125                 xyPlot.getRangeAxis().setLabelFont(axisFont);
126                 xyPlot.getDomainAxis().setTickLabelFont(axisTickFont);
127                 xyPlot.getRangeAxis().setTickLabelFont(axisTickFont);
128                 // xyPlot.getDomainAxis().setMaxCategoryLabelWidthRatio(100);
129
xyPlot.setBackgroundPaint(bgPaint);
130                 xyPlot.setRangeGridlinesVisible(true);
131                 xyPlot.setRangeGridlinePaint(new Color JavaDoc(166, 166, 166));
132                 // xyPlot.setRangeTickBandPaint(purple);
133
// Color purple = new Color(171, 25, 97);
134
// xyPlot.setRangeCrosshairPaint(purple);
135
xyPlot.getDomainAxis().setAxisLineVisible(false);
136                 xyPlot.getRangeAxis().setAxisLineVisible(false);
137                 xyPlot.setOutlinePaint(new Color JavaDoc(0, 0, 0));
138                 xyPlot.getRangeAxis().setMinimumAxisValue(0);
139         }
140     
141         customizeLegend(chart, legendFont, legendPosition);
142     
143         
144         }
145     
146
147     /**
148      * @param component
149      * @param chart
150      * @param legendFont
151      */

152     private void customizeLegend(JFreeChart chart,
153             Font JavaDoc legendFont,
154             int legendPosition) {
155         StandardLegend legend = (StandardLegend) chart.getLegend();
156         
157         if (legend != null) {
158             legend.setItemFont(legendFont);
159             // legend.setPreferredWidth(EnhancedChartComponent.DEFAULT_LEGEND_WIDTH);
160
legend.setAnchor(legendPosition);
161             legend.setOutlinePaint(legend.getBackgroundPaint());
162         }
163     }
164     
165     private RectangleEdge createRectangleEdge(int slicerPosition){
166         RectangleEdge slicerRectPos = RectangleEdge.BOTTOM;
167         
168
169         switch (slicerPosition) {
170         case 0:
171             slicerRectPos = RectangleEdge.LEFT;
172             break;
173
174         case 1:
175             slicerRectPos = RectangleEdge.TOP;
176             break;
177
178         case 2:
179             slicerRectPos = RectangleEdge.RIGHT;
180             break;
181
182         case 3:
183             slicerRectPos = RectangleEdge.BOTTOM;
184             break;
185         }
186         return slicerRectPos;
187
188     }
189     
190     private HorizontalAlignment createHorizontalAlignment(int slicerAlignment){
191         HorizontalAlignment slicerHorizAlignment = HorizontalAlignment.LEFT;
192             
193         switch (slicerAlignment) {
194             case 4:
195                 slicerHorizAlignment = HorizontalAlignment.CENTER;
196                 break;
197     
198             case 3:
199                 slicerHorizAlignment = HorizontalAlignment.LEFT;
200                 break;
201     
202             case 2:
203                 slicerHorizAlignment = HorizontalAlignment.RIGHT;
204                 break;
205         }
206         
207         return slicerHorizAlignment;
208     }
209
210             /**
211              * Series paint will be set in the list order of the colorPallette
212              * parameter. Can contain a list of any java.awt.Paint objects
213              * (Color, GradientPaint, etc).
214              * Will only attempt if the paintList is not null.
215              *
216              * @param colorPalette list of java.awt.Paint objects
217              * @param renderer
218              */

219             private void setupSeriesPaint(List JavaDoc paintList,
220                 CategoryItemRenderer renderer) {
221                 logger.debug("setupSeriesPaint: " + paintList);
222
223                 if (paintList != null) {
224                     Iterator JavaDoc palette = paintList.iterator();
225
226                     for (int i = 0; palette.hasNext(); i++) {
227                         Paint JavaDoc current = (Paint JavaDoc) palette.next();
228                         renderer.setSeriesPaint(i, current);
229                     }
230                 }
231             }
232
233             public void generatePareto(CategoryPlot plot) {
234                     CategoryDataset dataset = plot.getDataset();
235                 PieDataset pieDataset = DatasetUtilities.createPieDatasetForRow(dataset,
236                         0);
237                 KeyedValues cumulative = DataUtilities.getCumulativePercentages(pieDataset);
238                 LineAndShapeRenderer renderer = new LineAndShapeRenderer();
239                 CategoryDataset dataset2 = DatasetUtilities
240                         .createCategoryDataset("Cumulative Pct", // will show up in legend
241
cumulative);
242                     NumberAxis axis2 = new NumberAxis("Culmulative Percentage"); // axis label
243

244                     axis2.setNumberFormatOverride(NumberFormat.getPercentInstance());
245                     axis2.setMaximumAxisValue(1.0);//set max to 100%, otherwise defaults to 105%
246
plot.setRangeAxis(1, axis2);
247                     plot.setDataset(1, dataset2);
248                     plot.setRenderer(1, renderer);
249                     plot.mapDatasetToRangeAxis(1, 1);
250                     plot.setDatasetRenderingOrder(DatasetRenderingOrder.FORWARD);
251             }
252             
253
254
255             /**
256              * build slicer text string
257              */

258             private String JavaDoc buildSlicer(Result result) {
259                 StringBuffer JavaDoc slicer = new StringBuffer JavaDoc();
260                 slicer.append("Slicer: ");
261
262                 Iterator JavaDoc pi = result.getSlicer().getPositions()
263                                     .iterator();
264
265                 while (pi.hasNext()) {
266                     Position p = (Position) pi.next();
267                     Member[] members = p.getMembers();
268
269                     for (int i = 0; i < members.length; i++) {
270                         slicer.append(members[i].getLevel().getLabel());
271                         slicer.append("=");
272                         slicer.append(members[i].getLabel());
273
274                         if (i < (members.length - 1)) {
275                             slicer.append(", ");
276                         }
277                     }
278                 }
279
280                 return slicer.toString();
281             }
282
283             /**
284              * Get cell value as a Number. Parses the cell value string
285              * using the locale set in this.locale.
286              * @param cell
287              * @return value as Number (can be null)
288              */

289
290             /*
291                private Number getNumberValue(Cell cell) {
292                  //**** HACK AR 2004.01.10
293                   //String value = cell.getFormattedValue();
294                   Object value = cell.getValue();
295             
296                  //added to fix data format bug in range axis
297                  if(cell.getFormattedValue()!=null && cell.getFormattedValue()!="" )
298                  {
299             
300                      String fmtValue=cell.getFormattedValue();
301                      fmtValue=fmtValue.trim();
302                      if(fmtValue.endsWith("%"))
303                      {
304                          rangeIsPercentage =true;
305                      }
306                      else if(fmtValue.startsWith("$"))
307                      {
308                          rangeIsCurrency=true;
309             
310                      }
311                      else
312                      {
313                          rangeIsDefault=true;
314                      }
315                      //rangeIsDefault=false;
316                      //if(!cell.getFormat().isPercent())
317                      // rangeIsPercentage=false;
318                  }
319                  ////////////////
320                  DecimalFormatSymbols dfs = new DecimalFormatSymbols(locale);
321                  DecimalFormat formatter = new DecimalFormat();
322                  formatter.setDecimalFormatSymbols(dfs);
323             
324                  Number number = null;
325             
326                  try {
327                    // need this formatter so that we can properly render jfreecharts
328                    number = formatter.parse(String.valueOf(value));
329                  }
330                  catch (Exception e) {
331                    logger.error(e);
332                    number = null;
333                  }
334             
335                  return number;
336                }
337              */

338             private float toFloat(double input) {
339                 float output = 1.0f;
340
341                 try {
342                     output = (float) input;
343                 } catch (Exception JavaDoc e) {
344                     logger.warn(e);
345                 }
346
347                 return output;
348             }
349                     
350                     
351     private List JavaDoc getDefaultColorPalette(){
352             List JavaDoc palette = new LinkedList JavaDoc();
353             palette.add(new Color JavaDoc(51,102,54));
354             palette.add(new Color JavaDoc(153,204,255));
355             palette.add(new Color JavaDoc(153,153,51));
356             palette.add(new Color JavaDoc(204,153,51));
357             palette.add(new Color JavaDoc(0,102,102));
358             palette.add(new Color JavaDoc(51,153,255));
359             palette.add(new Color JavaDoc(153,51,0));
360             palette.add(new Color JavaDoc(204,204,53));
361             palette.add(new Color JavaDoc(102,153,204));
362             palette.add(new Color JavaDoc(153,153,204));
363             palette.add(new Color JavaDoc(204,204,204));
364             palette.add(new Color JavaDoc(102,153,153));
365             palette.add(new Color JavaDoc(204,204,102));
366             palette.add(new Color JavaDoc(204,102,0));
367             palette.add(new Color JavaDoc(153,153,255));
368             palette.add(new Color JavaDoc(0,102,204));
369             palette.add(new Color JavaDoc(153,204,204));
370             palette.add(new Color JavaDoc(153,153,153));
371             palette.add(new Color JavaDoc(255,204,0));
372             palette.add(new Color JavaDoc(0,153,153));
373             palette.add(new Color JavaDoc(153,204,51));
374             palette.add(new Color JavaDoc(255,153,0));
375             palette.add(new Color JavaDoc(153,153,102));
376             palette.add(new Color JavaDoc(51,153,102));
377             palette.add(new Color JavaDoc(204,204,51));
378             return palette;
379     }
380     
381     public void formatNumberAxis(NumberFormat JavaDoc numberFormatter, CategoryPlot plot){
382 // format range if it is percent/currency
383
// TODO - need to bring this in from enhanced chart component
384
if(numberFormatter != null){
385                 NumberAxis numberAxis = (NumberAxis)plot.getRangeAxis();
386                 numberAxis.setNumberFormatOverride(numberFormatter);
387         }
388         
389         /*
390            if(!rangeIsDefault && (catPlot.getRangeAxis() instanceof NumberAxis))
391            {
392                NumberAxis axis=(NumberAxis)catPlot.getRangeAxis();
393                if(rangeIsPercentage && !rangeIsCurrency)
394                {
395         
396                    axis.setNumberFormatOverride(NumberFormat.getPercentInstance());
397                }
398                else if(rangeIsCurrency && !rangeIsPercentage)
399                {
400                   NumberFormat fmt=NumberFormat.getCurrencyInstance();
401                   fmt.setMaximumFractionDigits(0);
402                   fmt.setMinimumFractionDigits(0);
403                   axis.setNumberFormatOverride(fmt);
404                }
405            }
406          */

407     }
408
409
410     public void customizeSlicer(JFreeChart chart,
411             Result result,
412             Font JavaDoc slicerFont,
413             int slicerPosition,
414             int slicerAlignment) {
415         logger.debug("customizing slicer position: " + slicerPosition);
416                 TextTitle slicerText = new TextTitle(
417                         buildSlicer(result),
418                         slicerFont,
419                         this.createHorizontalAlignment(slicerAlignment) );
420
421                 slicerText.setPosition( this.createRectangleEdge(slicerPosition) );
422                 chart.addSubtitle(slicerText);
423         
424     }
425                     
426 }
427
Popular Tags