简体   繁体   English

如何从ArrayList填充JComboBox?

[英]How to populate a JComboBox from an ArrayList?

I've got an ArrayList of objects, and all the objects have names. 我有一个对象的ArrayList,所有对象都有名称。 How can I populate a JComboBox with those names? 如何用这些名称填充JComboBox? I've looked online and found nothing so far. 我在网上看过,至今没有发现任何东西。 There are some resources, but they tend to go with a hardcoded version, which is useless. 有一些资源,但是它们倾向于使用无用的硬编码版本。

Since I don't have any code yet showing what I'm doing, I can't attach any. 由于我还没有任何代码可以显示自己的工作,因此无法附加任何代码。

JComboBox works with Array or Vector . JComboBoxArrayVector You should use .toArray() method in the ArrayList to create an array. 您应该在ArrayList使用.toArray()方法创建一个数组。

String[] names = namesList.toArray(new String[0]);

then use names 然后使用names

You can directly feed in the items at construction time: JComboBox cb = new JComboBox(yourArrayList.toArray()); 您可以在构造时直接输入项目: JComboBox cb = new JComboBox(yourArrayList.toArray()); (you might have to check type parametrisation here) (您可能需要在此处检查类型参数设置)

JComboBox has constructors for Array and Vector as input. JComboBox具有数组和向量的构造函数作为输入。 In your case it should be easier to convert to Array instead of converting to a Vector. 在您的情况下,转换为Array而不是转换为Vector应该更容易。

Or after initialization: 或初始化后:

for (String item : yourArrayList) {
    cb.addItem(item);
}

See http://docs.oracle.com/javase/7/docs/api/javax/swing/JComboBox.html 参见http://docs.oracle.com/javase/7/docs/api/javax/swing/JComboBox.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM