5

我是Java的初学者。我真的需要从数组中返回DefaultTableModel( ) 或. 有可能的?我无法将数组插入(构造函数)。javax.swingArrayListDefaultTableModel

代码如下:

private DefaultListModel model;


public DefaultListModel getNamesAndIdToCombobox(Connection conn, boolean closeConn, String sql) throws SQLException {

    long counter = 0;

    try {
        Statement stmt = 
                conn.prepareStatement(sql);
        ResultSet rs = stmt.executeQuery(sql);

        while (rs.next()) {
            // String longKey = (String)rs.getString(2);
            try
            {
                jListList.add(new JListValues(rs.getLong(2), rs.getString(1)));
            }
            catch(SQLException sqlException){}

            try
            {
                jListList.add(new JListValues(rs.getLong(2), rs.getLong(1)));
            }
            catch(SQLException sqlException){}

            try
            {
                jListList.add(new JListValues(rs.getString(2), rs.getLong(1)));
            }
            catch(SQLException sqlException){}
            counter++;

        }
        JListValues[] array = jListList.toArray(new JListValues[jListList.size()]);


        model = new DefaultListModel(array);       // HERE IT IS A PROBLEM

        LOGGER.info("getNamesAndIdToCombobox result count: " + counter);
    } catch (SQLException e) {
        LOGGER.error("Error", e);
        throw e;
    } finally {
        try {
            if (closeConn == true)
                conn.close();
        } catch (Exception e) {/* null */
        }
    }
    return model;
}
4

2 回答 2

4

添加以下代码以添加 arraylist 值DefaultListModel应该可以工作:

 DefaultListModel<JListValues> model = new DefaultListModel<>()
 for(JListValues val : array)
         model.addElement(val);
于 2013-10-02T19:25:09.253 回答
4

使用以下内容,无需遍历数据集并且效率更高。

JList<String> jlist = new JList<String>(new String[]{"a","b","c","d"});

DefaultListModel<String> defaultListModel = (DefaultListModel<String>)jlist.getModel();

ArrayList<String> arrayList = Collections.list(defaultListModel.elements());
于 2014-09-09T20:40:06.297 回答