I am trying to get items from a table and display them into JList. I ran the code and nothing was displayed in JList and there was no error. I debugged the code and it counted until table item length. Followed this answer.
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);
}
}
Table Content: Name: Departments
Columns:
Id - INT primary key, auto increment, unique
Name - VARCHAR(255)