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)
listDepartments.setBounds(189, 33, 1, 1);- don't use setBounds(...). Swing was designed to be used with a layout manager. And definitely don't use a width/height of 1 (this will be nothing to paint). First get a simple example working where you hard code the data in the JList. Then once you understand the basics of Swing you make the code more dynamic by getting the data from a database. If you need more help then post a proper SSCCE of your code that uses hardcoded data.SetBoundsis created automatically when I draged-droped the JList.