JTable封装

//用于保存字段信息
public
class TableTitle { private int with ; private String columnName; private String attributeName; public TableTitle(int with,String columnName,String attributeName){ this.with = with; this.columnName = columnName; this.attributeName = attributeName; } public int getWith() { return with; } public void setWith(int with) { this.with = with; } public String getColumnName() { return columnName; } public void setColumnName(String columnName) { this.columnName = columnName; } public String getAttributeName() { return attributeName; } public void setAttributeName(String attributeName) { this.attributeName = attributeName; } }

 

public class TestTable {
    
    private DefaultTableModel dtm= null;
    
    private JTable table;
    
    /**
     * 添加数据
     * @param dateSource
     * @param listTitle
     * @param table
     */
    public void initTable(List dateSource,List listTitle,JTable table){
        this.table = table;
        setTitle(listTitle);
    
        for (int i = 0; i < dateSource.size(); i++) {
            try {
                Object[] ot = new Object[listTitle.size()];
                for (int j = 0; j < listTitle.size(); j++) {
                    if(j==2){
                    }else{
                        TableTitle tt = (TableTitle)listTitle.get(j);
                        Object obj = dateSource.get(i);
                        ot[j] = PropertyUtils.getSimpleProperty(obj,tt.getAttributeName());
                    }
                }
                this.dtm.addRow(ot);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            }
        }
    }
    /**
     * 设置表格的标题
     * @param li
     * @param table
     */
    public void setTitle(List li){
        this.table.setAutoResizeMode(this.table.AUTO_RESIZE_OFF);
        this.dtm = new DefaultTableModel();
        for (int i = 0; i < li.size(); i++) {
            TableTitle tt = (TableTitle)li.get(i);
            this.dtm.addColumn(tt.getColumnName());
            this.table.setModel(dtm);
        }
        for (int j = 0; j < li.size(); j++) {
            TableTitle tt = (TableTitle)li.get(j);
            this.table.getColumnModel().getColumn(j).setPreferredWidth(tt.getWith());
        }
    }
}

 

posted on 2013-09-22 15:42  定数  阅读(437)  评论(0)    收藏  举报

导航