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 java.text.DateFormat;
23  import java.util.Date;
24  import javax.swing.table.DefaultTableCellRenderer;
25  import org.xnap.commons.util.StringHelper;
26  
27  /***
28   * Renders time for a table cell. If the value is an Integer object it
29   * is rendered as a length. If value is a Long object it is rendered
30   * as absolute time relative to the 1.1.1970.
31   */
32  public class TimeCellRenderer extends DefaultTableCellRenderer
33  {
34  
35  	private DateFormat dateFormat;
36  
37  	public TimeCellRenderer(DateFormat dateFormat) 
38      {
39  		this.dateFormat = dateFormat;
40  		
41  		setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
42      }
43  
44  	public TimeCellRenderer() 
45      {
46  		this(DateFormat.getDateInstance());
47      }
48  
49  	protected void setValue(Object value) 
50  	{
51  		if (value == null) {
52  			super.setValue(null);
53  		}
54  		else if (value instanceof Integer) {
55  			int i = ((Number)value).intValue();
56  			super.setValue((i >= 0) ? StringHelper.formatLength(i) : null);
57  		}
58  		else if (value instanceof Long) {
59  			long l = ((Long)value).longValue();
60  			super.setValue((l >= 0) ? dateFormat.format(new Date(l)) : null);
61  		}
62  		else if (value instanceof Date) {
63  			super.setValue(dateFormat.format((Date)value));
64  		}
65  		else {
66  			throw new IllegalArgumentException("Expected Integer, Long or java.util.Date; received " + value.getClass());
67  		}
68  	}
69  	
70  }