`
jerry_shen
  • 浏览: 89229 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

一个非常好用的Grid类及其相关类

    博客分类:
  • Java
阅读更多
这里是我写的一个Grid类,可以用作数据表示,传输。Excel解析等等方面。这里的源码是四年前的代码原型。等项目过一阶段我会放出现在和spring BindException集成的版本。
/**
 * <p>
 * Grid description
 * </p>
 * 
 * @author Jerry Shen
 * @version v 1.0 Dec. 1st, 2004 
 * ---------------------------------------------------------------------------
 * @History
 */
package com.infosys.redpas.model;

import java.util.ArrayList;
import java.util.TreeMap;

public class Grid {
	
	private Row[] rows;

	private Modeler rowModeler;

	private int width = 0;	
	
	private TreeMap metaData;
	
	private Row metaRow;
	
	public Grid(){
		super();
		rowModeler = new DefaultModeler();
		metaData = new TreeMap();
		metaRow = null;
	}
	
	public Grid(Modeler m){
		this();
		setRowModeler(m);
	}
	
	/**
	 * @return Returns the rowModeler.
	 */
	public Modeler getRowModeler() {
		return rowModeler;
	}
	/**
	 * @param rowModeler The rowModeler to set.
	 */
	public void setRowModeler(Modeler rowModeler) {
		this.rowModeler = rowModeler;
	}
	/**
	 * @return Returns the width.
	 */
	public int getWidth() {
		return width;
	}
	/**
	 * @param width The width to set.
	 */
	public void setWidth(int width) {
		this.width = width;
	}
	
	// Get the rows count of the grid
	public int getHeight(){
		if (rows==null)
			return 0;
		return rows.length;
	}
	
	// set up the grid table head row
	public void setMetaRow(Row r){
		if (getHeight()==0&& r != null && r.getFieldsNumber() > 0 ){
			metaRow = r;
			setWidth(r.getFieldsNumber());
		}
		else if (getWidth()> 0 && r.getFieldsNumber()==getWidth()){
			metaRow = r;
		}
	}
	
	// get the grid table head row
	public Row getMetaRow(){
		if (metaRow != null)
			return metaRow.getRow();
		else 
			return  Row.EMPTY_ROW;
	}
	
	// get the grid table head by col
	public String getRowHead(int col){
		Row r = getMetaRow();
		if (r!=null && !(r.getField(col)==null ||"".equals(r.getField(col))))
				return r.getField(col);
		else
			return "";
	}
	
	// add a row to the grid, the row will be validated
	public void addRow(Row r){
		if (rowModeler == null||Row.EMPTY_ROW.equals(r))
			return;
		if (!validate(r))
			return;
		if (rows == null) {
			if (getWidth()==0){
				rows = new Row[1];
				rows[0] = r;
				width = r.getFieldsNumber();
				metaRow = new Row(getWidth());
			}
			else if (getWidth() == r.getFieldsNumber()) {
				rows = new Row[1];
				rows[0] = r;
			}else {
				return;
			}
		}
		else if (getWidth() == r.getFieldsNumber()){
			Row[] rs = new Row[getHeight()+1];
			for (int i=0;i<getHeight();i++)
				rs[i] = rows[i];
			rs[getHeight()] = r;
			rows = rs;
		}
		else {
			return;
		}
	}
	
	// remove one row of the grid
	public void removeRow(int pos){
		if (pos < 0 || getHeight() <= pos || rows == null){
			return;
		}
		else if (getHeight() == 1 && pos == 0){
			rows = null;
			return;
		}
		else {
			Row[] rs = new Row[getHeight()-1];
			for (int i=0,j=0; i <getHeight()-1; i++,j++){
				if (j!=pos) {
					rs[i] = rows[j];
				} else {
					i--;
				}
			}
			rows = rs;
		}
	}
	
	// model one row to a Model object
	public Model doModel(int row){
		if (rowModeler == null)
			return null;
		if (row < getHeight() && row >= 0 && (! (rowModeler == null))){
			return rowModeler.doModel(rows[row]);			
		}
		else return null;
	}
	
	// set one field of the grid
	public void setField(int row, int col, String value){
		if (row >=0 && row < getHeight() && col >= 0 && col < getWidth())
			rows[row].setField(col,value);
	}
	
	// get one field of the grid
	public String getField(int row, int col){
		if (row >=0 && row < getHeight() && col >= 0 && col < getWidth() && rows != null)
			return rows[row].getField(col);
		else 
			return null;
	}
	
	// get the row of the grid
	public Row getRow(int row){
		if (row >= 0 && row < getHeight() )
			return rows[row].getRow();
		else 
			return null;
	}
	
	// set one row of the grid, the row will be validated
	public void setRow(int row,Row r){
		if (r.getFieldsNumber()== getWidth() && row >= 0 && row < getHeight() && validate(r))
			rows[row] = r;		
	}
	
	// get the row(use as an colum) of one colum
	public Row getColum(int col){
		if (col >= 0 && col < getWidth()) {
			Row r = new Row(getHeight());
			for (int i=0; i< r.getFieldsNumber();i++)
				r.setField(i,getField(i,col));
			return r;
		}
		else 
			return null;
			
	}	
	
	// set one colum of this grid
	public void setColum(int col,Row colum){
		if (getHeight()==colum.getFieldsNumber()&&col >=0 && col < getWidth()){
			for (int i=0; i < getHeight();i++)
				setField(i,col,colum.getField(i));
		}
	}
	
	// set the meta data carried by the grid
	// if the key is not existed, then create a new key
	public void setMetaData(String key,String value){
		try {
			metaData.put(key, value);
		}catch (Exception e){
		}		
	}
	
	// get the meta data carried with the grid
	// return "" if the meta data is not existed 
	public String getMetaData(String key){
		try {
			String str = (String)metaData.get(key);
			if (str == null || "".equals(str))
				return "";
			else 
				return str;
		}
		catch (Exception e){
			return "";
		}
	}
	
	// generate the model list.
	public ArrayList generateList(){
		ArrayList arr = new ArrayList();
		for (int i=0; i < getHeight();i++) {
			Model m = doModel(i);
			if (m==null)
				return null;
			else 
				arr.add(m);
		}		
		return  arr;		
	}
	
	// print out the grid on the console
	public void consoleShow(){
		for (int i=0; i < getHeight();i++){
			Row r = getRow(i);
			r.consoleShow();
		}
	}
	
	// see wether one row in the grid is validated
	public boolean validate(Row r){
		if (rowModeler == null)
			return false;
		else 
			return rowModeler.validate(r);
	}
	
	// see all the rows in the grid is validated
	public boolean validate(){
		if (rowModeler == null)
			return false;
		else if (getHeight()==0)
			return false;
		else {			
			for (int i=0; i<getHeight();i++){
				if (!validate(rows[i]))
					return false;
			}
			return true;
		}		
	}
	
	// add an model to the grid using the rowmodeler's deModel
	public void addRowByModel(Model m){
		try {
			Row r = rowModeler.deModel(m);
			addRow(r);				
		}catch (Exception e){
		}
	}
	
}


/**
 * <p>
 * Model description
 * </p>
 * 
 * @author Jerry Shen
 * @version v 1.0 Dec. 1st, 2004
 * ---------------------------------------------------------------------------
 * @History
 */
package com.infosys.redpas.model;

import java.io.Serializable;

// This is the parent class for all the models
public class Model implements Serializable{
}

/**
 * <p>
 * Modeler description
 * </p>
 * 
 * @author Jerry Shen
 * @version v 1.0 Dec. 1st, 2004 
 * ---------------------------------------------------------------------------
 * @History
 */

package com.infosys.redpas.model;

public interface Modeler{
	// Model a model from a row
	public Model doModel(Row r);	
	
	// validate to see if the row can model a model
	public boolean validate(Row r);
	
	// deModel a model to a row
	public Row deModel(Model m);
}


/**
 * <p>
 * DefaultModeler description
 * </p>
 * 
 * @author Jerry Shen
 * @version v 1.0 Dec. 2nd, 2004
 * ---------------------------------------------------------------------------
 * @History
 */

package com.infosys.redpas.model;

// The dumb defaultModeler for normal grids
// a Grid must had a Modeler
public class DefaultModeler implements Modeler{

	public Model doModel(Row r){
		return r;
	}
	
	public boolean validate(Row r){
		return true;
	}
	
	public Row deModel(Model m){
		return Row.EMPTY_ROW;
	}
}



/**
 * <p>
 * Row description
 * </p>
 * 
 * @author Jerry Shen
 * @version v 1.0 Dec. 1st, 2004 
 * ---------------------------------------------------------------------------
 * @History modified by Jerry Shen, Dec. 9th, 2004
 */
package com.infosys.redpas.model;

public class Row extends Model{
	private String[] fields;

	public static final Row EMPTY_ROW = new Row();
	
	public Row(int length){
		fields = new String[length];
	}
		
	public Row(){
		this(1);
		setField(0,"");
	}
	
	public Row(String[] row){
		this(row.length);
		setFields(row);
	}
	
	public int getFieldsNumber(){
		Row r= getRow();
		if (r.getField(0)==null ||"".equals(r.getField(0)))
			return 0;
		else 
			return fields.length;
	}
	
	public void setFields(String[] fields){
		this.fields = fields;
	}
	
	public String[] getFields(){
		return fields;
	}
	
	public String getField(int pos){
		if (this==Row.EMPTY_ROW ||fields == null || fields.length < pos + 1 || pos < 0)
			return "";
		else 
			return fields[pos];
	}
	
	public void setField(int pos,String value){
		if (this == Row.EMPTY_ROW ||fields == null || fields.length < pos + 1)
			return;
		else 
			fields[pos] = value;
	}
	
	public String toString(){
		StringBuffer sb = new StringBuffer();
		if (getFieldsNumber()>0){
			for (int i=0; i < getFieldsNumber();i++)
				sb.append(getField(i)).append(", ");
			sb.deleteCharAt(sb.length()-1).deleteCharAt(sb.length()-1);
			return sb.toString();
		}
		else 
			return "";
	}
	
	public void consoleShow(){
		System.out.println(toString());	
	}
	
	public Row getRow(){
		if (fields==null)
			return EMPTY_ROW;
		else {
			for (int i= 0;i<fields.length;i++){
				if (fields[i]!= null)
					return this;
			}
			return EMPTY_ROW;				
		}
	}
	
	public boolean equals(Row r){
		Row thisRow = this.getRow();
		Row thatRow = r.getRow();
		if (thisRow.getFieldsNumber()!=thatRow.getFieldsNumber())
			return false;
		else {
			for (int i = 0; i < thisRow.getFieldsNumber();i++){
				if (!thisRow.getField(i).equals(thatRow.getField(i)))
						return false;
			}
			return true;
		}
	}
}



/**
 * <p>
 * ActualExpenseModeler description
 * </p>
 * 
 * @author Jerry Shen
 * @version v 1.0 Dec. 2nd, 2004
 * ---------------------------------------------------------------------------
 * @History
 */
package com.infosys.budget.modeler;

import com.infosys.budget.model.ActualExpense;
import com.infosys.redpas.model.Model;
import com.infosys.redpas.model.Modeler;
import com.infosys.redpas.model.Row;

public class ActualExpenseModeler implements Modeler{
	private Row row;
	
	public Model doModel(Row r){
		if (!validate(r)) {
			return null;
		}
		else {
			try {
				ActualExpense exp = new ActualExpense();
				String[] rValue = r.getFields();
				exp.setActualExpenseId(rValue[0]);
				exp.setExpenseHeadId(rValue[1]);
				exp.setBudgetId(rValue[2]);
				exp.setMonth(rValue[3]);
				exp.setAmount(Double.parseDouble(rValue[4]));
				exp.setCurrencyId(rValue[5]);
				exp.setExchangeRate(Double.parseDouble(rValue[6]));
				exp.setInputTime(rValue[7]);
				exp.setActualExpenseBatchId(rValue[8]);
				return exp;
			} catch (Exception e){
				return null;
			}
		}	
	}
	
	public boolean validate(Row r){
		if (r==null || r.getFieldsNumber()!= 9)
			return false;
		for (int i=0; i < r.getFieldsNumber();i++){
			if (r.getField(i)==null || "".equals(r.getField(i))){
				return false;
			}
		}
		try {
			Long.parseLong(r.getField(0));
			Long.parseLong(r.getField(1));
			Long.parseLong(r.getField(2));
			Float.parseFloat(r.getField(4));
			Float.parseFloat(r.getField(6));
			Long.parseLong(r.getField(8));
		} catch (Exception e){
			return false;
		}
		return true;
	}
	
	public Row deModel(Model actualModel){
		if (actualModel == null) {
			return Row.EMPTY_ROW;
		}
		else {
			try {
				ActualExpense actual=(ActualExpense)actualModel;
				Row r = new Row(9);
				r.setField(0,actual.getActualExpenseId());
				r.setField(1,actual.getExpenseHeadId());
				r.setField(2,actual.getBudgetId());
				r.setField(3,actual.getMonth());
				r.setField(4,""+actual.getAmount());
				r.setField(5,actual.getCurrencyId());
				r.setField(6,""+actual.getExchangeRate());
				r.setField(7,actual.getInputTime());
				r.setField(8,actual.getActualExpenseBatchId());
				return r;
			} catch (Exception e){
				return Row.EMPTY_ROW;
			}
		}	
	}
}


分享到:
评论
5 楼 jerry_shen 2008-08-24  
没有界面,是用于数据表示的Utils类。
4 楼 nismaster 2008-08-24  
看一下显示的界面拉
3 楼 jerry_shen 2008-08-24  
另两个相关类
/**
 * <p>
 * ActualExpense description
 * </p>
 * 
 * @author Jerry Shen
 * @version v 1.0 Nov. 29th, 2004
 * ---------------------------------------------------------------------------
 * @History
 */
package com.infosys.budget.model;

import com.infosys.redpas.model.Model;

public class ActualExpense extends Model {

	private String actualExpenseId;

	private String expenseHeadId;

	private String budgetId;

	private String month;

	private double amount;

	private String currencyId;

	private double exchangeRate;

	private String inputTime;

	private String actualExpenseBatchId;	

	//	 constructors
	public ActualExpense(){
		super();
	}	
	

	/**
	 * @return Returns the actualExpenseId.
	 */
	public String getActualExpenseId() {
		return actualExpenseId;
	}
	/**
	 * @param actualExpenseId The actualExpenseId to set.
	 */
	public void setActualExpenseId(String actualExpenseId) {
		this.actualExpenseId = actualExpenseId;
	}
	/**
	 * @return Returns the amount.
	 */
	public double getAmount() {
		return amount;
	}
	/**
	 * @param amount The amount to set.
	 */
	public void setAmount(double amount) {
		this.amount = amount;
	}
	/**
	 * @return Returns the budgetId.
	 */
	public String getBudgetId() {
		return budgetId;
	}
	/**
	 * @param budgetId The budgetId to set.
	 */
	public void setBudgetId(String budgetId) {
		this.budgetId = budgetId;
	}
	/**
	 * @return Returns the currencyExchangeRate.
	 */
	public double getExchangeRate() {
		return exchangeRate;
	}
	/**
	 * @param exchangeRate The currencyExchangeRate to set.
	 */
	public void setExchangeRate(double exchangeRate) {
		this.exchangeRate = exchangeRate;
	}
	/**
	 * @return Returns the currencyId.
	 */
	public String getCurrencyId() {
		return currencyId;
	}
	/**
	 * @param currencyId The currencyId to set.
	 */
	public void setCurrencyId(String currencyId) {
		this.currencyId = currencyId;
	}
	/**
	 * @return Returns the expenseHeadId.
	 */
	public String getExpenseHeadId() {
		return expenseHeadId;
	}
	/**
	 * @param expenseHeadId The expenseHeadId to set.
	 */
	public void setExpenseHeadId(String expenseHeadId) {
		this.expenseHeadId = expenseHeadId;
	}
	/**
	 * @return Returns the inputTime.
	 */
	public String getInputTime() {
		return inputTime;
	}
	/**
	 * @param inputTime The inputTime to set.
	 */
	public void setInputTime(String inputTime) {
		this.inputTime = inputTime;
	}
	/**
	 * @return Returns the month.
	 */
	public String getMonth() {
		return month;
	}
	/**
	 * @param month The month to set.
	 */
	public void setMonth(String month) {
		this.month = month;
	}
	/**
	 * @return Returns the actualExpenseBatchId.
	 */
	public String getActualExpenseBatchId() {
		return actualExpenseBatchId;
	}
	/**
	 * @param actualExpenseBatchId The actualExpenseBatchId to set.
	 */
	public void setActualExpenseBatchId(String actualExpenseBatchId) {
		this.actualExpenseBatchId = actualExpenseBatchId;
	}
	public boolean equals(Object o) {
		if (o == null) {
			return false;
		} else if (this == o) {
			return true;
		} else if (o instanceof ActualExpense) {
			ActualExpense that = (ActualExpense) o;
			return that.getActualExpenseId().equals(this.getActualExpenseId());
		} else {
			return false;
		}
	}
	
	public String toString(){
		StringBuffer sb = new StringBuffer();
		sb.append("actualExpenseId:").append(getActualExpenseId()).append("\n")
		.append("amount:").append(getAmount()).append("\n")
		.append("budgetId:").append(getBudgetId()).append("\n")
		.append("exchangeRate:").append(getExchangeRate()).append("\n")
		.append("currencyId:").append(getCurrencyId()).append("\n")
		.append("expenseHeadId:").append(getExpenseHeadId()).append("\n")
		.append("inputTime:").append(getInputTime()).append("\n")
		.append("month:").append(getMonth()).append("\n")
		.append("actualExpenseBatchId").append(getActualExpenseBatchId()).append("\n");
		return sb.toString();
	}
}


/**
 * <p>
 * ActualExpenseBatch description
 * </p>
 * 
 * @author Jerry Shen
 * @version v 1.0 Dec. 3rd, 2004
 * ---------------------------------------------------------------------------
 * @History
 */
package com.infosys.budget.model;

import com.infosys.redpas.model.Model;

public class ActualExpenseBatch extends Model {

	private String actualExpenseBatchId;

	private String budgetId;
	
	private String budgetName;

	private String month;

	private String comments;	

	//	 constructors
	public ActualExpenseBatch(){
		super();
	}	
	

	/**
	 * @return Returns the actualExpenseBatchId.
	 */
	public String getActualExpenseBatchId() {
		return actualExpenseBatchId;
	}
	/**
	 * @param actualExpenseBatchId The actualExpenseBatchId to set.
	 */
	public void setActualExpenseBatchId(String actualExpenseBatchId) {
		this.actualExpenseBatchId = actualExpenseBatchId;
	}
	/**
	 * @return Returns the budgetId.
	 */
	public String getBudgetId() {
		return budgetId;
	}
	/**
	 * @param budgetId The budgetId to set.
	 */
	public void setBudgetId(String budgetId) {
		this.budgetId = budgetId;
	}
	/**
	 * @return Returns the budgetName.
	 */
	public String getBudgetName() {
		return budgetName;
	}
	/**
	 * @param budgetName The budgetName to set.
	 */
	public void setBudgetName(String budgetName) {
		this.budgetName = budgetName;
	}
	/**
	 * @return Returns the comment.
	 */
	public String getComments() {
		return comments;
	}
	/**
	 * @param comment The comment to set.
	 */
	public void setComments(String comment) {
		this.comments = comment;
	}
	/**
	 * @return Returns the month.
	 */
	public String getMonth() {
		return month;
	}
	public String getMonthName() {
		if ("00".equals(month))
			return "Jan";
		else if ("01".equals(month))
			return "Feb";
		else if ("02".equals(month))
			return "Mar";
		else if("03".equals(month))
			return "Apr";
		else if ("04".equals(month))
			return "May";
		else if ("05".equals(month))
			return "Jun";
		else if ("06".equals(month))
			return "Jul";
		else if ("07".equals(month))
			return "Aug";
		else if("08".equals(month))
			return "Sep";
		else if ("09".equals(month))
			return "Oct";
		else if ("10".equals(month))
			return "Nov";
		else if ("11".equals(month))
			return "Dec";
		else 
			return "Jan";
	}
	/**
	 * @param month The month to set.
	 */
	public void setMonth(String month) {
		this.month = month;
	}
	public boolean equals(Object o) {
		if (o == null) {
			return false;
		} else if (this == o) {
			return true;
		} else if (o instanceof ActualExpense) {
			ActualExpense that = (ActualExpense) o;
			return that.getActualExpenseId().equals(this.getActualExpenseBatchId());
		} else {
			return false;
		}
	}
	
	public String toString(){
		StringBuffer sb = new StringBuffer();
		sb.append("actualExpenseBatchId:").append(getActualExpenseBatchId()).append("\n")
		.append("budgetId:").append(getBudgetId()).append("\n")
		.append("comment:").append(getComments()).append("\n")
		.append("month:").append(getMonth()).append("\n");
		return sb.toString();
	}
}
2 楼 jerry_shen 2008-08-23  
Grid类的metaData是元数据,metaRow是题头行,Modeler是造型器,Row是数据行。
1 楼 jerry_shen 2008-08-23  
本质上,这个类是两维电子表格,两维的字符串数据集和他们的一些方便方法的集成。

相关推荐

    【。net 专业】 面试题

    9.对于一个实现了IDisposable接口的类,以下哪些项可以执行与释放或重置非托管资源相关的应用程序定义的任务?(多选) ( ABC ) A.Close B.DisposeC.Finalize D.using E.Quit 10.Net依赖以下哪项技术实现跨语言互用性...

    精通JS脚本之ExtJS框架.part2.rar

    最后利用一个商品信息管理系统和一个企业任务管理系统,向读者演示了ExtJS在实际项目中的应用以及实现流程。  《精通JS脚本之ExtJS框架》附有配套光盘,提供了书中实例的源代码和视频教学文件。此外,读者还可以...

    精通JS脚本之ExtJS框架.part1.rar

    最后利用一个商品信息管理系统和一个企业任务管理系统,向读者演示了ExtJS在实际项目中的应用以及实现流程。  《精通JS脚本之ExtJS框架》附有配套光盘,提供了书中实例的源代码和视频教学文件。此外,读者还可以...

    易语言程序免安装版下载

     静态编译后的易语言EXE/DLL之间不能再共享譬如窗口、窗口组件等类似资源,对于已经静态连接到一个EXE/DLL中的支持库,该支持库中的数据或资源将不能再被其它EXE/DLL中所使用的同名支持库访问。这是因为代码被分别...

    基础地理信息数据库管理系统.doc

    图模板) 布局设置(放大、缩小、全图、漫游、前一视图、后一视图、1:1、比例尺、纸张尺 寸设置,布局缩放调整、布局编辑(图名、说明类注记编辑、简单点、线、面编辑)布 局保存。 打印输出。 10、数据导出 标准...

    VB编程资源大全(源码 网络)

    (11KB) 34,tapi_src.ZIP 一个比较完成的tapi程序,包括一个包含全部tapi定义的模块和一个tapi类,包括查看以建立的tapi连接、拨号、中断连接以及对线路和拨号进行设置。(38KB) 35,rashangup.ZIP ras...

    fedbook:前端修炼小册(Wenyuan's frontend developer book. Including HTML, CSS, JavaScript, etc.)

    记录每一天的进步,越努力,越幸运,欢迎收藏或 star。 与的区别: 博客记录日常开发经验,读书笔记、生活随笔、理财等等,涉及面比较分散。 小册以点亮技能树为主,系统梳理前端开发及其周边知识点,作为学习笔记和...

    电子元器件封装设计规范.pdf

    电⼦元器件封装设计规范 电⼦元器件设计库封装标准 电⼦元器件设计库封装标准 这⾥记录着我所遵循的电⼦... 3.2.1 SMD焊盘命名规范 焊盘命名规范 3.2.2 PTH焊盘命名规范 焊盘命名规范 3.3 电阻类封装命名规范 电阻类封

Global site tag (gtag.js) - Google Analytics