本文介绍了将ArrayList转换为DefaultListModel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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).

代码如下:

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

推荐答案

添加以下代码以将arraylist值添加到DefaultListModel应该可以:

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

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

这篇关于将ArrayList转换为DefaultListModel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 18:15