我正在尝试从表中获取项目并将它们显示到JList中。我运行了代码,JList中没有显示任何内容,也没有错误。我调试了代码并计算到表项长度。 关注this回答。
static Connection conn = new DBConnection().connect();
private JList listDepartments = null;
public AddDepartment() {
listDepartments = new JList();
listDepartments.setBounds(189, 33, 1, 1);
contentPane.add(listDepartments);
update_departments(listDepartments);
}
private static void update_departments(JList listDepartments) {
try {
String sql = "Select * FROM Departments";
PreparedStatement pstmt = conn.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery();
DefaultListModel listModel = new DefaultListModel();
while (rs.next()) {
System.out.println("inside while");
String departmentName = rs.getString("Name");
listModel.addElement(departmentName);
}
listDepartments.setModel(listModel);
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex);
}
}
表格内容: 姓名:部门
专栏:
Id - INT主键,自动增量,唯一
名称 - VARCHAR(255)
答案 0 :(得分:2)
使用JTable进行了更改,并在public addDepartment()
model = new DefaultTableModel();
tableDepartments = new JTable(model);
从listDepartments.setModel(listModel);
函数中删除update_departments()
。