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