1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21 package org.apache.struts2.components.table.renderer;
22
23 import java.text.DecimalFormat;
24
25 import org.apache.struts2.components.table.WebTable;
26
27
28 /***
29 */
30 public class NumericCellRenderer extends AbstractCellRenderer {
31
32 DecimalFormat _formater = new DecimalFormat();
33
34 /***
35 * this is the format string that DecimalFormat would use.
36 *
37 * @see DecimalFormat
38 */
39 String _formatString = null;
40
41 /***
42 * if set the is the color to use if Number is negative.
43 */
44 String _negativeColor = null;
45
46 /***
47 * if set this is the color to render if number is positive
48 */
49 String _positiveColor = null;
50
51
52 public NumericCellRenderer() {
53 super();
54 }
55
56
57 public String getCellValue(WebTable table, Object data, int row, int col) {
58 StringBuffer retVal = new StringBuffer(128);
59
60 if (data == null) {
61 return "";
62 }
63
64 if (data instanceof Number) {
65 double cellValue = ((Number) data).doubleValue();
66
67 if (cellValue >= 0) {
68 processNumber(retVal, _positiveColor, cellValue);
69 } else {
70 processNumber(retVal, _negativeColor, cellValue);
71 }
72
73 return retVal.toString();
74 }
75
76 return data.toString();
77 }
78
79 public void setFormatString(String format) {
80 _formatString = format;
81 _formater.applyPattern(_formatString);
82 }
83
84 public void setNegativeColor(String color) {
85 _negativeColor = color;
86 }
87
88 public void setPositiveColor(String color) {
89 _positiveColor = color;
90 }
91
92 protected void processNumber(StringBuffer buf, String color, double cellValue) {
93 if (color != null) {
94 buf.append(" <font color='").append(color).append("'>");
95 }
96
97 buf.append(_formater.format(cellValue));
98
99 if (color != null) {
100 buf.append("</font>");
101 }
102 }
103 }