Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert ArrayList to DefaultListModel

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;
}
like image 266
Patrick Avatar asked Oct 02 '13 19:10

Patrick


2 Answers

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

 DefaultListModel<JListValues> model = new DefaultListModel<>()
 for(JListValues val : array)
         model.addElement(val);
like image 154
Sage Avatar answered Nov 14 '22 04:11

Sage


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());
like image 4
johnny Avatar answered Nov 14 '22 03:11

johnny