Java 将 ArrayList 转换为 DefaultListModel
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19144855/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert ArrayList to DefaultListModel
提问by Patrick
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).
我是 Java 初学者。我真的需要返回DefaultTableModel
(javax.swing
从数组或)ArrayList
。有可能的?我无法将数组插入DefaultTableModel
(构造函数)。
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;
}
采纳答案by Sage
adding the following code for adding arraylist values to DefaultListModel
should work:
添加以下代码以将 arraylist 值添加到DefaultListModel
应该可以工作:
DefaultListModel<JListValues> model = new DefaultListModel<>()
for(JListValues val : array)
model.addElement(val);
回答by johnny
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());