数据库表项不显示在JList中

时间:2016-10-28 21:09:13

标签: java mysql swing

我正在尝试从表中获取项目并将它们显示到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)

1 个答案:

答案 0 :(得分:2)

使用JTable进行了更改,并在public addDepartment()

中添加了后续代码
model = new DefaultTableModel();
tableDepartments = new JTable(model);

listDepartments.setModel(listModel);函数中删除update_departments()