这里是一个try块,它的目的是通过table_job过滤以查找匹配关键字的行。但是,当表模型改变时,我很难获得正确的行索引。它总是选择第一行,即使过滤后的结果显示的行不是第一行。
我知道你可以用fireTableDataChanged()
做点什么,但我不确定如何和在哪里做到这一点,在try
和catch
块或在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());
选择了错误的行,而不是更新后的选择行。我该如何考虑这一点呢?
您可能需要将"行"值转换为模型索引值(如果您的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());
快速修复:如何在筛选列表中获得实际行
int row=getjTable().getSelectedRow();
if (getjTable().getRowSorter()!=null) {
row = getjTable().getRowSorter().convertRowIndexToModel(row);
}