KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > opensymphony > webwork > components > table > renderer > NumericCellRenderer


1 /*
2  * Copyright (c) 2002-2003 by OpenSymphony
3  * All rights reserved.
4  */

5 package com.opensymphony.webwork.components.table.renderer;
6
7 import com.opensymphony.webwork.components.table.WebTable;
8
9 import java.text.DecimalFormat JavaDoc;
10
11
12 /**
13  * @author $author$
14  * @version $Revision: 1.1 $
15  */

16 public class NumericCellRenderer extends AbstractCellRenderer {
17     //~ Instance fields ////////////////////////////////////////////////////////
18

19     DecimalFormat JavaDoc _formater = new DecimalFormat JavaDoc();
20
21     /**
22      * this is the format string that DecimalFormat would use.
23      *
24      * @see DecimalFormat
25      */

26     String JavaDoc _formatString = null;
27
28     /**
29      * if set the is the color to use if Number is negative.
30      */

31     String JavaDoc _negativeColor = null;
32
33     /**
34      * if set this is the color to render if number is positive
35      */

36     String JavaDoc _positiveColor = null;
37
38     //~ Constructors ///////////////////////////////////////////////////////////
39

40     public NumericCellRenderer() {
41         super();
42     }
43
44     //~ Methods ////////////////////////////////////////////////////////////////
45

46     public String JavaDoc getCellValue(WebTable table, Object JavaDoc data, int row, int col) {
47         StringBuffer JavaDoc retVal = new StringBuffer JavaDoc(128);
48
49         if (data == null) {
50             return "";
51         }
52
53         if (data instanceof Number JavaDoc) {
54             double cellValue = ((Number JavaDoc) data).doubleValue();
55
56             if (cellValue >= 0) {
57                 processNumber(retVal, _positiveColor, cellValue);
58             } else {
59                 processNumber(retVal, _negativeColor, cellValue);
60             }
61
62             return retVal.toString();
63         }
64
65         return data.toString();
66     }
67
68     public void setFormatString(String JavaDoc format) {
69         _formatString = format;
70         _formater.applyPattern(_formatString);
71     }
72
73     public void setNegativeColor(String JavaDoc color) {
74         _negativeColor = color;
75     }
76
77     public void setPositiveColor(String JavaDoc color) {
78         _positiveColor = color;
79     }
80
81     protected void processNumber(StringBuffer JavaDoc buf, String JavaDoc color, double cellValue) {
82         if (color != null) {
83             buf.append(" <font color='").append(color).append("'>");
84         }
85
86         buf.append(_formater.format(cellValue));
87
88         if (color != null) {
89             buf.append("</font>");
90         }
91     }
92 }
93
Popular Tags