001: /*
002: * $Id: NumericCellRenderer.java 471756 2006-11-06 15:01:43Z husted $
003: *
004: * Licensed to the Apache Software Foundation (ASF) under one
005: * or more contributor license agreements. See the NOTICE file
006: * distributed with this work for additional information
007: * regarding copyright ownership. The ASF licenses this file
008: * to you under the Apache License, Version 2.0 (the
009: * "License"); you may not use this file except in compliance
010: * with the License. You may obtain a copy of the License at
011: *
012: * http://www.apache.org/licenses/LICENSE-2.0
013: *
014: * Unless required by applicable law or agreed to in writing,
015: * software distributed under the License is distributed on an
016: * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
017: * KIND, either express or implied. See the License for the
018: * specific language governing permissions and limitations
019: * under the License.
020: */
021: package org.apache.struts2.components.table.renderer;
022:
023: import java.text.DecimalFormat;
024:
025: import org.apache.struts2.components.table.WebTable;
026:
027: /**
028: */
029: public class NumericCellRenderer extends AbstractCellRenderer {
030:
031: DecimalFormat _formater = new DecimalFormat();
032:
033: /**
034: * this is the format string that DecimalFormat would use.
035: *
036: * @see DecimalFormat
037: */
038: String _formatString = null;
039:
040: /**
041: * if set the is the color to use if Number is negative.
042: */
043: String _negativeColor = null;
044:
045: /**
046: * if set this is the color to render if number is positive
047: */
048: String _positiveColor = null;
049:
050: public NumericCellRenderer() {
051: super ();
052: }
053:
054: public String getCellValue(WebTable table, Object data, int row,
055: int col) {
056: StringBuffer retVal = new StringBuffer(128);
057:
058: if (data == null) {
059: return "";
060: }
061:
062: if (data instanceof Number) {
063: double cellValue = ((Number) data).doubleValue();
064:
065: if (cellValue >= 0) {
066: processNumber(retVal, _positiveColor, cellValue);
067: } else {
068: processNumber(retVal, _negativeColor, cellValue);
069: }
070:
071: return retVal.toString();
072: }
073:
074: return data.toString();
075: }
076:
077: public void setFormatString(String format) {
078: _formatString = format;
079: _formater.applyPattern(_formatString);
080: }
081:
082: public void setNegativeColor(String color) {
083: _negativeColor = color;
084: }
085:
086: public void setPositiveColor(String color) {
087: _positiveColor = color;
088: }
089:
090: protected void processNumber(StringBuffer buf, String color,
091: double cellValue) {
092: if (color != null) {
093: buf.append(" <font color='").append(color).append("'>");
094: }
095:
096: buf.append(_formater.format(cellValue));
097:
098: if (color != null) {
099: buf.append("</font>");
100: }
101: }
102: }
|