编译时的组合框错误

时间:2013-07-27 08:02:03

标签: java swing arraylist jcombobox comboboxmodel

我希望组合框在运行时从数据库中存储名称,所以我创建了一个列表,但是组合框显示错误......

        List<String> s = new ArrayList<String>();
        {
            try
            {
                Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                Connection con =DriverManager.getConnection("jdbc:odbc:project","sa","123456");
                Statement stmt= con.createStatement();
                ResultSet rs=stmt.executeQuery("SELECT Name FROM company");
                i=0;
                while(rs.next()) {
                    s.add(rs.getString("Name"));
                }
            }
            catch(Exception ex) {             {
                JOptionPane.showConfirmDialog(f,ex);
            }
            cb=new JComboBox(s);
        }

1 个答案:

答案 0 :(得分:5)

可能的问题是您将List<String>引用传递给JComboBox。一种正确的方法是将List<String> s转换为String[]数组并将其传递给constructor: JComboBox(E[] items)

 new JComboBox(s.toArray(new String[s.size()]));

另请阅读How to Use Combo Boxes