26

JComboBoxにArrayListを設定する必要があります。これを行う方法はありますか?

4

8 に答える 8

26

toArray()ArrayList クラスのメソッドを使用して、それをJComboBox

詳細については、JavaDocチュートリアルを参照してください。

于 2009-08-18T04:06:25.940 に答える
25

配列リストでコンボ ボックスを埋めるエレガントな方法:

List<String> ls = new ArrayList<String>(); 
jComboBox.setModel(new DefaultComboBoxModel<String>(ls.toArray(new String[0])));
于 2015-04-05T19:27:19.613 に答える
13

受け入れられた回答や、これを解決する方法に関する@fivetwentysixのコメントは好きではありません。これを行う方法は 1 つありますが、toArray を使用するための完全な解決策はありません。オブジェクト配列になってしまわないように、toArray を使用して、正しい型とサイズの配列である引数を与える必要があります。オブジェクト配列は機能しますが、厳密に型指定された言語でのベスト プラクティスではないと思います。

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);
于 2014-10-13T19:48:08.603 に答える
3

ArrayList を使用して新しい Vector を作成し、それを JCombobox コンストラクターに渡すことができると思います。

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

私の例は文字列だけです。

于 2015-04-30T21:44:25.963 に答える
1

既存の回答 ( this onethis one )を組み合わせることによりArrayList、 a に aを追加する適切な型安全な方法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);
于 2018-12-22T21:08:18.047 に答える
-5

それが解決策だと思います

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());
于 2014-03-27T14:16:01.553 に答える