如何在AbstractTableModel中表示复杂类?

时间:2010-11-20 01:05:10

标签: java user-interface swing abstracttablemodel

我有这堂课:

public abstract class Directory {

    protected int id;
    protected File path;
    protected LinkedList<Filter> filters;
    protected LinkedList<File> files;
    protected int wildcard;
    public static int numCols = 3;

    /* other things */
}

我写了这个表模型:

public class DirectoryListTableModel extends AbstractTableModel {

    private static final long serialVersionUID = 1L;
    private LinkedList<Directory> datalist;
    private String[] columnNames= {"ID", "Directory", "Wildcard", "Filters"};


    public DirectoryListTableModel(){
    }

    public void setDatalist(LinkedList<Directory> temp){
        this.datalist = temp;
    }

    public void showElement(){
        fireTableRowsInserted(this.datalist.size()-2,this.datalist.size()-2);
    }

    public LinkedList<Directory> getDatalist(){
        return (LinkedList<Directory>) this.datalist.clone();
    }

    @Override
    public String getColumnName(int column) {
        return this.columnNames[column];    
    }

    @Override
    public int getColumnCount() {
        return Directory.numCols;
    }

    @Override
    public int getRowCount() {
        return this.datalist.size();
    }

    @Override
    public Object getValueAt(int row, int col) {

        Directory temp = this.datalist.get(row);

        switch(col){
        case 0:
            return temp.getId();
        case 1:
            return temp.getPath();
        case 2:
            return temp.getWildcard();
        default:
            return null;        
        }
    }
}

正如您所看到的,我有一个LinkedList<Filter>,我想将其显示为一个简单的字符串。我怎么能这样做?

1 个答案:

答案 0 :(得分:2)

e.g:

case 3:
    return temp.getFilters().toString();

注意:

  • 在声明字段时使用接口(例如List)而不是实现(LinkedList)(如果你没有充分的理由不这样做)。
  • 在大多数情况下,ArrayList比LinkedList具有更好的性能(例如,通过索引访问)
  • 同时覆盖getColumnClass
  • 让您的字段保密“
  • setDatalist:fireTableDataChanged