我想創建一個5列的空表並添加行到它。我創建了一個單獨的表模型類,擴展了AbstractTableModel
。將行添加到模型但未添加。獲取arrayindex超出範圍例外
類是:
public class MyTableModel extends AbstractTableModel
{
private String[] columnNames = {"Name",
"Size",
"Directory",
"Last Modified Time",
"Readable"};
Object[][] data=new Object[][]{
};
public int getColumnCount()
{
return columnNames.length;
}
public String getColumnName(int col)
{
return columnNames[col];
}
public Class getColumnClass(int c)
{
return getValueAt(0, c).getClass();
}
public boolean isCellEditable(int row, int col)
{
if (col < 1)
{
return false;
}
else
{
return false;
}
}
public void setValueAt(Object value, int row, int col)
{
data[row][col]=value;
}
public void updateJarTable(Object[] row)
{
setValueAt(row[0],0,0);
fireTableDataChanged();
setValueAt(row[1],0,1);
fireTableDataChanged();
setValueAt(row[2],0,2);
fireTableDataChanged();
setValueAt(row[3],0,3);
fireTableDataChanged();
setValueAt(row[4],0,4);
fireTableDataChanged();
}
@Override
public int getRowCount() {
// TODO Auto-generated method stub
return data.length;
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
// TODO Auto-generated method stub
return data[rowIndex][columnIndex];
}
}
在此之後我創建一個表,並應用該TableModel來作爲:
table=new JTable(new MyTableModel());
當我點擊一個按鈕,一個新的行應被追加。
submit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
Object[] row={"col1","col2","col3","col4","col5"};
model1.updateJarTable(row);
table.revalidate();
}
});
其中MODEL1是:
private MyTableModel model1=new MyTableModel();
但是當我運行它在我的方法獲得ArrayIndexOutofBoundsException
:updateJarTable
和setValueAt
我不知道在哪裏出了問題。請幫我找到它。謝謝 !
最好使用DefaultTableModel而不是重新實現自己的表模型的輪子 – StanislavL