2009-08-18 121 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); 

易懂的代碼。編輯<>根據需要。