View Javadoc

1   /*
2    *  XNap Commons
3    *
4    *  Copyright (C) 2005  Steffen Pingel
5    *
6    *  This library is free software; you can redistribute it and/or
7    *  modify it under the terms of the GNU Lesser General Public
8    *  License as published by the Free Software Foundation; either
9    *  version 2.1 of the License, or (at your option) any later version.
10   *
11   *  This library is distributed in the hope that it will be useful,
12   *  but WITHOUT ANY WARRANTY; without even the implied warranty of
13   *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14   *  Lesser General Public License for more details.
15   *
16   *  You should have received a copy of the GNU Lesser General Public
17   *  License along with this library; if not, write to the Free Software
18   *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19   */
20  package org.xnap.commons.gui.table;
21  
22  import javax.swing.table.DefaultTableCellRenderer;
23  
24  /***
25   * A cell renderer for {@link Number} objects. 
26   */
27  public class NumberCellRenderer extends DefaultTableCellRenderer {
28  
29      private int precision;
30  	private long minValue;
31  	private String formatString;
32  
33      public NumberCellRenderer(long minValue, int precision) 
34      {
35  		this.minValue = minValue;
36  		
37  		setPrecision(precision);
38  		setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
39      }
40  
41      public NumberCellRenderer(long minValue)
42      {
43  		this(minValue, 0);
44      }
45  
46      public NumberCellRenderer()
47      {
48  		this(0, 0);
49      }
50  
51      /***
52       * Sets the position of the decimal separator.
53       */
54      public void setPrecision(int newValue) 
55      {
56  		setFormatString("%,f." + precision);
57      }
58  
59  	public void setFormatString(String formatString) 
60      {
61  		this.formatString = formatString;
62      }
63  
64  	public String getFormatString()
65  	{
66  		return formatString;
67  	}
68  	
69      public void setValue(Object value) 
70      {
71  		if (value instanceof Number) {
72  			double d = ((Number)value).doubleValue();
73  			if (d >= minValue) {
74  				super.setValue(String.format(formatString, d));
75  				return;
76  			}
77  		}
78  
79  		super.setValue(null);
80      } 
81  }