2009-08-18 119 views

回答

16

使用ArrayList类的toArray()方法,并将其传递到的JComboBox

构造见JavaDoctutorial获取更多信息。

+3

如果你正在做一些像ArrayList 。在你的Person类中,你可以定义toString()来调整ComboBox的值。另外,当使用ArrayList.toArray()时,你可能不得不声明你的数组变量为Object [](而不是String [])。 – fivetwentysix 2011-05-12 03:19:43

+1

在教程中没有示例与arraylist – Lobato 2015-01-09 20:29:11

0

以供将来参考:

//first create the array; 
String[] comboBoxArray = {"item1","item2","item3"}; 


//create JComboBox and assign it to the comboBox 
JComboBox comboBox1 = new JComboBox(comboBoxArray); 
+8

这根本不回答这个问题。他想知道如何使用ArrayList来完成,而不是使用原始类型数组。 – sage88 2014-10-13 19:21:45

-4

我认为这是解决

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()); 
+1

这令人难以置信的混淆。这个问题可以用2行代码解决,而不需要所有这些混乱。 – sage88 2014-10-13 19:53:30

6

我不喜欢关于如何解决这一公认的答案或@ 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); 
11

优雅的方式来填补组合框数组列表

List<String> ls = new ArrayList<String>(); 
jComboBox.setModel(new DefaultComboBoxModel(ls.toArray())); 
+1

我还没有试过这个,但是好像你最终会用一个Object数组填充jComboBox而不是使用这种方法的String数组。 – sage88 2016-06-03 02:16:54

2

我相信你可以使用ArrayList中创建一个新的载体,并传递到JComboBox中构造函数。

JComboBox<String> combobox = new JComboBox<String>(new Vector<String>(myArrayList)); 

我的例子只是字符串,虽然。

1
DefaultComboBoxModel DLM = new DefaultComboBoxModel(); 
    for (int i = 0; i < <ArrayList>.size(); i++) { 
     DLM.addElement(<ArrayList>.get(i).getField()); 
    } 

    <ComboBoxName>.setModel(DLM); 

易懂的代码。编辑<>根据需要。