Issue
I have a class that extends JTable. In that class I create a customer table that is populated. When I click on a specific row I want to take out the ID field of that selected row.
Now my issue is that all info I find speaks of using a
table.getColumnModel().... table.convertRowIndex ....
But inside my anonymous event ListSelectionListener I cannot get this to work. It does not want to use the this. to reflect to the JTable and I cannot use table. as that is not recognized.
@Component
public class CustomersTable extends JTable {
private final CustomerService customerService;
public CustomersTable(CustomerService customerService) {
this.customerService = customerService;
String[] columnNames = new String[]{"Id", "Voornaam", "Achternaam", "Email", "Telefoon", "Straat", "Nummer",
"Postcode", "Stad", "Commentaar"};
DefaultTableModel tableModel = new DefaultTableModel(columnNames, 0);
this.setModel(tableModel);
List<CustomerEntity> allCustomer = this.customerService.getAllCustomer();
for (CustomerEntity entity : allCustomer) {
tableModel.addRow(entity.getForJTable());
}
// De selectie van de rij
ListSelectionModel model = this.getSelectionModel();
model.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
model.addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
if(!model.isSelectionEmpty()) {
// get selected row
// long id = this.getColumnModel().getColumnIndex("Id");
int selectedRow = model.getMinSelectionIndex();
// openCustomerCard(selectedRow);
}
}
});
}
}
Solution
// long id = this.getColumnModel().getColumnIndex("Id");
The "this" refers to the instance of your ListSelectionListener.
To access the instance of the JTable you can use:
JTable table = CustomersTable.this;
However this is not the best design. Don't extend JTable.
You should only extend a class when you add functionality to to the class. Creaating the TableModel or adding a listener is not adding functionality.
Read the section from the Swing tutorial on How to Use Tables. The TableFilterDemo
shows how to use the ListSelectionListener.
Now my issue is that all info I find speaks of using a table.getColumnModel()....
There is no need to use the column model. You get the data from the TableModel:
int row = table.getSelectedRow();
long id = table.getModel().getValueAt(row, 0);
table.convertRowIndex ....
You only need to use that method in you are sorting or filtering the table, but yes it is good practice to use that method just to be safe:
int row = table.convertRowIndexToModel( table.getSelectedRow() );
long id = table.getModel().getValueAt(row, 0);
Answered By - camickr
Answer Checked By - Timothy Miller (JavaFixing Admin)