将 TableRowSorter 添加到表及其相应模型后,任何相应的添加(专门在 firetabletablerowsinserted 处)都会导致异常。从测试中可以清楚地看出,GetRowCount() 返回的值超出了模型范围。但是,在添加排序器或过滤器后如何继续向表中添加值对我来说没有意义?
例如,我在向表中添加任何内容之前设置行过滤器,然后在模型中使用以下调用向表中添加一个值:
this.addRow(row, createRow(trans,row));
this.fireTableRowsInserted(this.getRowCount(), this.getRowCount());
rowcount 的大小为 1 并且抛出异常:
java.lang.IndexOutOfBoundsException: Invalid range
at javax.swing.DefaultRowSorter.checkAgainstModel(Unknown Source)
at javax.swing.DefaultRowSorter.rowsInserted(Unknown Source)
at com.gui.model
如果我执行相同的步骤而不首先添加排序器,一切都很好。我假设我可能需要通知模型排序器可能已进行更改并尝试了以下操作,但仍然返回异常:
this.addRow(row, createRow(trans,row));
this.fireTableStructureChanged()
this.fireTableRowsInserted(this.getRowCount(), this.getRowCount());
我什至尝试在调用 fire 之前通知模型内的排序器,一个值已添加到模型中,如下所示,但它也失败了:
this.addRow(row, createRow(trans,row));
if(sorter.getRowFilter() != null){
//if a sorter exists we are in add notify sorter
sorter.rowsInserted(getRowCount(), getRowCount());
}
this.fireTableRowsInserted(this.getRowCount(), this.getRowCount());
最后,我对 FireTableRowsInsterted(0,0) 进行了硬编码,它不会引发任何异常。但没有任何内容添加到表中?所以,我知道这肯定是某种类型的越界问题。
我查遍了一切,似乎找不到答案。如果有人知道这是如何工作的,那将会非常有帮助。
下面是在 jpanel 中设置排序器的代码:
messageTable.setRowSorter(null);
HttpTransactionTableModel m = getTransactionTableModel();
final int statusIndex = m.getColIndex("status");
RowFilter<Object,Object> startsWithAFilter = new RowFilter<Object,Object>() {
public boolean include(Entry<? extends Object, ? extends Object> entry) {
for(char responseCode:responseCodes)
{
if (entry.getStringValue(statusIndex).startsWith(Character.toString(responseCode))) {
return true;
}
}
// None of the columns start with "a"; return false so that this
// entry is not shown
return false;
}
};
m.sorter.setRowFilter(startsWithAFilter);
messageTable.setRowSorter(m.sorter);
这是我的模型中为模型增加价值的代码:
public void update(Observable o, Object evt) {
if (evt instanceof ObservableEvent<?>) {
ObservableEvent<?> event = (ObservableEvent<?>) evt;
if (event.getElement() instanceof HttpTransaction) {
HttpTransaction trans = (HttpTransaction) event.getElement();
// handle adding of an element
if (event.getAction() == PUT) {
if (includeTransaction(trans)) {
// handle request elements
if (trans.getRequest() != null && idMap.get(trans.getID()) == null) {
idMap.put(trans.getID(), count++);
// transactionManager.save(trans);
int row = idMap.get(trans.getID());
this.addRow(row, createRow(trans,row));
if(sorter.getRowFilter() != null){
sorter.rowsInserted(getRowCount(), getRowCount());
}
this.fireTableRowsInserted(this.getRowCount(), this.getRowCount());
}