Hoody
Hoody

Reputation: 3062

JTable correct row number after filtering

Here is a try block which serves the purpose of filtering through table_job to find rows which match keyword. However, when the table model changes, I am struggling to obtain the correct row index. It always picks the the first row, even though the filtered result shows a row which is not first.

I understand you can do something with fireTableDataChanged(), but I am not sure HOW and WHERE to do this, in the try and catch block OR in the setLabelText() method which displays the content of the table as . JLabel

try 
{
    sql = "SELECT Job.jobID as 'Job ID', Employer.name as'Company', Job.title as 'Role', Job.description as  'Description', Job.type as 'Type', Job.benefits as 'Benefits', Job.closing as 'Closing Date' FROM Job INNER JOIN Employer ON Job.employerID=Employer.employerID ORDER BY Employer.name";
    pst = conn.prepareStatement(sql);
    rs = pst.executeQuery();
    TableModel model = DbUtils.resultSetToTableModel(rs);
    table_job.setModel(model);
    final TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(model);
    table_job.setRowSorter(sorter);               
    searchJob.addActionListener(new ActionListener()
    {

        public void actionPerformed(ActionEvent e) 
        {
            String text = keyword.getText(); 
            if (text.length() == 0) 
            {
                sorter.setRowFilter(null);
            } 
            else 
            {
                sorter.setRowFilter(RowFilter.regexFilter(text));
            }
        }             
    });
}
catch (Exception e) 
{
    e.printStackTrace();                
}

private void setLabelText() 
{
    try 
    {
        String table_click0 = (table_job.getModel().getValueAt(
                row, 0).toString());
        String sqlSt = "SELECT Employer.name, * FROM Job INNER JOIN Employer ON Job.employerID = Employer.employerID WHERE jobID='"+table_click0+"' ";
        //rest of code to Label text...
    }

The String table_click0 = (table_job.getModel().getValueAt(row, 0).toString()); is picking up the wrong row, not the updated selected row. How can I take this into account?

Upvotes: 5

Views: 8694

Answers (2)

errod1
errod1

Reputation: 21

Quick fix: how to get the actual row in a filtered list

int row=getjTable().getSelectedRow();
if (getjTable().getRowSorter()!=null) {
    row = getjTable().getRowSorter().convertRowIndexToModel(row);
}

Upvotes: 0

Guillaume Polet
Guillaume Polet

Reputation: 47608

You probably need to convert your "row" value to a model index value (if your row value is retrieved from a "view" point of view), using convertRowIndexToModel. So just replace

String table_click0 = (table_job.getModel().getValueAt(row, 0).toString());

with

String table_click0 = table_job.getModel().getValueAt(table_job.
                          convertRowIndexToModel(row), 0).toString());

Upvotes: 9

Related Questions