JXTable and primary key – how to.
Today I will describe in a few words and a couple lines of code how to get the id of the row in JXTable. When working with data coming from database we don’t really want to display the primary key of the object but to hide it. This can cause a small problem once we want to find out for example which item was clicked, ok we can easily find out which row it was but its not always easy to find out which actual object it was especially when using JXTable sorting capabilities.
The whole trick is to get the the corresponding object from the model and not from the view.
Here is a short code snippet to do just that, hope that helps everyone who uses great JXTable component to display some data.
int rowx = table.getSelectedRow();
int resultx = 0;
if (rowx < 0) {
return 0;
}
resultx = table.convertRowIndexToModel(rowx);
int id = (Integer) table.getModel().getValueAt(resultx, 0);
return id;
}
This works of course assuming that your object index is set as first column in your model (position 0).