我花了几天时间试图正确地进行JTable排序。我知道我必须使用的代码,但似乎无法获得它适合'并研究我的代码。我从数据库中获取TableModel数据,所以如果我在初始化模型时调用getColumnClass(),我得到一个NullPointerException(当然),但我似乎无法让getColumnClass(int)在其他任何地方工作例如model.getColumnClass(columnIndex)。我只需要按数字顺序对第一列进行排序,其余的是字符串。这是我的代码。 (ps:这是第一次使用JBDC,所以我很可能在我打电话的顺序中有错误 - 或者可能在' longhand'哈哈)
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); }
答案 0 :(得分:1)
它正在排序,但仅按第一个数字排序。所以这样排序:123 17 22 28 45 5 56 66
因为它将所有数据都视为字符串数据。
model = new DefaultTableModel();
jTable1 = new JTable(model);
您正在使用DefaultTableModel和JTable的默认实现。 getColumnClass(...)
方法的默认实现只返回Object.class,因此每个对象的toString()值都会被排序。
您不会手动调用getColumnClass()方法,您需要覆盖getColumnClass(...)
的{{1}}方法:
TableModel