java - Unable to get column names as headers into JTable -
i have code should create jtable column hearders based on field names returned query. reason code not working, new java , have been doing research cant seem find issue is. appreciated.
public void inittable(){ try { defaulttablemodel tblmodel = new defaulttablemodel() { @override public boolean iscelleditable(int row, int column) { return false; } }; tblmain.setmodel(tblmodel); tblmain.setselectionmode(listselectionmodel.single_selection); //tblmain.gettableheader().setreorderingallowed(false); connection dbconn = dbconn(); statement stmt = dbconn.createstatement(); string qry = "select * services"; resultset rs = stmt.executequery(qry); int numcols = rs.getmetadata().getcolumncount(); system.out.println("num cols: " + numcols); (int col = 1; col <= numcols; col++){ tblmodel.addcolumn(rs.getmetadata().getcolumnlabel(col)); //tblmodel.addcolumn("tmp"); system.out.println(col + " - " + rs.getmetadata().getcolumnlabel(col)); } int row = 0; while (rs != null && rs.next()){ tblmodel.addrow(new object[0]); tblmodel.setvalueat(rs.getstring("serviceid"), row, 0); tblmodel.setvalueat(rs.getstring("institution"), row, 1); tblmodel.setvalueat(rs.getstring("doctor"), row, 2); tblmodel.setvalueat(rs.getstring("street"), row, 3); tblmodel.setvalueat(rs.getstring("city"), row, 4); tblmodel.setvalueat(rs.getstring("state"), row, 5); tblmodel.setvalueat(rs.getstring("zipcode"), row, 6); tblmodel.setvalueat(rs.getdate("date"), row, 7); tblmodel.setvalueat(rs.getdouble("cost"), row, 8); tblmodel.setvalueat(rs.getint("servicetypeid"), row, 9); tblmodel.setvalueat(rs.getstring("comments"), row, 10); row++; } rs.close(); } catch (exception e){ e.printstacktrace(); } }
not related problem suggest better way add data model.
instead of creating empty array , using setvalueat(...) can change looping code like:
while (rs != null && rs.next()) { vector<object> row = new vector<object>(11); tblmodel.addrow(new object[0]); row.add(rs.getstring("serviceid")); row.add(rs.getstring("institution")); ... row.add(rs.getstring("comments")); tblmodel.addrow( row ); }
reasons approach:
the defaulttablemodel stores data in vector. data array copied vector. save resources using vector beginning.
the code shorter type. makes easier rearrange columns since don't need worry indexes.
every time invoke setvalueat(...) method event generated tell table paint itself. happening 12 times, once addrow() method , once each setvalueat() method. using addrow() method @ end generate 1 event.
Comments
Post a Comment