Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Database table items don't display in JList

Tags:

java

mysql

swing

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)

like image 643
Munchmallow Avatar asked Dec 13 '25 07:12

Munchmallow


1 Answers

Changed with JTable and added followed codes in public addDepartment()

model = new DefaultTableModel();
tableDepartments = new JTable(model);

removed listDepartments.setModel(listModel); from update_departments() function.

like image 126
Munchmallow Avatar answered Dec 15 '25 20:12

Munchmallow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!