【发布时间】:2010-11-20 11:21:38
【问题描述】:
我需要用 ArrayList 填充 JComboBox。有没有办法做到这一点?
【问题讨论】:
标签: java swing arraylist jcombobox
我需要用 ArrayList 填充 JComboBox。有没有办法做到这一点?
【问题讨论】:
标签: java swing arraylist jcombobox
【讨论】:
用数组列表填充组合框的优雅方式:
List<String> ls = new ArrayList<String>();
jComboBox.setModel(new DefaultComboBoxModel<String>(ls.toArray(new String[0])));
【讨论】:
我不喜欢接受的答案或@fivetwentysix 关于如何解决这个问题的评论。它采用了一种方法来做到这一点,但没有给出使用 toArray 的完整解决方案。您需要使用 toArray 并为其提供一个类型和大小正确的数组的参数,这样您就不会得到一个 Object 数组。虽然对象数组可以工作,但我认为这不是强类型语言的最佳实践。
String[] array = arrayList.toArray(new String[arrayList.size()]);
JComboBox comboBox = new JComboBox(array);
或者,您也可以只使用 for 循环来保持强类型。
String[] array = new String[arrayList.size()];
for(int i = 0; i < array.length; i++) {
array[i] = arrayList.get(i);
}
JComboBox comboBox = new JComboBox(array);
【讨论】:
DefaultComboBoxModel dml= new DefaultComboBoxModel();
for (int i = 0; i < <ArrayList>.size(); i++) {
dml.addElement(<ArrayList>.get(i).getField());
}
<ComboBoxName>.setModel(dml);
可理解的代码。根据需要编辑<> 类型。
【讨论】:
我相信您可以使用 ArrayList 创建一个新 Vector 并将其传递给 JCombobox 构造函数。
JComboBox<String> combobox = new JComboBox<String>(new Vector<String>(myArrayList));
我的例子只是字符串。
【讨论】:
检查这个简单的代码
import java.util.ArrayList;
import javax.swing.JComboBox;
import javax.swing.JFrame;
public class FirstFrame extends JFrame{
static JComboBox<ArrayList> mycombo;
FirstFrame()
{
this.setSize(600,500);
this.setTitle("My combo");
this.setLayout(null);
ArrayList<String> names=new ArrayList<String>();
names.add("jessy");
names.add("albert");
names.add("grace");
mycombo=new JComboBox(names.toArray());
mycombo.setBounds(60,32,200,50);
this.add(mycombo);
this.setVisible(true); // window visible
}
public static void main(String[] args) {
FirstFrame frame=new FirstFrame();
}
}
【讨论】:
通过组合现有答案(this one 和 this one),将ArrayList 添加到JComboBox 的正确类型安全方法如下:
private DefaultComboBoxModel<YourClass> getComboBoxModel(List<YourClass> yourClassList)
{
YourClass[] comboBoxModel = yourClassList.toArray(new YourClass[0]);
return new DefaultComboBoxModel<>(comboBoxModel);
}
在您的GUI 代码中,您将整个列表设置到您的JComboBox 中,如下所示:
DefaultComboBoxModel<YourClass> comboBoxModel = getComboBoxModel(yourClassList);
comboBox.setModel(comboBoxModel);
【讨论】:
我认为这是解决方案
ArrayList<table> libel = new ArrayList<table>();
try {
SessionFactory sf = new Configuration().configure().buildSessionFactory();
Session s = sf.openSession();
s.beginTransaction();
String hql = "FROM table ";
org.hibernate.Query query = s.createQuery(hql);
libel= (ArrayList<table>) query.list();
Iterator it = libel.iterator();
while(it.hasNext()) {
table cat = (table) it.next();
cat.getLibCat();//table colonm getter
combobox.addItem(cat.getLibCat());
}
s.getTransaction().commit();
s.close();
sf.close();
} catch (Exception e) {
System.out.println("Exception in getSelectedData::"+e.getMessage());
【讨论】: