Yow,我正在尝试在我的 jFrame 中添加一个 jTable,并且我想将我的数据库表中的记录显示到 jTable 中。
我能够创建一个 jTable(我将代码放在构造函数中)并在代码中手动输入要显示的值。有效。但是当我尝试调用从数据库中检索数据的方法并尝试在 jtable 中显示它们时。它给了我一个错误“NullPointerException”。
我的构造函数中创建表的代码:
String[] columnname = {"Subject Code", "Prelim", "Midterm", "SemiFinal", "Finals"};
setTable();
Object[][] data = {};
gradetable = new JTable(data, columnname){
public boolean isCellEditable(int data, int columns){
return false;
}
public Component prepareRenderer(TableCellRenderer r, int data, int columns){
Component c = super.prepareRenderer(r, data, columns);
if (data % 2 == 0){
c.setBackground(Color.GRAY);
}
else{
c.setBackground(Color.WHITE);
}
if (isCellSelected(data, columns)){
c.setBackground(Color.ORANGE);
}
return c;
}
};
gradetable.setPreferredScrollableViewportSize(new Dimension (400, 150));
gradetable.setFillsViewportHeight(true);
jsp = new JScrollPane(gradetable);
我用来从数据库中检索数据并将它们添加到表中的方法:
private void setTable(){
DefaultTableModel model = (DefaultTableModel)gradetable.getModel();
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con = (Connection)DriverManager.getConnection("jdbc:mysql://localhost:3306/grading","root","");
Statement st = con.createStatement();
String sql = "SELECT * FROM student INNER JOIN grade ON student.idnumber = grade.idnumber WHERE student.idnumber = '2010-00125'";
ResultSet rs = st.executeQuery(sql);
model.setRowCount(0);
while (rs.next()){
//this.setName(rs.getString("name"));
//this.setCourse(rs.getString("course"));
//this.setYear(rs.getString("year"));
String d1, d2, d4, d3, d5;
d1 = rs.getString("subjectcode");
d2 = rs.getString("prelim");
d3 = rs.getString("midterm");
d4 = rs.getString("semifinal");
d5 = rs.getString("finals");
model.addRow(new Object[]{d1,d2,d3,d4,d5});
}
rs.close();
con.close();
}catch(ClassNotFoundException | SQLException ex){
JOptionPane.showMessageDialog(null, ex);
}
}