I have spent a few days trying to get my JTable sorting correctly. I know the code I have to use, but cannot seem to get it for 'fit' and work into my code. I am getting the TableModel data from a database so if i call the getColumnClass() when initalising the model, I get a NullPointerException (of course), but I can't seem to get the getColumnClass(int) to work anywhere else such as model.getColumnClass(columnIndex). I only need to sort the first column in numerical order as the rest are strings. Here is my code. (ps: this is the first time using JBDC so I most likely have errors in the order I am calling - or maybe doing it in 'longhand' haha)
public JTable memberList() { JTable jTable1; DefaultTableModel model; model = new DefaultTableModel(); jTable1 = new JTable(model); TableRowSorter sorter = new TableRowSorter(model); try { Statement stmt = conn.createStatement(); String sql = "select rm.race_no,cm.firstname,cm.lastname,cm.phone,cm.dob,cm.email,cm.TwinTown_ID,rm.disqualified,cm.notes\n" + "from competitor_master cm join competitor_season cs on cm.competitor_id = cs.competitor_id\n" + "inner join race_master rm on cs.race_no= rm.race_no where cm.twintown_id is not null and cs.season_start_year in (year(sysdate()))\n" + "group by (race_no);"; ResultSet rs = stmt.executeQuery(sql); String b = "", c = "", d = "", e = "", f = "", g = "", h = "", i = ""; int a; model.addColumn("Member Number"); model.addColumn("First Name"); model.addColumn("Last Name"); model.addColumn("Phone"); model.addColumn("Date of Birth"); model.addColumn("Email"); model.addColumn("TT Member Number"); model.addColumn("Disqualified"); model.addColumn("Notes"); while(rs.next()) { a = rs.getInt(1); b = rs.getString("FirstName"); c = rs.getString("LastName"); d = rs.getString("phone"); e = rs.getString("dob"); f = rs.getString("email"); g = rs.getString("TwinTown_ID"); h = rs.getString("disqualified"); i = rs.getString("notes"); model.addRow(new Object[] {a,b,c,d,e,f,g,h,i}); model.getColumnClass(1); } stmt.close(); rs.close(); } catch (SQLException ex) { } jTable1.getTableHeader().setFont(new Font("Microsoft Tai Le", Font.BOLD, 14)); jTable1.getTableHeader().setBackground(Color.WHITE); jTable1.getTableHeader().setForeground(new Color(234, 168, 82)); jTable1.getTableHeader().setBorder(null); jTable1.setRowSorter(sorter); return jTable1; }
public Class getColumnClass (int column){ if (column==1) { return(Integer.class); } return(String.class); }