Convert ArrayList to DefaultListModel

浪尽此生 提交于 2019-12-01 17:26:01

问题


I'm beginner in Java. I really need to return DefaultTableModel (javax.swing) from array or ArrayList. It is possible? I can't insert array into DefaultTableModel (constructor).

Code is below:

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;
}

回答1:


adding the following code for adding arraylist values to DefaultListModel should work:

 DefaultListModel<JListValues> model = new DefaultListModel<>()
 for(JListValues val : array)
         model.addElement(val);



回答2:


with the following, there is no need to iterate through a data set and is much more efficient.

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());


来源:https://stackoverflow.com/questions/19144855/convert-arraylist-to-defaultlistmodel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!