Alexander Paudak
Alexander Paudak

Reputation: 155

How to get data on JTable when using RowSorter?

I am having problem in getting the data when selecting a row from a JTable. This happens whenever I enable setAutoCreateRowSorter(true) of the table. So far this is what I did:

private void displayBooks(){
    bookTable.setAutoCreateRowSorter(true);
    bookTable.getTableHeader().setFont(new java.awt.Font("Century Gothic", 1, 14));
    dtm = (DefaultTableModel) bookTable.getModel();
    clearTable(dtm);
    for(Book book: books){
        dtm.addRow(new Object[]{book.getId(), ...//rest of the code
    }
}

On the bookTableMouseClicked method this is what I did:

 ...
 if(bookTable.getSelectedRow() >= 0){
     Book book = books.get(bookTable.getSelectedRow());
        setBook(book);
 }...

I am now having ambiguous data when I clicked the header table to sort the data.

Upvotes: 0

Views: 153

Answers (2)

camickr
camickr

Reputation: 324108

The problem is that you are storing data in two places:

  1. in the TableModel
  2. in an ArrayList

The data should only be stored in the TableModel. This way you don't need to worry about syncing the data since it is only in one place.

You could simply create a Book object from the selected row by using getValueAt(..) method of the JTable. You would need to invoke that method for each column in the table.

Or the other approach is to create a custom TableModel that holds Book objects, then you could just get the Book object directly from the table. This is a little more work, but it is the better approach.

Check out Row Table Model for a step-by-step approach on how to create a custom TableModel for a custom object.

Upvotes: 0

Thomas Kläger
Thomas Kläger

Reputation: 21435

The selected row number on a JTable instance is always the selected row number on the view side.

If you activate row sorters this no longer matches the row number on the model side.

To transform between these two row numbers the JTable offers methods for converting from "view row index" to "model row index" and vice versa. These methods are named convertRowIndexToModel and convertRowIndexToView.

In your mouseClicked handler you need to call the function convertRowIndexToModel as follows:

if (bookTable.getSelectedRow() >= 0){
    Book book = books.get(bookTable.convertRowIndexToModel(bookTable.getSelectedRow()));
    setBook(book);
}

Upvotes: 3

Related Questions