ArrayIndexOutOfBoundsException: -1 on JTable creation/tablechanged

心不动则不痛 提交于 2019-12-06 05:44:21

A rowIndex of -1 (==TableModelEvent.HEADER_ROW) indicates that the model's structure has changed completely. Such an event is fired internally by the JTable on setModel. Read the api doc of TableModelEvent to fully understand which types/values to expect in the listener's tableChanged.

BTW, @AKJ is right - no need to fire any TableModelEvents in your table code. Make the model fire the events as appropriate

This means that you are passing -1 as row or column. This is not permitted - make sure you pass a correct value.

I have a feeling that your problem is here:

TableModelEvent tme = new TableModelEvent(tableModel);      
this.tableChanged(tme); 
->
  int column = e.getColumn();     
  AbstractTableModel model = (AbstractTableModel)e.getSource();     
  String columnName = model.getColumnName(column); 

Because you haven't specified a row or column value, the getColumn() and getRow() calls will return -1, which you are then passing to getValueAt().

Try looking at the constructor for TableModelEvent. It has options for specifying those row/column values.

TableModelEvent tme = new TableModelEvent(tableModel);
this.tableChanged(tme);

I don't see any need of this call. As pointed by other posters this is the cause of your problem.

If you are implementing the table model correctly, whenever you update the table model the jtable will automatically get notifications and you don't need to write the tableChanged() method as well. So I am lost why you need to call tableChanged() explicitly.

Whenever you want to update the table just update the model. Also at first glance there does not seem to be any threading issue involved.

Your AnnoTable constructor is leaking references to the incompletely constructed "this" object. Also, registering Listeners from the constructor is not safe. enter link description here

Build your objects doing the least amount of work possible in the constructor and then operate on the fully built objects. Add listeners, adjust the models, fireEvents etc...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!