我为库存中的化学品列表制作了一个 jtable,我可以使用以下代码对每一列进行排序(chemicalTable 是 jTable 的名称):
chemicalTable.setAutoCreateRowSorter(true);
TableRowSorter<TableModel> sorter1
= new TableRowSorter<TableModel>(chemicalTable.getModel());
chemicalTable.setRowSorter(sorter1);
然后,我使用 jTextfield 创建了一个带有 keyTyped 侦听器的搜索框,这样每当用户键入某个字符时,表格就会刷新。它通常有效。
我在搜索框的 keyTypedListener 中使用了这段代码:
DefaultTableModel dm = (DefaultTableModel) chemicalTable.getModel();
str = searchChemicalText.getText();
try {
String url = "jdbc:mysql://localhost/chemical inventory";
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection(url, "root", "");
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "Error Occurred.", "Error", JOptionPane.ERROR_MESSAGE);
}
int ctr = 0;
while (ctr < chemicalTable.getRowCount()) {
chemicalTable.getModel().setValueAt(null, ctr, 0);
chemicalTable.getModel().setValueAt(null, ctr, 1);
chemicalTable.getModel().setValueAt(null, ctr, 2);
ctr++;
}
int count = 0;
try {
Statement stmt = conn.createStatement();
String query = "Select * FROM chemicallist where name_of_reagent like '%" + str + "%'";
ResultSet rs = stmt.executeQuery(query);
if (rs.next()) {
rs = stmt.executeQuery(query);
while (rs.next()) {
String qty = null, qtyunit = null, chemstate = null, reagentName = null;
reagentName = rs.getString("name_of_reagent");
qty = rs.getString("quantity");
qtyunit = rs.getString("quantity_unit");
chemstate = rs.getString("state");
chemicalTable.getModel().setValueAt(reagentName, count, 0);
chemicalTable.getModel().setValueAt(qty + " " + qtyunit, count, 1);
chemicalTable.getModel().setValueAt(chemstate, count, 2);
if (count + 1 > chemicalTable.getRowCount() - 1) {
dm.setRowCount(chemicalTable.getRowCount() + 1);
dm.fireTableRowsInserted(0, 5);
}
count++;
}
}
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "Error Occurred.", "Error", JOptionPane.ERROR_MESSAGE);
}
我的问题是:每当我首先对任何列(col1、col2 或 col3)进行排序并在搜索框中插入一个字符时,都会收到以下错误消息:
“事件调度期间发生异常:Java.lang.NullPointerException”