Search code examples
javajtabletablemodel

Hidden column but not read the correct value


I create a simple JTable with TableModel, and I hidden the first column. I set at my JTable also the TableRowSorter This is the code that I use to create a table

tableModelArticoliVendere = new MyTableModelDescrizioneArticoli();
tableArticoliVendere = new CustomTableArticoliDaVendereBar(tableModelArticoliVendere);  
sorter = new TableRowSorter<MyTableModelDescrizioneArticoli>(tableModelArticoliVendere);
tableArticoliVendere.setRowSorter(sorter);
tableArticoliVendere.addMouseListener(new MyMouseAdapterArticoliDaVendere());
tableArticoliVendere.removeColumn(tableArticoliVendere.getColumnModel().getColumn(0));

If the user click on the one row of the table the mouse listenere are called.

This is the method:

public class MyMouseAdapterArticoliDaVendere extends MouseAdapter {
    public void mouseClicked(MouseEvent me) {
        JTable t = (JTable)me.getSource();
        if (me.getClickCount() == 1) {
            String codiceArticolo =((JTable)tableArticoliVendere).getModel().getValueAt(t.getSelectedRow(), 0).toString();
            inserisciProdotto(codiceArticolo);
        }
    }
}

The problem is this: If I see the complete table and I clik on the one of the row table, I read the codiceArticolo right. If I use the row filter, and I try to click on the first row I have an error.

I have the table with 3 row for example:

TABLE
 column 0| column 1
 ------------------
 valore1 | 1
 valore2 | 2
 valore3 | 3 

If I use the filter I have this situation:

 TABLE
 column 0| column 1
 ------------------
 valore2 | 2
 valore3 | 3 

if I try to click on the first row, the value of codiceArticolo is valore1 and not valore2.

If I not hidden the column 0, I don't have this error.


Solution

  • When you have sorting or filtering enabled in your table, the indexes of table rows and columns stop lining up with indexes of the model rows and columns. You can account for this using convertRowIndexToModel and convertColumnIndexToModel.

    For instance, when you use t.getSelectedRow(), you can adjust like this:

    int tableRowIndex = t.getSelectedRow();
    int modelRowIndex = t.convertRowIndexToModel(tableRowIndex);
    

    It will also help if you indicate in your code when you are using view indexes and when you are using model indexes.