swing - NullPointerException in Java TableRowSorter -
i made jtable list of chemicals in inventory can sort each columns using following code (chemicaltable name of jtable):
chemicaltable.setautocreaterowsorter(true); tablerowsorter<tablemodel> sorter1 = new tablerowsorter<tablemodel>(chemicaltable.getmodel()); chemicaltable.setrowsorter(sorter1); then used jtextfield create searchbox keytyped listener whenever user types character table refreshes. , works.
i used code in keytypedlistener searchbox:
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 * chemicallist name_of_reagent '%" + 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); } my problem is: whenever sort first columns (col1, col2, or col3) , insert character in searchbox, got error message:
"exception occurred during event dispatching: java.lang.nullpointerexception"
although it's not possible debug code fragments, several things stand out:
in same section, reference
tablemodeldm,chemicaltable.getmodel(); use single reference or verify refer same instance.instead of meddling
setrowcount(), use 1 ofaddrow()methods.the
defaulttablemodelmethods alter model fire correct event , table automatically update accordingly; shouldn't have yourself.
Comments
Post a Comment