最近我遇到了一个奇怪的问题。每当我尝试删除属于DefaultTableModel对象的TableModelListener中的行时,我得到的是ArrayOutOfBounds Exception 0> = 0,1> = 1(取决于我选择的)我在这里发现了类似的问题:
java.lang.ArrayIndexOutOfBoundsException: 0 >= 0 attempting to populate JTable
然而,仍然无法修复它。我的目的是当用户在组合框中选择删除选项时,我只想完全删除该行。 removeRow()方法顺便在侦听器之外正常工作。这是代码和解释:
String[] columnNames = {"Kargo ID",
"Alıcı Adres",
"Ağırlık(KG)",
"Tutar(TL)",
"Alım Saati","Durum","İletim Saati"};
Object[][] data = {
{new Integer(3), "Sinan Caddesi",
new Integer(100), new Integer(5),"" ,"",""}};
final DefaultTableModel dtm = new DefaultTableModel(data,columnNames);
final JTable table = new JTable(dtm){
@Override
public boolean isCellEditable(int row, int column) {
return column == 5;//Combobox column
}
};
//Making Combobox
TableColumn c = table.getColumnModel().getColumn(5);
JComboBox comboBox = new JComboBox();
comboBox.addItem("");
comboBox.addItem("Delete");
c.setCellEditor(new DefaultCellEditor(comboBox));
//System.out.println(dtm.getRowCount());
table.setPreferredScrollableViewportSize(new Dimension(500, 70));
table.setFillsViewportHeight(false);
//I printed row and column numbers, they re correct.
dtm.addTableModelListener(new TableModelListener() {
@Override
public void tableChanged(TableModelEvent e) {
int row = e.getFirstRow();
int column = e.getColumn();
DefaultTableModel model = (DefaultTableModel)e.getSource();
Object data = model.getValueAt(row, column);
//System.out.println(data); DATA IS CORRECT
if(((String)data).equals("Delete"))
dtm.removeRow(row);//Exception Here
//System.out.println(row + " " + column);
}
});
我错过了一些重点吗?任何帮助将不胜感激。
答案 0 :(得分:3)
“非常”的基本想法是,在调用TableModel#setValue
时,您要检查已修改的column
。如果column
是(在这种情况下)5
,您需要检查价值是多少......
例如......
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
if (columnIndex == 5) {
if ("Delete".equals(aValue)) {
removeRow(rowIndex);
}
}
}
请注意,上面的示例会覆盖setValueAt
的默认行为,因此,如果您依赖于模型中更新的值,则需要调用super.setValueAt(...)