如何使用ArrayList填充JComboBox?

我需要使用ArrayList填充JComboBox。 有没有办法做到这一点?

使用ArrayList类的toArray()方法并将其传递给JComboBox的构造函数

有关详细信息,请参阅JavaDoc和教程 。

数组列表填充combobox的优雅方法:

 List ls = new ArrayList(); jComboBox.setModel(new DefaultComboBoxModel(ls.toArray())); 

我不喜欢接受的答案或@ 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); 

我相信你可以使用你的ArrayList创建一个新的Vector并将其传递给JCombobox构造函数。

 JComboBox combobox = new JComboBox(new Vector(myArrayList)); 

我的例子只是字符串。

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

可理解的code.Edit <>根据需要。

检查这个简单的代码

 import java.util.ArrayList; import javax.swing.JComboBox; import javax.swing.JFrame; public class FirstFrame extends JFrame{ static JComboBox mycombo; FirstFrame() { this.setSize(600,500); this.setTitle("My combo"); this.setLayout(null); ArrayList names=new ArrayList(); 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(); } } 

备查:

 //first create the array; String[] comboBoxArray = {"item1","item2","item3"}; //create JComboBox and assign it to the comboBox JComboBox comboBox1 = new JComboBox(comboBoxArray); 

我认为这是解决方案

 ArrayList libel = new ArrayList
(); 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
) 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());