Reshad
Reshad

Reputation: 2652

getting the id from a row

I have a JTable that shows the result from a database

for(VoertuigenModel m : vModel.selectVoertuigen())
        {   
            if(m.getStatus().equals("Beschikbaar"))
            {
                tableModelVoertuigen.addRow(new Object[]{
                        m.getMerk(),
                        m.getType(),
                        m.getKleur(),
                        m.getStatus(),
                        m.getId()
                });
            }
        }

And this looks like this

Jtable example

Now How can I get the AUTO-ID when from a row that is selected?

For example I want to select the 3rd row then I want to set '4' in a variable.

Upvotes: 0

Views: 2700

Answers (1)

Sage
Sage

Reputation: 15418

Now How can I get the AUTO-ID when from a row that is selected?

  • Add ListSelectionListener to JTable SelectionModel() using addListSelectionListener

  • On Selection event, get the selected row index of the table view using table.getSelectedRow(). Selection data actually describes selected cells in the "view" (table data as it appears after any sorting or filtering) rather than in the table model. while sorting, filtering, or user manipulation of columns, you must convert selection coordinates using the JTable's conversion methods:

    1. convertRowIndexToModel(row): maps the row index of view to underlying TableModel
    2. convertColumnIndexToModel(column): maps the column index of view to underlying TableModel
  • Get the column Index by invoking getColumnIndex("AUTO-ID") on JTable's column model

     table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
    
            @Override
            public void valueChanged(ListSelectionEvent e) {
    
                int row =  table.convertRowIndexToModel(table.getSelectedRow());
                int col = table.getColumnModel().getColumnIndex("AUTO-ID");
    
                int auto_id = (Integer) table.getModel().getValueAt(row, col);
                     // assuming that `m.getId()` is returning `int` 
                    //while adding with addRow() function
            }
        });
    

Note:: use int[] getSelectedRows() function of JTable when you are selecting more then one row and want to work with them.

Upvotes: 1

Related Questions