2013-01-13 67 views
5

這裏是一個try塊,它用於通過table_job過濾來查找與關鍵字匹配的行。但是,當表模型發生變化時,我正努力獲得正確的行索引。它始終選取第一行,即使篩選結果顯示不是第一行。過濾後的JTable正確的行號

我知道你可以做一些與fireTableDataChanged(),但我不知道在何處以及如何做到這一點,在trycatch塊或setLabelText()方法,顯示該表爲. 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... 
    } 
內容

String table_click0 = (table_job.getModel().getValueAt(row, 0).toString());正在拾取錯誤的行,而不是更新的選定行。我怎樣才能考慮到這一點?

+1

1)1號線的空白就足夠了! 2)爲了更快地獲得更好的幫助,請發佈[SSCCE](http://sscce.org/)(將數據庫中的因子排除並對某些數據進行硬編碼)。 3)這可能需要['convertRowIndexToModel(int viewRowIndex)'](http://docs.oracle.com/javase/7/docs/api/javax/swing/JTable.html#convertRowIndexToModel%28int%29)。 –

+0

我想你想看看[JTable#convertRowIndexToModel](http://docs.oracle.com/javase/7/docs/api/javax/swing/JTable.html#convertRowIndexToModel(int))。您可能還想閱讀[如何使用表格,排序和過濾](http://docs.oracle.com/javase/tutorial/uiswing/components/table.html#sorting) – MadProgrammer

+0

@MadProgrammer @Andrew - 謝謝,我應該通過什麼作爲論點。因爲'table_job.convertRowIndexToModel();'單獨是非法的,它應該在'setLabelText()'還是在try catch塊中 – Hoody

回答

9

你可能需要你的「行」值轉換爲模型索引值(如果你row值從一個「視圖」點檢索),使用convertRowIndexToModel。所以,只是更換

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

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

快速修復:如何獲得實際的行篩選列表中的代碼

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