传输List数据到jtable中

前一段时间在做一个swing程序的时候,需要通过jtable来显示数据,但是发现向jtable中传输多行数据发现不好做

然后我采用java面向对象的思想做了一些简单的封装,下面是源代码:

public class JTableDataUtil
{
private Class clazz;


public JTableDataUtil(Class clazz)
{
this.clazz = clazz;
}
/**
* 该方法是把保存好的list数据保存到vector中,方便
* 向jtable中传输多行数据
* @param list
* @return
*/
public List getVector(List list)
{
List vectorList = new ArrayList();
Field[] fields = clazz.getDeclaredFields();
for (T t : list)
{
// Class clazz = obj.getClass();
// Field[] fields = clazz.getDeclaredFields();
Vector vector = new Vector();
for (Field field : fields)
{
try
{
PropertyDescriptor pd = new PropertyDescriptor(
field.getName(), clazz);
Method getMethod = pd.getReadMethod();
Object value = getMethod.invoke(t);
vector.add(value);
} catch (IntrospectionException e)
{
e.printStackTrace();
} catch (InvocationTargetException e)
{
e.printStackTrace();
} catch (IllegalAccessException e)
{
e.printStackTrace();
}
}
vectorList.add(vector);
}
return vectorList;
}


/**
* 该方法是把保存好的list数据保存到Object[][]2维数组中,方便
* 向jtable中传输多行数据
* @param list
* @return
*/
public Object[][] getObjData(List list)
{
Field[] fields = clazz.getDeclaredFields();
Object[][] data = new Object[list.size()][fields.length];
for (int i = 0; i < list.size(); i++)
{
T t = (T) list.get(i);
Object[] a = new Object[fields.length];
for (int j = 0; j < fields.length; j++)
{
Field field = fields[j];
try
{
PropertyDescriptor pd = new PropertyDescriptor(
field.getName(), clazz);
Method getMethod = pd.getReadMethod();
Object value = getMethod.invoke(t);
a[j] = value;
} catch (IntrospectionException e)
{
e.printStackTrace();
} catch (InvocationTargetException e)
{
e.printStackTrace();
} catch (IllegalAccessException e)
{
e.printStackTrace();
}
}
data[i] = a;
}
return data;
}


/**
* 该方法是把javabean封装的数据保存到vector方便jtable使用
* @param t
* @return
*/
public Vector addData(T t)
{
Field[] fields = clazz.getDeclaredFields();
Vector vector = new Vector();
for (Field field : fields)
{
try
{
PropertyDescriptor pd = new PropertyDescriptor(field.getName(),
clazz);
Method getMethod = pd.getReadMethod();
Object value = getMethod.invoke(t);
vector.add(value);
} catch (IntrospectionException e)
{
e.printStackTrace();
} catch (InvocationTargetException e)
{
e.printStackTrace();
} catch (IllegalAccessException e)
{
e.printStackTrace();
}
}
return vector;
}
}

你可能感兴趣的:(传输List数据到jtable中)