Reputation: 891
I have a jbutton which loads data from a DB, and then populates a jtable (using a DefaultTableModel)
Then, I have this event on the row selection of the table:
jTableDettagliFattura.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent event) {
int selected= jTableDettagliFattura.getSelectedRow();
String id = jTableDettagliFattura.getModel().getValueAt(selected, 0).toString();
System.out.println(id);
}
});
When I load the table for the first time (using the button), everything works fine. But if I select one of the table rows, and then reload the table with the button, I get the "java.lang.ArrayIndexOutOfBoundsException: -1", at the command "jTableDettagliFattura.setModel(model);" (that was perfectly working the first time).
What could be the problem? Is the selection event somehow "ruining" my model?
Upvotes: 0
Views: 112
Reputation: 324088
But if I select one of the table rows, and then reload the table with the button, I get the "java.lang.ArrayIndexOutOfBoundsException: -1"
There is no row selected when the model is reloaded. The listener probably fires an event to indicate the selection was removed.
Try:
int selected = jTableDettagliFattura.getSelectedRow();
if (selected == -1) return;
The main point is don't assume a row is selected. Validate the index before doing your processing.
Upvotes: 2