这是一个处理表格过程的类filtering
//类 DbUtils
public class DbUtils {
public static TableModel resultSetToTableModel(ResultSet rs) {
try {
ResultSetMetaData metaData = rs.getMetaData();
int numberOfColumns = metaData.getColumnCount();
Vector columnNames = new Vector();
for (int column=0; column < numberOfColumns; column++) {
columnNames.addElement(metaData.getColumnLabel(column + 1));
}
Vector rows = new Vector();
while(rs.next()) {
Vector newRow = new Vector();
for (int i =1; i <= numberOfColumns; i++) {
newRow.addElement(rs.getObject(i));
}
rows.addElement(newRow);
}
return new DefaultTableModel(rows,columnNames);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
我有一个更新类 Job_GUI 中的作业表的方法,传入的参数是sql statements
从中table_job
填充的。传入什么 sql 语句取决于在JTabbedPane
考虑index
值的情况下选择哪个。这就是我的问题所在。
//类Job_GUI
public void UpdateJobTable(String sql) {
try {
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
table_job.setModel(DbUtils.resultSetToTableModel(rs));
table_job.getColumnModel().getColumn(0).setPreferredWidth(50);
table_job.getColumnModel().getColumn(1).setPreferredWidth(140);
table_job.getColumnModel().getColumn(2).setPreferredWidth(170);
table_job.getColumnModel().getColumn(3).setPreferredWidth(80);
table_job.getColumnModel().getColumn(4).setPreferredWidth(120);
}
catch (Exception e ) {
JOptionPane.showMessageDialog(null, e);
}
finally {
try {
pst.close();
rs.close();
} catch (Exception e) {
}
}
}
private void JobTabbedPaneStateChanged(javax.swing.event.ChangeEvent evt) {
JTabbedPane sourceTabbedPane = (JTabbedPane) evt.getSource();
int index = sourceTabbedPane.getSelectedIndex();
if (index == 0) {
jobTableInit();
}
else if (index == 1) {
fillCombo();
}
else if(index==2) {
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);
JScrollPane pane = new JScrollPane(table_job);
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();
}
}
当我处于index 2
模式时,table_job
内容被擦除,即返回索引 0,表变为空,而最初它充满了数据。当我在索引 2 时,我不想table_job
为空,而是仍然继续显示数据,除非在keyword
中输入a,否则JTextField
调整table_job
为搜索匹配项。但 table_job 没有显示任何内容。我在索引 2 的 if 块中的代码片段中做错了什么,也许我在其他地方错了?