将数组存储在JTable列中

时间:2017-01-11 14:14:42

标签: java swing jtable

我想使用for循环在JTable列中显示数组的值。

我的代码如下所示:

public class MigTable extends FormsTableModel implements XmlInterface {

    private Element srcDoc = null;
    private String string = null;
    private ArrayList<Integer>data =new ArrayList<Integer>(Arrays.asList(20,10,100));

    public MigTable(Element element, String string) {
        super(element,string);

    }

    @Override
    public Class<?> getColumnClass(int columnIndex) {
        switch (columnIndex){
            case 0: return  super.getColumnClass(0);
            case 1: return super.getColumnClass(1);
            case 2: return Integer.class;
            default: return Object.class;
        }
    }

    @Override
    public int getColumnCount() {
        return 3;
    }

    @Override
    public String getColumnName(int columnIndex) {
        switch(columnIndex){
            case 0: return super.getColumnName(0);
            case 1: return super.getColumnName(1);
            case 2: return "status";
        }

        return null;
    }


    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
            // Here I'm getting the values 
            if (columnIndex==2){
                // I would like to do it here so that at column Index 2 has the datas
                //from the array list 20 10 100
            }
        }
        return super.getValueAt(rowIndex, columnIndex);
    }

    @Override
    public boolean isCellEditable(int i, int i2) {
        // TODO Implement this method
        return false;
    }

    @Override
    public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
        if (rowIndex > getColumnName(columnIndex).length())
            throw new IllegalArgumentException ("" + rowIndex);
        super.setValueAt(aValue, rowIndex, columnIndex);
    }
}

感谢您的帮助

1 个答案:

答案 0 :(得分:0)

这是你的意思吗?

@Override
public Object getValueAt(int rowIndex, int columnIndex) {
    // here i am getting values 
    if (columnIndex==2){
        // i would like to do it here so that at column Index 2 has the datas from the array list 20 10 100 }
        if (rowIndex < data.size()) {
            return data.get(rowIndex);
        } else {
            return null;
        }
    }
    return super.getValueAt(rowIndex, columnIndex);
}

(我还没有测试过)

编辑:另一个选项,授予您的超类可以处理它,将数据放在那里。例如,DefaultTableModel可以。在构造函数中添加几行:

public MigTable(Element element, String string) {
    super(element,string);
    for (int index = 0; index < data.size(); index++) {
        setValueAt(data.get(index), index, 2);
    }
}

使用此功能,您无需覆盖getValueAt()