如何将多个项目添加到 DefaultComboBoxModel [英] How to add multiple items to the DefaultComboBoxModel

查看:40
本文介绍了如何将多个项目添加到 DefaultComboBoxModel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码,但我不知道如何将所有项目添加到我的组合框中.

I have the following code but I don't know how to add all of the items to my combobox.

DefaultTableModel rs = MyDB.DataTable("SELECT `Activity` FROM `transactions` WHERE `Group` = '" + Gname.getText()+ "' OR `Group` = 'ALL'");

DefaultComboBoxModel dmc = new DefaultComboBoxModel();

dmc.addElement("");

if (rs.getRowCount() > 0) {
    dmc.addElement(rs.getValueAt(0,0).toString());
}

cboItem.setModel(dmc);

它只向我的 DefaultTableModel 添加一项,我该如何添加所有项?

It only adds one item to my DefaultTableModel, how can I add all of them?

推荐答案

DefaultComboBoxModel 的构造函数采用 Object[].您可以首先遍历 rs 值准备一个数组(或列表),然后将此数组传递给 DefaultComboBoxModel 构造函数.像这样...

The constructor of DefaultComboBoxModel takes Object[]. You can first iterate over the rs values prepare an array (or list) and then pass this array to DefaultComboBoxModel constructor. Like this ...

DefaultTableModel rs = MyDB.DataTable("SELECT `Activity` FROM `transactions` WHERE `Group` = '" + Gname.getText()+ "' OR `Group` = 'ALL'");
int columnCount = rs.getColumnCount();
int rowCount = rs.getRowCount();

List <Object> values = new ArrayList<Object>();
for (int rowIndex = 0; rowIndex < rowCount; rowIndex ++){
    for(int columnIndex = 0; columnIndex < columnCount; columnIndex++){
         Object value = rs.getValueAt(rowIndex , columnIndex );
         values.add(value);
    }
}
DefaultComboBoxModel dmc = new DefaultComboBoxModel(values.toArray());

这篇关于如何将多个项目添加到 DefaultComboBoxModel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆